Programs & Examples On #Ipl

Intermec Printer Language

PHP array value passes to next row

Change the checkboxes so that the name includes the index inside the brackets:

<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>"> 

The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.

Microsoft Advertising SDK doesn't deliverer ads

I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.

Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled

Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is

  1. Remove the XAML for the ad
  2. Remove the xmlns declaration (usually at the top of the page, but sometimes will be declared in the ad itself)
  3. Remove the bad DLL (the one ending in .SDK )
  4. Do a Clean and then Build (clean out anything remaining from the DLL)
  5. Add the xmlns reference (actual reference is below)
  6. Add the ad to the page (example below)

Here is the xmlns reference:

xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI" 

Then the ad itself:

<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480"                    AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/> 

How to implement a simple scenario the OO way

The approach I would take is: when reading the chapters from the database, instead of a collection of chapters, use a collection of books. This will have your chapters organised into books and you'll be able to use information from both classes to present the information to the user (you can even present it in a hierarchical way easily when using this approach).

Method Call Chaining; returning a pointer vs a reference?

Since nullptr is never going to be returned, I recommend the reference approach. It more accurately represents how the return value will be used.

String index out of range: 4

You are using the wrong iteration counter, replace inp.charAt(i) with inp.charAt(j).

Passing multiple values for same variable in stored procedure

Your stored procedure is designed to accept a single parameter, Arg1List. You can't pass 4 parameters to a procedure that only accepts one.

To make it work, the code that calls your procedure will need to concatenate your parameters into a single string of no more than 3000 characters and pass it in as a single parameter.

Calling another method java GUI

I'm not sure what you're trying to do, but here's something to consider: c(); won't do anything. c is an instance of the class checkbox and not a method to be called. So consider this:

public class FirstWindow extends JFrame {      public FirstWindow() {         checkbox c = new checkbox();         c.yourMethod(yourParameters); // call the method you made in checkbox     } }  public class checkbox extends JFrame {      public checkbox(yourParameters) {          // this is the constructor method used to initialize instance variables     }      public void yourMethod() // doesn't have to be void     {         // put your code here     } } 

Java and unlimited decimal places?

I believe that you are looking for the java.lang.BigDecimal class.

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

Is it possible to execute multiple _addItem calls asynchronously using Google Analytics?

From the docs:

_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.

So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.

Edit: Further reading led me here:

http://www.analyticsmarket.com/blog/edit-ecommerce-data

Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.

Message: Trying to access array offset on value of type null

This happens because $cOTLdata is not null but the index 'char_data' does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.

To check whether the index exists or not you can use isset():

isset($cOTLdata['char_data'])

Which means the line should look something like this:

$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;

Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).

How to set value to form control in Reactive Forms in Angular

The "usual" solution is make a function that return an empty formGroup or a fullfilled formGroup

createFormGroup(data:any)
{
 return this.fb.group({
   user: [data?data.user:null],
   questioning: [data?data.questioning:null, Validators.required],
   questionType: [data?data.questionType, Validators.required],
   options: new FormArray([this.createArray(data?data.options:null])
})
}

//return an array of formGroup
createArray(data:any[]|null):FormGroup[]
{
   return data.map(x=>this.fb.group({
        ....
   })
}

then, in SUBSCRIBE, you call the function

this.qService.editQue([params["id"]]).subscribe(res => {
  this.editqueForm = this.createFormGroup(res);
});

be carefull!, your form must include an *ngIf to avoid initial error

<form *ngIf="editqueForm" [formGroup]="editqueForm">
   ....
</form>

Pandas Merging 101

This post will go through the following topics:

  • Merging with index under different conditions
    • options for index-based joins: merge, join, concat
    • merging on indexes
    • merging on index of one, column of other
  • effectively using named indexes to simplify merging syntax

BACK TO TOP



Index-based joins

TL;DR

There are a few options, some simpler than others depending on the use case.

  1. DataFrame.merge with left_index and right_index (or left_on and right_on using names indexes)
    • supports inner/left/right/full
    • can only join two at a time
    • supports column-column, index-column, index-index joins
  2. DataFrame.join (join on index)
    • supports inner/left (default)/right/full
    • can join multiple DataFrames at a time
    • supports index-index joins
  3. pd.concat (joins on index)
    • supports inner/full (default)
    • can join multiple DataFrames at a time
    • supports index-index joins

Index to index joins

Setup & Basics

import pandas as pd
import numpy as np

np.random.seed([3, 14])
left = pd.DataFrame(data={'value': np.random.randn(4)}, 
                    index=['A', 'B', 'C', 'D'])    
right = pd.DataFrame(data={'value': np.random.randn(4)},  
                     index=['B', 'D', 'E', 'F'])
left.index.name = right.index.name = 'idxkey'

left
           value
idxkey          
A      -0.602923
B      -0.402655
C       0.302329
D      -0.524349

right
 
           value
idxkey          
B       0.543843
D       0.013135
E      -0.326498
F       1.385076

Typically, an inner join on index would look like this:

left.merge(right, left_index=True, right_index=True)

         value_x   value_y
idxkey                    
B      -0.402655  0.543843
D      -0.524349  0.013135

Other joins follow similar syntax.

Notable Alternatives

  1. DataFrame.join defaults to joins on the index. DataFrame.join does a LEFT OUTER JOIN by default, so how='inner' is necessary here.

     left.join(right, how='inner', lsuffix='_x', rsuffix='_y')
    
              value_x   value_y
     idxkey                    
     B      -0.402655  0.543843
     D      -0.524349  0.013135
    

    Note that I needed to specify the lsuffix and rsuffix arguments since join would otherwise error out:

     left.join(right)
     ValueError: columns overlap but no suffix specified: Index(['value'], dtype='object')
    

    Since the column names are the same. This would not be a problem if they were differently named.

     left.rename(columns={'value':'leftvalue'}).join(right, how='inner')
    
             leftvalue     value
     idxkey                     
     B       -0.402655  0.543843
     D       -0.524349  0.013135
    
  2. pd.concat joins on the index and can join two or more DataFrames at once. It does a full outer join by default, so how='inner' is required here..

     pd.concat([left, right], axis=1, sort=False, join='inner')
    
                value     value
     idxkey                    
     B      -0.402655  0.543843
     D      -0.524349  0.013135
    

    For more information on concat, see this post.


Index to Column joins

To perform an inner join using index of left, column of right, you will use DataFrame.merge a combination of left_index=True and right_on=....

right2 = right.reset_index().rename({'idxkey' : 'colkey'}, axis=1)
right2
 
  colkey     value
0      B  0.543843
1      D  0.013135
2      E -0.326498
3      F  1.385076

left.merge(right2, left_index=True, right_on='colkey')

    value_x colkey   value_y
0 -0.402655      B  0.543843
1 -0.524349      D  0.013135

Other joins follow a similar structure. Note that only merge can perform index to column joins. You can join on multiple columns, provided the number of index levels on the left equals the number of columns on the right.

join and concat are not capable of mixed merges. You will need to set the index as a pre-step using DataFrame.set_index.


Effectively using Named Index [pandas >= 0.23]

If your index is named, then from pandas >= 0.23, DataFrame.merge allows you to specify the index name to on (or left_on and right_on as necessary).

left.merge(right, on='idxkey')

         value_x   value_y
idxkey                    
B      -0.402655  0.543843
D      -0.524349  0.013135

For the previous example of merging with the index of left, column of right, you can use left_on with the index name of left:

left.merge(right2, left_on='idxkey', right_on='colkey')

    value_x colkey   value_y
0 -0.402655      B  0.543843
1 -0.524349      D  0.013135


Continue Reading

Jump to other topics in Pandas Merging 101 to continue learning:

* you are here

Numpy, multiply array with scalar

Using .multiply() (ufunc multiply)

a_1 = np.array([1.0, 2.0, 3.0])
a_2 = np.array([[1., 2.], [3., 4.]])
b = 2.0 

np.multiply(a_1,b)
# array([2., 4., 6.])
np.multiply(a_2,b)
# array([[2., 4.],[6., 8.]])

How to compare oldValues and newValues on React Hooks useEffect?

If you prefer a useEffect replacement approach:

const usePreviousEffect = (fn, inputs = []) => {
  const previousInputsRef = useRef([...inputs])

  useEffect(() => {
    fn(previousInputsRef.current)
    previousInputsRef.current = [...inputs]
  }, inputs)
}

And use it like this:

usePreviousEffect(
  ([prevReceiveAmount, prevSendAmount]) => {
    if (prevReceiveAmount !== receiveAmount) // side effect here
    if (prevSendAmount !== sendAmount) // side effect here
  },
  [receiveAmount, sendAmount]
)

Note that the first time the effect executes, the previous values passed to your fn will be the same as your initial input values. This would only matter to you if you wanted to do something when a value did not change.

Android Material and appcompat Manifest merger failed

Follow these steps:

  • Goto Refactor and Click Migrate to AndroidX
  • Click Do Refactor

Bootstrap 4 multiselect dropdown

Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3

NOTE: this component only works in since version 1.13.0

_x000D_
_x000D_
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
  <option>Mustard</option>_x000D_
  <option>Ketchup</option>_x000D_
  <option>Relish</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Xcode 10 Error: Multiple commands produce

This answer is deprecated - XCode 12 has deprecated the Legacy Build System, it will be removed in a further release

I'm using XCode 11.4 Can't build old project

Xcode => File => Project Settings => Build System => Legacy Build System

enter image description here

enter image description here

Iterating through a list to render multiple widgets in Flutter?

You can use ListView to render a list of items. But if you don't want to use ListView, you can create a method which returns a list of Widgets (Texts in your case) like below:

var list = ["one", "two", "three", "four"];

    @override
    Widget build(BuildContext context) {
      return new MaterialApp(
          home: new Scaffold(
        appBar: new AppBar(
          title: new Text('List Test'),
        ),
        body: new Center(
          child: new Column( // Or Row or whatever :)
            children: createChildrenTexts(),
          ),
        ),
      ));
    }

     List<Text> createChildrenTexts() {
    /// Method 1
//    List<Text> childrenTexts = List<Text>();
//    for (String name in list) {
//      childrenTexts.add(new Text(name, style: new TextStyle(color: Colors.red),));
//    }
//    return childrenTexts;

    /// Method 2
    return list.map((text) => Text(text, style: TextStyle(color: Colors.blue),)).toList();
  }

what is an illegal reflective access

Apart from an understanding of the accesses amongst modules and their respective packages. I believe the crux of it lies in the Module System#Relaxed-strong-encapsulation and I would just cherry-pick the relevant parts of it to try and answer the question.

What defines an illegal reflective access and what circumstances trigger the warning?

To aid in the migration to Java-9, the strong encapsulation of the modules could be relaxed.

  • An implementation may provide static access, i.e. by compiled bytecode.

  • May provide a means to invoke its run-time system with one or more packages of one or more of its modules open to code in all unnamed modules, i.e. to code on the classpath. If the run-time system is invoked in this way, and if by doing so some invocations of the reflection APIs succeed where otherwise they would have failed.

In such cases, you've actually ended up making a reflective access which is "illegal" since in a pure modular world you were not meant to do such accesses.

How it all hangs together and what triggers the warning in what scenario?

This relaxation of the encapsulation is controlled at runtime by a new launcher option --illegal-access which by default in Java9 equals permit. The permit mode ensures

The first reflective-access operation to any such package causes a warning to be issued, but no warnings are issued after that point. This single warning describes how to enable further warnings. This warning cannot be suppressed.

The modes are configurable with values debug(message as well as stacktrace for every such access), warn(message for each such access), and deny(disables such operations).


Few things to debug and fix on applications would be:-

  • Run it with --illegal-access=deny to get to know about and avoid opening packages from one module to another without a module declaration including such a directive(opens) or explicit use of --add-opens VM arg.
  • Static references from compiled code to JDK-internal APIs could be identified using the jdeps tool with the --jdk-internals option

The warning message issued when an illegal reflective-access operation is detected has the following form:

WARNING: Illegal reflective access by $PERPETRATOR to $VICTIM

where:

$PERPETRATOR is the fully-qualified name of the type containing the code that invoked the reflective operation in question plus the code source (i.e., JAR-file path), if available, and

$VICTIM is a string that describes the member being accessed, including the fully-qualified name of the enclosing type

Questions for such a sample warning: = JDK9: An illegal reflective access operation has occurred. org.python.core.PySystemState

Last and an important note, while trying to ensure that you do not face such warnings and are future safe, all you need to do is ensure your modules are not making those illegal reflective accesses. :)

How to set environment via `ng serve` in Angular 6

This answer seems good.
however, it lead me towards an error as it resulted with
Configuration 'xyz' could not be found in project ...
error in build.
It is requierd not only to updated build configurations, but also serve ones.

So just to leave no confusions:

  1. --env is not supported in angular 6
  2. --env got changed into --configuration || -c (and is now more powerful)
  3. to manage various envs, in addition to adding new environment file, it is now required to do some changes in angular.json file:
    • add new configuration in the build { ... "build": "configurations": ... property
    • new build configuration may contain only fileReplacements part, (but more options are available)
    • add new configuration in the serve { ... "serve": "configurations": ... property
    • new serve configuration shall contain of browserTarget="your-project-name:build:staging"

Adding an .env file to React Project

  1. Install dotenv as devDependencies:
npm i --save-dev dotenv
  1. Create a .env file in the root directory:
my-react-app/
|- node-modules/
|- public/
|- src/
|- .env
|- .gitignore
|- package.json
|- package.lock.json.
|- README.md
  1. Update the .env file like below & REACT_APP_ is the compulsory prefix for the variable name.
REACT_APP_BASE_URL=http://localhost:8000
REACT_APP_API_KEY=YOUR-API-KEY
  1. [ Optional but Good Practice ] Now you can create a configuration file to store the variables and export the variable so can use it from others file.

For example, I've create a file named base.js and update it like below:

export const BASE_URL = process.env.REACT_APP_BASE_URL;
export const API_KEY = process.env.REACT_APP_API_KEY;
  1. Or you can simply just call the environment variable in your JS file in the following way:
process.env.REACT_APP_BASE_URL

Getting "TypeError: failed to fetch" when the request hasn't actually failed

If your are invoking fetch on a localhost server, use non-SSL unless you have a valid certificate for localhost. fetch will fail on an invalid or self signed certificate especially on localhost.

Pyspark: Filter dataframe based on multiple conditions

You can also write like below (without pyspark.sql.functions):

df.filter('d<5 and (col1 <> col3 or (col1 = col3 and col2 <> col4))').show()

Result:

+----+----+----+----+---+
|col1|col2|col3|col4|  d|
+----+----+----+----+---+
|   A|  xx|   D|  vv|  4|
|   A|   x|   A|  xx|  3|
|   E| xxx|   B|  vv|  3|
|   F|xxxx|   F| vvv|  4|
|   G| xxx|   G|  xx|  4|
+----+----+----+----+---+

How to set bot's status

Simple way to initiate the message on startup:

bot.on('ready', () => {
    bot.user.setStatus('available')
    bot.user.setPresence({
        game: {
            name: 'with depression',
            type: "STREAMING",
            url: "https://www.twitch.tv/monstercat"
        }
    });
});

You can also just declare it elsewhere after startup, to change the message as needed:

bot.user.setPresence({ game: { name: 'with depression', type: "streaming", url: "https://www.twitch.tv/monstercat"}}); 

Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support

Another possibility, is the machine has an older version of xlrd installed separately, and it's not in the "..:\Python27\Scripts.." folder.

In another word, there are 2 different versions of xlrd in the machine.

enter image description here

when you check the version below, it reads the one not in the "..:\Python27\Scripts.." folder, no matter how updated you done with pip.

print xlrd.__version__

Delete the whole redundant sub-folder, and it works. (in addition to xlrd, I had another library encountered the same)

How to shift a block of code left/right by one space in VSCode?

Have a look at File > Preferences > Keyboard Shortcuts (or Ctrl+K Ctrl+S)

Search for cursorColumnSelectDown or cursorColumnSelectUp which will give you the relevent keyboard shortcut. For me it is Shift+Alt+Down/Up Arrow

Is ConfigurationManager.AppSettings available in .NET Core 2.0?

I know it's a bit too late, but maybe someone is looking for easy way to access appsettings in .net core app. in API constructor add the following:

public class TargetClassController : ControllerBase
{
    private readonly IConfiguration _config;

    public TargetClassController(IConfiguration config)
    {
        _config = config;
    }

    [HttpGet("{id:int}")]
    public async Task<ActionResult<DTOResponse>> Get(int id)
    {
        var config = _config["YourKeySection:key"];
    }
}

No provider for HttpClient

In angular github page, this problem was discussed and found solution. https://github.com/angular/angular/issues/20355

How to clear react-native cache?

If you are using WebStorm, press configuration selection drop down button left of the run button and select edit configurations:

edit configurations

Double click on Start React Native Bundler at bottom in Before launch section:

before launch

Enter --reset-cache to Arguments section:

arguments

How to display multiple images in one figure correctly?

You could try the following:

import matplotlib.pyplot as plt
import numpy as np

def plot_figures(figures, nrows = 1, ncols=1):
    """Plot a dictionary of figures.

    Parameters
    ----------
    figures : <title, figure> dictionary
    ncols : number of columns of subplots wanted in the display
    nrows : number of rows of subplots wanted in the figure
    """

    fig, axeslist = plt.subplots(ncols=ncols, nrows=nrows)
    for ind,title in zip(range(len(figures)), figures):
        axeslist.ravel()[ind].imshow(figures[title], cmap=plt.jet())
        axeslist.ravel()[ind].set_title(title)
        axeslist.ravel()[ind].set_axis_off()
    plt.tight_layout() # optional



# generation of a dictionary of (title, images)
number_of_im = 20
w=10
h=10
figures = {'im'+str(i): np.random.randint(10, size=(h,w)) for i in range(number_of_im)}

# plot of the images in a figure, with 5 rows and 4 columns
plot_figures(figures, 5, 4)

plt.show()

However, this is basically just copy and paste from here: Multiple figures in a single window for which reason this post should be considered to be a duplicate.

I hope this helps.

LabelEncoder: TypeError: '>' not supported between instances of 'float' and 'str'

As string data types have variable length, it is by default stored as object type. I faced this problem after treating missing values too. Converting all those columns to type 'category' before label encoding worked in my case.

df[cat]=df[cat].astype('category')

And then check df.dtypes and perform label encoding.

Automatically set appsettings.json for dev and release environments in asp.net core?

  1. Create multiple appSettings.$(Configuration).json files like:

    • appSettings.staging.json
    • appSettings.production.json
  2. Create a pre-build event on the project which copies the respective file to appSettings.json:

    copy appSettings.$(Configuration).json appSettings.json
    
  3. Use only appSettings.json in your Config Builder:

    var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddEnvironmentVariables();
    
    Configuration = builder.Build();
    

Vuex - passing multiple parameters to mutation

Mutations expect two arguments: state and payload, where the current state of the store is passed by Vuex itself as the first argument and the second argument holds any parameters you need to pass.

The easiest way to pass a number of parameters is to destruct them:

mutations: {
    authenticate(state, { token, expiration }) {
        localStorage.setItem('token', token);
        localStorage.setItem('expiration', expiration);
    }
}

Then later on in your actions you can simply

store.commit('authenticate', {
    token,
    expiration,
});

npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself

For each error of the form:

npm WARN {something} requires a peer of {other thing} but none is installed. You must install peer dependencies yourself.

You should:

$ npm install --save-dev "{other thing}"

Note: The quotes are needed if the {other thing} has spaces, like in this example:

npm WARN [email protected] requires a peer of rollup@>=0.66.0 <2 but none was installed.

Resolved with:

$ npm install --save-dev "rollup@>=0.66.0 <2"

exporting multiple modules in react.js

When you

import App from './App.jsx';

That means it will import whatever you export default. You can rename App class inside App.jsx to whatever you want as long as you export default it will work but you can only have one export default.

So you only need to export default App and you don't need to export the rest.

If you still want to export the rest of the components, you will need named export.

https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export

Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App

If you need in different Layer :

Create a Static Class and expose all config properties on that layer as below :

_x000D_
_x000D_
using Microsoft.Extensions.Configuration;_x000D_
using System.IO;_x000D_
_x000D_
namespace Core.DAL_x000D_
{_x000D_
    public static class ConfigSettings_x000D_
    {_x000D_
        public static string conStr1 { get ; }_x000D_
        static ConfigSettings()_x000D_
        {_x000D_
            var configurationBuilder = new ConfigurationBuilder();_x000D_
            string path = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json");_x000D_
            configurationBuilder.AddJsonFile(path, false);_x000D_
            conStr1 = configurationBuilder.Build().GetSection("ConnectionStrings:ConStr1").Value;_x000D_
        }_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

Unable to create migrations after upgrading to ASP.NET Core 2.0

I had same problem. Just changed the ap.jason to application.jason and it fixed the issue

How to downgrade tensorflow, multiple versions possible?

If you are using python3 on windows then you might do this as well

pip3 install tensorflow==1.4

you may select any version from "(from versions: 1.2.0rc2, 1.2.0, 1.2.1, 1.3.0rc0, 1.3.0rc1, 1.3.0rc2, 1.3.0, 1.4.0rc0, 1.4.0rc1, 1.4.0, 1.5.0rc0, 1.5.0rc1, 1.5.0, 1.5.1, 1.6.0rc0, 1.6.0rc1, 1.6.0, 1.7.0rc0, 1.7.0rc1, 1.7.0)"

I did this when I wanted to downgrade from 1.7 to 1.4

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

At the latest Google Play Services 15.0.0, it occurs this error when you include entire play service like this

implementation 'com.google.android.gms:play-services:15.0.0'

Instead, you must specific the detail service like Google Drive

com.google.android.gms:play-services-drive:15.0.0

select rows in sql with latest date for each ID repeated multiple times

You can use a join to do this

SELECT t1.* from myTable t1
LEFT OUTER JOIN myTable t2 on t2.ID=t1.ID AND t2.`Date` > t1.`Date`
WHERE t2.`Date` IS NULL;

Only rows which have the latest date for each ID with have a NULL join to t2.

How to format JSON in notepad++

Here are the steps to install JSToolNPP plugin on your Notepad++.

  1. Download 64bit version from Sourceforge or the 32bit version if you are on a 32-bit OS.

    64bit - JSToolNPP.1.21.0.uni.64.zip: Download from SourceForget.net
    
  2. Notepad++ before installation

does not show JSTool in the Plugins menu.

  1. Unzip the downloaded JSToolNPP.1.21.0.uni.64 and copy the JSMinNPP.dll and place it under C:\Program Files\Notepad++\plugins.

  2. Close Notepad++ and reopen it. If you have downloaded an incompatible dll, then it will complain, else it will open successfully. If it complains about incompatibility, go back to STEP 1 and download the correct bit version as per your OS. Check Plugins in Notepad++.

JSTool is now located in the Plugins menu.

  1. Paste a sample unformatted but valid JSON data in Notepad++.

  2. Select all text in Notepad++ (CTRL+A) and format using Plugins -> JSTool -> JSFormat.

NOTE: On side note, if you do not want to install any plugins like this, I would recommend using the following 2 best online formatters.

Any difference between await Promise.all() and multiple await?

Note:

This answer just covers the timing differences between await in series and Promise.all. Be sure to read @mikep's comprehensive answer that also covers the more important differences in error handling.


For the purposes of this answer I will be using some example methods:

  • res(ms) is a function that takes an integer of milliseconds and returns a promise that resolves after that many milliseconds.
  • rej(ms) is a function that takes an integer of milliseconds and returns a promise that rejects after that many milliseconds.

Calling res starts the timer. Using Promise.all to wait for a handful of delays will resolve after all the delays have finished, but remember they execute at the same time:

Example #1
const data = await Promise.all([res(3000), res(2000), res(1000)])
//                              ^^^^^^^^^  ^^^^^^^^^  ^^^^^^^^^
//                               delay 1    delay 2    delay 3
//
// ms ------1---------2---------3
// =============================O delay 1
// ===================O           delay 2
// =========O                     delay 3
//
// =============================O Promise.all

_x000D_
_x000D_
async function example() {
  const start = Date.now()
  let i = 0
  function res(n) {
    const id = ++i
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve()
        console.log(`res #${id} called after ${n} milliseconds`, Date.now() - start)
      }, n)
    })
  }

  const data = await Promise.all([res(3000), res(2000), res(1000)])
  console.log(`Promise.all finished`, Date.now() - start)
}

example()
_x000D_
_x000D_
_x000D_

This means that Promise.all will resolve with the data from the inner promises after 3 seconds.

But, Promise.all has a "fail fast" behavior:

Example #2
const data = await Promise.all([res(3000), res(2000), rej(1000)])
//                              ^^^^^^^^^  ^^^^^^^^^  ^^^^^^^^^
//                               delay 1    delay 2    delay 3
//
// ms ------1---------2---------3
// =============================O delay 1
// ===================O           delay 2
// =========X                     delay 3
//
// =========X                     Promise.all

_x000D_
_x000D_
async function example() {
  const start = Date.now()
  let i = 0
  function res(n) {
    const id = ++i
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve()
        console.log(`res #${id} called after ${n} milliseconds`, Date.now() - start)
      }, n)
    })
  }
  
  function rej(n) {
    const id = ++i
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        reject()
        console.log(`rej #${id} called after ${n} milliseconds`, Date.now() - start)
      }, n)
    })
  }
  
  try {
    const data = await Promise.all([res(3000), res(2000), rej(1000)])
  } catch (error) {
    console.log(`Promise.all finished`, Date.now() - start)
  }
}

example()
_x000D_
_x000D_
_x000D_

If you use async-await instead, you will have to wait for each promise to resolve sequentially, which may not be as efficient:

Example #3
const delay1 = res(3000)
const delay2 = res(2000)
const delay3 = rej(1000)

const data1 = await delay1
const data2 = await delay2
const data3 = await delay3

// ms ------1---------2---------3
// =============================O delay 1
// ===================O           delay 2
// =========X                     delay 3
//
// =============================X await

_x000D_
_x000D_
async function example() {
  const start = Date.now()
  let i = 0
  function res(n) {
    const id = ++i
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve()
        console.log(`res #${id} called after ${n} milliseconds`, Date.now() - start)
      }, n)
    })
  }
  
  function rej(n) {
    const id = ++i
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        reject()
        console.log(`rej #${id} called after ${n} milliseconds`, Date.now() - start)
      }, n)
    })
  }
  
  try {
    const delay1 = res(3000)
    const delay2 = res(2000)
    const delay3 = rej(1000)

    const data1 = await delay1
    const data2 = await delay2
    const data3 = await delay3
  } catch (error) {
    console.log(`await finished`, Date.now() - start)
  }
}

example()
_x000D_
_x000D_
_x000D_

ESLint not working in VS Code?

I use Use Prettier Formatter and ESLint VS Code extension together for code linting and formating.

enter image description here

enter image description here

now install some packages using given command, if more packages required they will show with installation command as an error in the terminal for you, please install them also.

npm i eslint prettier eslint@^5.16.0 eslint-config-prettier eslint-plugin-prettier eslint-config-airbnb eslint-plugin-node eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react eslint-plugin-react-hooks@^2.5.0 --save-dev

now create a new file name .prettierrc in your project home directory, using this file you can configure settings of the prettier extension, my settings are below:

{
  "singleQuote": true
}

now as for the ESlint you can configure it according to your requirement, I am advising you to go Eslint website see the rules (https://eslint.org/docs/rules/)

Now create a file name .eslintrc.json in your project home directory, using that file you can configure eslint, my configurations are below:

{
  "extends": ["airbnb", "prettier", "plugin:node/recommended"],
  "plugins": ["prettier"],
  "rules": {
    "prettier/prettier": "error",
    "spaced-comment": "off",
    "no-console": "warn",
    "consistent-return": "off",
    "func-names": "off",
    "object-shorthand": "off",
    "no-process-exit": "off",
    "no-param-reassign": "off",
    "no-return-await": "off",
    "no-underscore-dangle": "off",
    "class-methods-use-this": "off",
    "prefer-destructuring": ["error", { "object": true, "array": false }],
    "no-unused-vars": ["error", { "argsIgnorePattern": "req|res|next|val" }]
  }
}

Vue js error: Component template should contain exactly one root element

Note This answer only applies to version 2.x of Vue. Version 3 has lifted this restriction.

You have two root elements in your template.

<div class="form-group">
  ...
</div>
<div class="col-md-6">
  ...
</div>

And you need one.

<div>
    <div class="form-group">
      ...
    </div>

    <div class="col-md-6">
      ...
    </div>
</div>

Essentially in Vue you must have only one root element in your templates.

Multiple conditions in ngClass - Angular 4

you need object notation

<section [ngClass]="{'class1':condition1, 'class2': condition2, 'class3':condition3}" > 

ref: NgClass

EF Core add-migration Build Failed

Try these steps:

  1. Clean the solution.

  2. Build every project separately.

  3. Resolve any errors if found (sometimes, VS is not showing errors until you build it separately).

  4. Then try to run migration again.

Flutter - Wrap text on overflow, like insert ellipsis or fade

You can do it like that

Expanded(
   child: Text(
   'Text',
   overflow: TextOverflow.ellipsis,
   maxLines: 1
   )
)

Angular 2 'component' is not a known element

Route modules (did not saw this as an answer)

First check: if you have declared- and exported the component inside its module, imported the module where you want to use it and named the component correctly inside the HTML.

Otherwise, you might miss a module inside your routing module:
When you have a routing module with a route that routes to a component from another module, it is important that you import that module within that route module. Otherwise the Angular CLI will show the error: component is not a known element.

For example

1) Having the following project structure:

+---core
¦   +---sidebar
¦           sidebar.component.ts
¦           sidebar.module.ts
¦
+---todos
    ¦   todos-routing.module.ts
    ¦   todos.module.ts
    ¦
    +---pages
            edit-todo.component.ts
            edit-todo.module.ts

2) Inside the todos-routing.module.ts you have a route to the edit.todo.component.ts (without importing its module):

  {
    path: 'edit-todo/:todoId',
    component: EditTodoComponent,
  },

The route will just work fine! However when importing the sidebar.module.ts inside the edit-todo.module.ts you will get an error: app-sidebar is not a known element.

Fix: Since you have added a route to the edit-todo.component.ts in step 2, you will have to add the edit-todo.module.ts as an import, after that the imported sidebar component will work!

Python: pandas merge multiple dataframes

Thank you for your help @jezrael, @zipa and @everestial007, both answers are what I need. If I wanted to make a recursive, this would also work as intended:

def mergefiles(dfs=[], on=''):
    """Merge a list of files based on one column"""
    if len(dfs) == 1:
         return "List only have one element."

    elif len(dfs) == 2:
        df1 = dfs[0]
        df2 = dfs[1]
        df = df1.merge(df2, on=on)
        return df

    # Merge the first and second datafranes into new dataframe
    df1 = dfs[0]
    df2 = dfs[1]
    df = dfs[0].merge(dfs[1], on=on)

    # Create new list with merged dataframe
    dfl = []
    dfl.append(df)

    # Join lists
    dfl = dfl + dfs[2:] 
    dfm = mergefiles(dfl, on)
    return dfm

How do I change the font color in an html table?

Try this:

 <html>
    <head>
        <style>
            select {
              height: 30px;
              color: #0000ff;
            }
        </style>
    </head>
    <body>
        <table>
            <tbody>
                <tr>
                    <td>
                        <select name="test">
                            <option value="Basic">Basic : $30.00 USD - yearly</option>
                            <option value="Sustaining">Sustaining : $60.00 USD - yearly</option>
                            <option value="Supporting">Supporting : $120.00 USD - yearly</option>
                        </select>
                    </td>
                </tr>
            </tbody>
        </table>
    </body>
</html>

Try-catch block in Jenkins pipeline script

try/catch is scripted syntax. So any time you are using declarative syntax to use something from scripted in general you can do so by enclosing the scripted syntax in the scripts block in a declarative pipeline. So your try/catch should go inside stage >steps >script.

This holds true for any other scripted pipeline syntax you would like to use in a declarative pipeline as well.

*ngIf else if in template

you don't need to use *ngIf if you use ng-container

<ng-container [ngTemplateOutlet]="myTemplate === 'first' ? first : myTemplate === 
   'second' ? second : third"></ng-container>

  <ng-template #first>first</ng-template>
  <ng-template #second>second</ng-template>
  <ng-template #third>third</ng-template>

angular 4: *ngIf with multiple conditions

<div *ngIf="currentStatus !== ('status1' || 'status2' || 'status3' || 'status4')">

re.sub erroring with "Expected string or bytes-like object"

I suppose better would be to use re.match() function. here is an example which may help you.

import re
import nltk
from nltk.tokenize import word_tokenize
nltk.download('punkt')
sentences = word_tokenize("I love to learn NLP \n 'a :(")
#for i in range(len(sentences)):
sentences = [word.lower() for word in sentences if re.match('^[a-zA-Z]+', word)]  
sentences

Error: Cannot match any routes. URL Segment: - Angular 2

Solved myself. Done some small structural changes also. Route from Component1 to Component2 is done by a single <router-outlet>. Component2 to Comonent3 and Component4 is done by multiple <router-outlet name= "xxxxx"> The resulting contents are :

Component1.html

<nav>
    <a routerLink="/two" class="dash-item">Go to 2</a>
</nav>
    <router-outlet></router-outlet>

Component2.html

 <a [routerLink]="['/two', {outlets: {'nameThree': ['three']}}]">In Two...Go to 3 ...       </a>
 <a [routerLink]="['/two', {outlets: {'nameFour': ['four']}}]">   In Two...Go to 4 ...</a>

 <router-outlet name="nameThree"></router-outlet>
 <router-outlet name="nameFour"></router-outlet>

The '/two' represents the parent component and ['three']and ['four'] represents the link to the respective children of component2 . Component3.html and Component4.html are the same as in the question.

router.module.ts

const routes: Routes = [
{
    path: '',
    redirectTo: 'one',
    pathMatch: 'full'
},
{
    path: 'two',
    component: ClassTwo, children: [

        {
            path: 'three',
            component: ClassThree,
            outlet: 'nameThree'
        },
        {
            path: 'four',
            component: ClassFour,
            outlet: 'nameFour'
        }
    ]
},];

Jenkins pipeline if else not working

your first try is using declarative pipelines, and the second working one is using scripted pipelines. you need to enclose steps in a steps declaration, and you can't use if as a top-level step in declarative, so you need to wrap it in a script step. here's a working declarative version:

pipeline {
    agent any

    stages {
        stage('test') {
            steps {
                sh 'echo hello'
            }
        }
        stage('test1') {
            steps {
                sh 'echo $TEST'
            }
        }
        stage('test3') {
            steps {
                script {
                    if (env.BRANCH_NAME == 'master') {
                        echo 'I only execute on the master branch'
                    } else {
                        echo 'I execute elsewhere'
                    }
                }
            }
        }
    }
}

you can simplify this and potentially avoid the if statement (as long as you don't need the else) by using "when". See "when directive" at https://jenkins.io/doc/book/pipeline/syntax/. you can also validate jenkinsfiles using the jenkins rest api. it's super sweet. have fun with declarative pipelines in jenkins!

What is HTTP "Host" header?

The Host Header tells the webserver which virtual host to use (if set up). You can even have the same virtual host using several aliases (= domains and wildcard-domains). In this case, you still have the possibility to read that header manually in your web app if you want to provide different behavior based on different domains addressed. This is possible because in your webserver you can (and if I'm not mistaken you must) set up one vhost to be the default host. This default vhost is used whenever the host header does not match any of the configured virtual hosts.

That means: You get it right, although saying "multiple hosts" may be somewhat misleading: The host (the addressed machine) is the same, what really gets resolved to the IP address are different domain names (including subdomains) that are also referred to as hostnames (but not hosts!).


Although not part of the question, a fun fact: This specification led to problems with SSL in early days because the web server has to deliver the certificate that corresponds to the domain the client has addressed. However, in order to know what certificate to use, the webserver should have known the addressed hostname in advance. But because the client sends that information only over the encrypted channel (which means: after the certificate has already been sent), the server had to assume you browsed the default host. That meant one ssl-secured domain per IP address / port-combination.

This has been overcome with Server Name Indication; however, that again breaks some privacy, as the server name is now transferred in plain text again, so every man-in-the-middle would see which hostname you are trying to connect to.

Although the webserver would know the hostname from Server Name Indication, the Host header is not obsolete, because the Server Name Indication information is only used within the TLS handshake. With an unsecured connection, there is no Server Name Indication at all, so the Host header is still valid (and necessary).

Another fun fact: Most webservers (if not all) reject your HTTP request if it does not contain exactly one Host header, even if it could be omitted because there is only the default vhost configured. That means the minimum required information in an http-(get-)request is the first line containing METHOD RESOURCE and PROTOCOL VERSION and at least the Host header, like this:

GET /someresource.html HTTP/1.1
Host: www.example.com

In the MDN Documentation on the "Host" header they actually phrase it like this:

A Host header field must be sent in all HTTP/1.1 request messages. A 400 (Bad Request) status code will be sent to any HTTP/1.1 request message that lacks a Host header field or contains more than one.

As mentioned by Darrel Miller, the complete specs can be found in RFC7230.

Add Legend to Seaborn point plot

I would suggest not to use seaborn pointplot for plotting. This makes things unnecessarily complicated.
Instead use matplotlib plot_date. This allows to set labels to the plots and have them automatically put into a legend with ax.legend().

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np

date = pd.date_range("2017-03", freq="M", periods=15)
count = np.random.rand(15,4)
df1 = pd.DataFrame({"date":date, "count" : count[:,0]})
df2 = pd.DataFrame({"date":date, "count" : count[:,1]+0.7})
df3 = pd.DataFrame({"date":date, "count" : count[:,2]+2})

f, ax = plt.subplots(1, 1)
x_col='date'
y_col = 'count'

ax.plot_date(df1.date, df1["count"], color="blue", label="A", linestyle="-")
ax.plot_date(df2.date, df2["count"], color="red", label="B", linestyle="-")
ax.plot_date(df3.date, df3["count"], color="green", label="C", linestyle="-")

ax.legend()

plt.gcf().autofmt_xdate()
plt.show()

enter image description here


In case one is still interested in obtaining the legend for pointplots, here a way to go:

sns.pointplot(ax=ax,x=x_col,y=y_col,data=df1,color='blue')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df2,color='green')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df3,color='red')

ax.legend(handles=ax.lines[::len(df1)+1], labels=["A","B","C"])

ax.set_xticklabels([t.get_text().split("T")[0] for t in ax.get_xticklabels()])
plt.gcf().autofmt_xdate()

plt.show()

MySql ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Try this (on Windows, i don't know how in others), if you have changed password a now don't work.

1) kill mysql 2) back up /mysql/data folder 3) go to folder /mysql/backup 4) copy files from /mysql/backup/mysql folder to /mysql/data/mysql (rewrite) 5) run mysql

In my XAMPP on Win7 it works.

WinError 2 The system cannot find the file specified (Python)

thank you, your first error guides me here and the solution solve mine too!

for permission error, f = open('output', 'w+'), change it into f = open(output+'output', 'w+').

or something else, but the way you are now using is having access to the installation directory of Python which normally in Program Files, and it probably needs administrator permission.

for sure, you could probably running python/your script as administrator to pass permission error though

How to set and reference a variable in a Jenkinsfile

A complete example for scripted pipepline:

       stage('Build'){
            withEnv(["GOPATH=/ws","PATH=/ws/bin:${env.PATH}"]) {
                sh 'bash build.sh'
            }
        }

How does the "view" method work in PyTorch?

What is the meaning of parameter -1?

You can read -1 as dynamic number of parameters or "anything". Because of that there can be only one parameter -1 in view().

If you ask x.view(-1,1) this will output tensor shape [anything, 1] depending on the number of elements in x. For example:

import torch
x = torch.tensor([1, 2, 3, 4])
print(x,x.shape)
print("...")
print(x.view(-1,1), x.view(-1,1).shape)
print(x.view(1,-1), x.view(1,-1).shape)

Will output:

tensor([1, 2, 3, 4]) torch.Size([4])
...
tensor([[1],
        [2],
        [3],
        [4]]) torch.Size([4, 1])
tensor([[1, 2, 3, 4]]) torch.Size([1, 4])

Cannot invoke an expression whose type lacks a call signature

TypeScript supports structural typing (also called duck typing), meaning that types are compatible when they share the same members. Your problem is that Apple and Pear don't share all their members, which means that they are not compatible. They are however compatible to another type that has only the isDecayed: boolean member. Because of structural typing, you don' need to inherit Apple and Pear from such an interface.

There are different ways to assign such a compatible type:

Assign type during variable declaration

This statement is implicitly typed to Apple[] | Pear[]:

const fruits = fruitBasket[key];

You can simply use a compatible type explicitly in in your variable declaration:

const fruits: { isDecayed: boolean }[] = fruitBasket[key];

For additional reusability, you can also define the type first and then use it in your declaration (note that the Apple and Pear interfaces don't need to be changed):

type Fruit = { isDecayed: boolean };
const fruits: Fruit[] = fruitBasket[key];

Cast to compatible type for the operation

The problem with the given solution is that it changes the type of the fruits variable. This might not be what you want. To avoid this, you can narrow the array down to a compatible type before the operation and then set the type back to the same type as fruits:

const fruits: fruitBasket[key];
const freshFruits = (fruits as { isDecayed: boolean }[]).filter(fruit => !fruit.isDecayed) as typeof fruits;

Or with the reusable Fruit type:

type Fruit = { isDecayed: boolean };
const fruits: fruitBasket[key];
const freshFruits = (fruits as Fruit[]).filter(fruit => !fruit.isDecayed) as typeof fruits;

The advantage of this solution is that both, fruits and freshFruits will be of type Apple[] | Pear[].

docker build with --build-arg with multiple arguments

If you want to use environment variable during build. Lets say setting username and password.

username= Ubuntu
password= swed24sw

Dockerfile

FROM ubuntu:16.04
ARG SMB_PASS
ARG SMB_USER
# Creates a new User
RUN useradd -ms /bin/bash $SMB_USER
# Enters the password twice.
RUN echo "$SMB_PASS\n$SMB_PASS" | smbpasswd -a $SMB_USER

Terminal Command

docker build --build-arg SMB_PASS=swed24sw --build-arg SMB_USER=Ubuntu . -t IMAGE_TAG

matplotlib: plot multiple columns of pandas data frame on the bar chart

Although the accepted answer works fine, since v0.21.0rc1 it gives a warning

UserWarning: Pandas doesn't allow columns to be created via a new attribute name

Instead, one can do

df[["X", "A", "B", "C"]].plot(x="X", kind="bar")

ReactJs: What should the PropTypes be for this.props.children?

For me it depends on the component. If you know what you need it to be populated with then you should try to specify exclusively, or multiple types using:

PropTypes.oneOfType 

If you want to refer to a React component then you will be looking for

PropTypes.element

Although,

PropTypes.node

describes anything that can be rendered - strings, numbers, elements or an array of these things. If this suits you then this is the way.

With very generic components, who can have many types of children, you can also use the below - though bare in mind that eslint and ts may not be happy with this lack of specificity:

PropTypes.any

How to create multiple page app using react

(Make sure to install react-router using npm!)

To use react-router, you do the following:

  1. Create a file with routes defined using Route, IndexRoute components

  2. Inject the Router (with 'r'!) component as the top-level component for your app, passing the routes defined in the routes file and a type of history (hashHistory, browserHistory)

  3. Add {this.props.children} to make sure new pages will be rendered there
  4. Use the Link component to change pages

Step 1 routes.js

import React from 'react';
import { Route, IndexRoute } from 'react-router';

/**
 * Import all page components here
 */
import App from './components/App';
import MainPage from './components/MainPage';
import SomePage from './components/SomePage';
import SomeOtherPage from './components/SomeOtherPage';

/**
 * All routes go here.
 * Don't forget to import the components above after adding new route.
 */
export default (
  <Route path="/" component={App}>
    <IndexRoute component={MainPage} />
    <Route path="/some/where" component={SomePage} />
    <Route path="/some/otherpage" component={SomeOtherPage} />
  </Route>
);

Step 2 entry point (where you do your DOM injection)

// You can choose your kind of history here (e.g. browserHistory)
import { Router, hashHistory as history } from 'react-router';
// Your routes.js file
import routes from './routes';

ReactDOM.render(
  <Router routes={routes} history={history} />,
  document.getElementById('your-app')
);

Step 3 The App component (props.children)

In the render for your App component, add {this.props.children}:

render() {
  return (
    <div>
      <header>
        This is my website!
      </header>

      <main>
        {this.props.children}
      </main>

      <footer>
        Your copyright message
      </footer>
    </div>
  );
}

Step 4 Use Link for navigation

Anywhere in your component render function's return JSX value, use the Link component:

import { Link } from 'react-router';
(...)
<Link to="/some/where">Click me</Link>

Remove all items from a FormArray in Angular

Angular 8

simply use clear() method on formArrays :

(this.invoiceForm.controls['other_Partners'] as FormArray).clear();

pandas: merge (join) two data frames on multiple columns

Try this

new_df = pd.merge(A_df, B_df,  how='left', left_on=['A_c1','c2'], right_on = ['B_c1','c2'])

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html

left_on : label or list, or array-like Field names to join on in left DataFrame. Can be a vector or list of vectors of the length of the DataFrame to use a particular vector as the join key instead of columns

right_on : label or list, or array-like Field names to join on in right DataFrame or vector/list of vectors per left_on docs

Get total of Pandas column

As other option, you can do something like below

Group   Valuation   amount
    0   BKB Tube    156
    1   BKB Tube    143
    2   BKB Tube    67
    3   BAC Tube    176
    4   BAC Tube    39
    5   JDK Tube    75
    6   JDK Tube    35
    7   JDK Tube    155
    8   ETH Tube    38
    9   ETH Tube    56

Below script, you can use for above data

import pandas as pd    
data = pd.read_csv("daata1.csv")
bytreatment = data.groupby('Group')
bytreatment['amount'].sum()

How to reload the current route with the angular 2 router

On param change reload page won't happen. This is really good feature. There is no need to reload the page but we should change the value of the component. paramChange method will call on url change. So we can update the component data

/product/: id / details

import { ActivatedRoute, Params, Router } from ‘@angular/router’;

export class ProductDetailsComponent implements OnInit {

constructor(private route: ActivatedRoute, private router: Router) {
    this.route.params.subscribe(params => {
        this.paramsChange(params.id);
    });
}

// Call this method on page change

ngOnInit() {

}

// Call this method on change of the param
paramsChange(id) {

}

YouTube Autoplay not working

Remove the spaces before the autoplay=1:

src="https://www.youtube.com/embed/-SFcIUEvNOQ?autoplay=1&;enablejsapi=1"

Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)

You should set your RecyclerView LayoutManager to Gridlayout mode. Just change your code when you want to set your RecyclerView LayoutManager:

recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), numberOfColumns));

Git merge with force overwrite

When I tried using -X theirs and other related command switches I kept getting a merge commit. I probably wasn't understanding it correctly. One easy to understand alternative is just to delete the branch then track it again.

git branch -D <branch-name>
git branch --track <branch-name> origin/<branch-name>

This isn't exactly a "merge", but this is what I was looking for when I came across this question. In my case I wanted to pull changes from a remote branch that were force pushed.

How to change the integrated terminal in visual studio code or VSCode

It is possible to get this working in VS Code and have the Cmder terminal be integrated (not pop up).

To do so:

  1. Create an environment variable "CMDER_ROOT" pointing to your Cmder directory.
  2. In (Preferences > User Settings) in VS Code add the following settings:

"terminal.integrated.shell.windows": "cmd.exe"

"terminal.integrated.shellArgs.windows": ["/k", "%CMDER_ROOT%\\vendor\\init.bat"]

Joining Spark dataframes on the key

Posting a java based solution, incase your team only uses java. The keyword inner will ensure that matching rows only are present in the final dataframe.

            Dataset<Row> joined = PersonDf.join(ProfileDf, 
                    PersonDf.col("personId").equalTo(ProfileDf.col("personId")),
                    "inner");
            joined.show();

JUnit 5: How to assert an exception is thrown?

They've changed it in JUnit 5 (expected: InvalidArgumentException, actual: invoked method) and code looks like this one:

@Test
public void wrongInput() {
    Throwable exception = assertThrows(InvalidArgumentException.class,
            ()->{objectName.yourMethod("WRONG");} );
}

Disable nginx cache for JavaScript files

The expires and add_header directives have no impact on NGINX caching the files, those are purely about what the browser sees.

What you likely want instead is:

location stuffyoudontwanttocache {
    # don't cache it
    proxy_no_cache 1;
    # even if cached, don't try to use it
    proxy_cache_bypass 1; 
}

Though usually .js etc is the thing you would cache, so perhaps you should just disable caching entirely?

How to do multiline shell script in Ansible

I prefer this syntax as it allows to set configuration parameters for the shell:

---
- name: an example
  shell:
    cmd: |
      docker build -t current_dir .
      echo "Hello World"
      date

    chdir: /home/vagrant/

Using OR operator in a jquery if statement

The logical OR '||' automatically short circuits if it meets a true condition once.

false || false || true || false = true, stops at second condition.

On the other hand, the logical AND '&&' automatically short circuits if it meets a false condition once.

false && true && true && true = false, stops at first condition.

Access multiple viewchildren using @viewchild

Use @ViewChildren from @angular/core to get a reference to the components

template

<div *ngFor="let v of views">
    <customcomponent #cmp></customcomponent>
</div>

component

import { ViewChildren, QueryList } from '@angular/core';

/** Get handle on cmp tags in the template */
@ViewChildren('cmp') components:QueryList<CustomComponent>;

ngAfterViewInit(){
    // print array of CustomComponent objects
    console.log(this.components.toArray());
}

l?i?v?e? ?d?e?m?o?

What's the difference between an Angular component and module

enter image description here

Simplest Explanation:

Module is like a big container containing one or many small containers called Component, Service, Pipe

A Component contains :

  • HTML template or HTML code

  • Code(TypeScript)

  • Service: It is a reusable code that is shared by the Components so that rewriting of code is not required

  • Pipe: It takes in data as input and transforms it to the desired output

Reference: https://scrimba.com/

How to get element-wise matrix multiplication (Hadamard product) in numpy?

For elementwise multiplication of matrix objects, you can use numpy.multiply:

import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
np.multiply(a,b)

Result

array([[ 5, 12],
       [21, 32]])

However, you should really use array instead of matrix. matrix objects have all sorts of horrible incompatibilities with regular ndarrays. With ndarrays, you can just use * for elementwise multiplication:

a * b

If you're on Python 3.5+, you don't even lose the ability to perform matrix multiplication with an operator, because @ does matrix multiplication now:

a @ b  # matrix multiplication

Jenkins: Cannot define variable in pipeline stage

The Declarative model for Jenkins Pipelines has a restricted subset of syntax that it allows in the stage blocks - see the syntax guide for more info. You can bypass that restriction by wrapping your steps in a script { ... } block, but as a result, you'll lose validation of syntax, parameters, etc within the script block.

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays

i have the same problem. this is how i fixed the problem. first when the error is occurred, my array data is coming form DB like this --,

{brands: Array(5), _id: "5ae9455f7f7af749cb2d3740"} 

make sure that your data is an ARRAY, not an OBJECT that carries an array. only array look like this --,

(5) [{…}, {…}, {…}, {…}, {…}]

it solved my problem.

Conda environments not showing up in Jupyter Notebook

I had similar issue and I found a solution that is working for Mac, Windows and Linux. It takes few key ingredients that are in the answer above:

To be able to see conda env in Jupyter notebook, you need:

  • the following package in you base env:
    conda install nb_conda

  • the following package in each env you create:
    conda install ipykernel

  • check the configurationn of jupyter_notebook_config.py
    first check if you have a jupyter_notebook_config.py in one of the location given by jupyter --paths
    if it doesn't exist, create it by running jupyter notebook --generate-config
    add or be sure you have the following: c.NotebookApp.kernel_spec_manager_class='nb_conda_kernels.manager.CondaKernelSpecManager'

The env you can see in your terminal: enter image description here

On Jupyter Lab you can see the same env as above both the Notebook and Console: enter image description here

And you can choose your env when have a notebook open: enter image description here

The safe way is to create a specific env from which you will run your example of envjupyter lab command. Activate your env. Then add jupyter lab extension example jupyter lab extension. Then you can run jupyter lab

R multiple conditions in if statement

Read this thread R - boolean operators && and ||.

Basically, the & is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. && is not, returning a single logical.

Sublime text 3. How to edit multiple lines?

Use CTRL+D at each line and it will find the matching words and select them then you can use multiple cursors.

You can also use find to find all the occurrences and then it would be multiple cursors too.

How does Python return multiple values from a function?

From Python Cookbook v.30

def myfun():
    return 1, 2, 3

a, b, c = myfun()

Although it looks like myfun() returns multiple values, a tuple is actually being created. It looks a bit peculiar, but it’s actually the comma that forms a tuple, not the parentheses

So yes, what's going on in Python is an internal transformation from multiple comma separated values to a tuple and vice-versa.

Though there's no equivalent in you can easily create this behaviour using array's or some Collections like Lists:

private static int[] sumAndRest(int x, int y) {
    int[] toReturn = new int[2];

    toReturn[0] = x + y;
    toReturn[1] = x - y;

    return toReturn;

}

Executed in this way:

public static void main(String[] args) {
    int[] results = sumAndRest(10, 5);

    int sum  = results[0];
    int rest = results[1];

    System.out.println("sum = " + sum + "\nrest = " + rest);

}

result:

sum = 15
rest = 5

How to convert JSON object to an Typescript array?

You have a JSON object that contains an Array. You need to access the array results. Change your code to:

this.data = res.json().results

How do I increase the contrast of an image in Python OpenCV

Brightness and contrast can be adjusted using alpha (a) and beta (ß), respectively. The expression can be written as

enter image description here

OpenCV already implements this as cv2.convertScaleAbs(), just provide user defined alpha and beta values

import cv2

image = cv2.imread('1.jpg')

alpha = 1.5 # Contrast control (1.0-3.0)
beta = 0 # Brightness control (0-100)

adjusted = cv2.convertScaleAbs(image, alpha=alpha, beta=beta)

cv2.imshow('original', image)
cv2.imshow('adjusted', adjusted)
cv2.waitKey()

Before -> After

enter image description here enter image description here

Note: For automatic brightness/contrast adjustment take a look at automatic contrast and brightness adjustment of a color photo

How to concatenate multiple column values into a single column in Panda dataframe

df['New_column_name'] = df['Column1'].map(str) + 'X' + df['Steps']

X= x is any delimiter (eg: space) by which you want to separate two merged column.

Split Spark Dataframe string column into multiple columns

Here's another approach, in case you want split a string with a delimiter.

import pyspark.sql.functions as f

df = spark.createDataFrame([("1:a:2001",),("2:b:2002",),("3:c:2003",)],["value"])
df.show()
+--------+
|   value|
+--------+
|1:a:2001|
|2:b:2002|
|3:c:2003|
+--------+

df_split = df.select(f.split(df.value,":")).rdd.flatMap(
              lambda x: x).toDF(schema=["col1","col2","col3"])

df_split.show()
+----+----+----+
|col1|col2|col3|
+----+----+----+
|   1|   a|2001|
|   2|   b|2002|
|   3|   c|2003|
+----+----+----+

I don't think this transition back and forth to RDDs is going to slow you down... Also don't worry about last schema specification: it's optional, you can avoid it generalizing the solution to data with unknown column size.

How to register multiple implementations of the same interface in Asp.Net Core?

I think the solution described in the following article "Resolución dinámica de tipos en tiempo de ejecución en el contenedor de IoC de .NET Core" is simpler and does not require factories.

You could use a generic interface

public interface IService<T> where T : class {}

then register the desired types on the IoC container:

services.AddTransient<IService<ServiceA>, ServiceA>();
services.AddTransient<IService<ServiceB>, ServiceB>();

After that you must declare the dependencies as follow:

private readonly IService<ServiceA> _serviceA;
private readonly IService<ServiceB> _serviceB;

public WindowManager(IService<ServiceA> serviceA, IService<ServiceB> serviceB)
{
    this._serviceA = serviceA ?? throw new ArgumentNullException(nameof(serviceA));
    this._serviceB = serviceB ?? throw new ArgumentNullException(nameof(ServiceB));
}

How to read connection string in .NET Core?

i have a data access library which works with both .net core and .net framework.

the trick was in .net core projects to keep the connection strings in a xml file named "app.config" (also for web projects), and mark it as 'copy to output directory',

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="conn1" connectionString="...." providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

ConfigurationManager.ConnectionStrings - will read the connection string.

    var conn1 = ConfigurationManager.ConnectionStrings["conn1"].ConnectionString;

How to add multiple columns to pandas dataframe in one assignment?

if adding a lot of missing columns (a, b, c ,....) with the same value, here 0, i did this:

    new_cols = ["a", "b", "c" ] 
    df[new_cols] = pd.DataFrame([[0] * len(new_cols)], index=df.index)

It's based on the second variant of the accepted answer.

docker entrypoint running bash script gets "permission denied"

I faced same issue & it resolved by

ENTRYPOINT ["sh", "/docker-entrypoint.sh"]

For the Dockerfile in the original question it should be like:

ENTRYPOINT ["sh", "/usr/src/app/docker-entrypoint.sh"]

How to pass multiple parameter to @Directives (@Components) in Angular with TypeScript?

Similar to the above solutions I used @Input() in a directive and able to pass multiple arrays of values in the directive.

selector: '[selectorHere]',

@Input() options: any = {};

Input.html

<input selectorHere [options]="selectorArray" />

Array from TS file

selectorArray= {
  align: 'left',
  prefix: '$',
  thousands: ',',
  decimal: '.',
  precision: 2
};

How to fix error Base table or view not found: 1146 Table laravel relationship table?

This problem occur due to wrong spell or undefined database name. Make sure your database name, table name and all column name is same as from phpmyadmin

How to call multiple functions with @click in vue?

I'd add, that you can also use this to call multiple emits or methods or both together by separating with ; semicolon

  @click="method1(); $emit('emit1'); $emit('emit2');"

Convert a string to datetime in PowerShell

$invoice = "Jul-16"
[datetime]$newInvoice = "01-" + $invoice

$newInvoice.ToString("yyyy-MM-dd")

There you go, use a type accelerator, but also into a new var, if you want to use it elsewhere, use it like so: $newInvoice.ToString("yyyy-MM-dd")as $newInvoice will always be in the datetime format, unless you cast it as a string afterwards, but will lose the ability to perform datetime functions - adding days etc...

Node.js heap out of memory

Just in case anyone runs into this in an environment where they cannot set node properties directly (in my case a build tool):

NODE_OPTIONS="--max-old-space-size=4096" node ...

You can set the node options using an environment variable if you cannot pass them on the command line.

How to create helper file full of functions in react native?

An alternative is to create a helper file where you have a const object with functions as properties of the object. This way you only export and import one object.

helpers.js

const helpers = {
    helper1: function(){

    },
    helper2: function(param1){

    },
    helper3: function(param1, param2){

    }
}

export default helpers;

Then, import like this:

import helpers from './helpers';

and use like this:

helpers.helper1();
helpers.helper2('value1');
helpers.helper3('value1', 'value2');

Export multiple classes in ES6 modules

Try this in your code:

import Foo from './Foo';
import Bar from './Bar';

// without default
export {
  Foo,
  Bar,
}

Btw, you can also do it this way:

// bundle.js
export { default as Foo } from './Foo'
export { default as Bar } from './Bar'
export { default } from './Baz'

// and import somewhere..
import Baz, { Foo, Bar } from './bundle'

Using export

export const MyFunction = () => {}
export const MyFunction2 = () => {}

const Var = 1;
const Var2 = 2;

export {
   Var,
   Var2,
}


// Then import it this way
import {
  MyFunction,
  MyFunction2,
  Var,
  Var2,
} from './foo-bar-baz';

The difference with export default is that you can export something, and apply the name where you import it:

// export default
export default class UserClass {
  constructor() {}
};

// import it
import User from './user'

merge one local branch into another local branch

Just in case you arrived here because you copied a branch name from Github, note that a remote branch is not automatically also a local branch, so a merge will not work and give the "not something we can merge" error.

In that case, you have two options:

git checkout [branchYouWantToMergeInto]
git merge origin/[branchYouWantToMerge]

or

# this creates a local branch
git checkout [branchYouWantToMerge]

git checkout [branchYouWantToMergeInto]
git merge [branchYouWantToMerge]

Communication between multiple docker-compose projects

Since Compose 1.18 (spec 3.5), you can just override the default network using your own custom name for all Compose YAML files you need. It is as simple as appending the following to them:

networks:
  default:
    name: my-app

The above assumes you have version set to 3.5 (or above if they don't deprecate it in 4+).

Other answers have pointed the same; this is a simplified summary.

Pass multiple parameters to rest API - Spring

Yes its possible to pass JSON object in URL

queryString = "{\"left\":\"" + params.get("left") + "}";
 httpRestTemplate.exchange(
                    Endpoint + "/A/B?query={queryString}",
                    HttpMethod.GET, entity, z.class, queryString);

multiple conditions for JavaScript .includes() method

Not the best answer and not the cleanest, but I think it's more permissive. Like if you want to use the same filters for all of your checks. Actually .filter() works with an array and return a filtered array (wich I find more easy to use too).

var str1 = 'hi, how do you do?';
var str2 = 'regular string';
var conditions = ["hello", "hi", "howdy"];

// Solve the problem
var res1 = [str1].filter(data => data.includes(conditions[0]) || data.includes(conditions[1]) || data.includes(conditions[2]));
var res2 = [str2].filter(data => data.includes(conditions[0]) || data.includes(conditions[1]) || data.includes(conditions[2]));

console.log(res1); // ["hi, how do you do?"]
console.log(res2); // []


// More useful in this case
var text = [str1, str2, "hello world"];

// Apply some filters on data
var res3 = text.filter(data => data.includes(conditions[0]) && data.includes(conditions[2]));
// You may use again the same filters for a different check
var res4 = text.filter(data => data.includes(conditions[0]) || data.includes(conditions[1]));

console.log(res3); // []
console.log(res4); // ["hi, how do you do?", "hello world"]

Chaining Observables in RxJS

About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :

Basically, flatMap is the equivalent of Promise.then.

For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)

How to get request URL in Spring Boot RestController

You may try adding an additional argument of type HttpServletRequest to the getUrlValue() method:

@RequestMapping(value ="/",produces = "application/json")
public String getURLValue(HttpServletRequest request){
    String test = request.getRequestURI();
    return test;
}

PySpark: multiple conditions in when clause

it should works at least in pyspark 2.4

tdata = tdata.withColumn("Age",  when((tdata.Age == "") & (tdata.Survived == "0") , "NewValue").otherwise(tdata.Age))

How to import multiple csv files in a single load?

Note that you can use other tricks like :

-- One or more wildcard:
       .../Downloads20*/*.csv
--  braces and brackets   
       .../Downloads201[1-5]/book.csv
       .../Downloads201{11,15,19,99}/book.csv

Printing an int list in a single line python3

Maybe this code will help you.

>>> def sort(lists):
...     lists.sort()
...     return lists
...
>>> datalist = [6,3,4,1,3,2,9]
>>> print(*sort(datalist), end=" ")
1 2 3 3 4 6 9

you can use an empty list variable to collect the user input, with method append(). and if you want to print list in one line you can use print(*list)

Sort collection by multiple fields in Kotlin

sortedWith + compareBy (taking a vararg of lambdas) do the trick:

val sortedList = list.sortedWith(compareBy({ it.age }, { it.name }))

You can also use the somewhat more succinct callable reference syntax:

val sortedList = list.sortedWith(compareBy(Person::age, Person::name))

Service located in another namespace

You can achieve this by deploying something at a higher layer than namespaced Services, like the service loadbalancer https://github.com/kubernetes/contrib/tree/master/service-loadbalancer. If you want to restrict it to a single namespace, use "--namespace=ns" argument (it defaults to all namespaces: https://github.com/kubernetes/contrib/blob/master/service-loadbalancer/service_loadbalancer.go#L715). This works well for L7, but is a little messy for L4.

How to set default values in Go structs

From https://golang.org/doc/effective_go.html#composite_literals:

Sometimes the zero value isn't good enough and an initializing constructor is necessary, as in this example derived from package os.

    func NewFile(fd int, name string) *File {
      if fd < 0 {
        return nil
      }
      f := new(File)
      f.fd = fd
      f.name = name
      f.dirinfo = nil
      f.nepipe = 0
      return f
}

Vue.js getting an element within a component

Composition API

Template refs section tells how this has been unified:

  • within template, use ref="myEl"; :ref= with a v-for
  • within script, have a const myEl = ref(null) and expose it from setup

The reference carries the DOM element from mounting onwards.

Docker-Compose with multiple services

The thing is that you are using the option -t when running your container.

Could you check if enabling the tty option (see reference) in your docker-compose.yml file the container keeps running?

version: '2'
services:
  ubuntu:
        build: .
        container_name: ubuntu
        volumes:
            - ~/sph/laravel52:/www/laravel
        ports:
          - "80:80"
        tty: true

How to capture multiple repeated groups?

I know that my answer came late but it happens to me today and I solved it with the following approach:

^(([A-Z]+),)+([A-Z]+)$

So the first group (([A-Z]+),)+ will match all the repeated patterns except the final one ([A-Z]+) that will match the final one. and this will be dynamic no matter how many repeated groups in the string.

Running stages in parallel with Jenkins workflow / pipeline

I have just tested the following pipeline and it works

parallel firstBranch: {
    stage ('Starting Test') 
    {
        build job: 'test1', parameters: [string(name: 'Environment', value: "$env.Environment")]
    }
}, secondBranch: {
    stage ('Starting Test2') 
    {
        build job: 'test2', parameters: [string(name: 'Environment', value: "$env.Environment")]
    }
}

This Job named 'trigger-test' accepts one parameter named 'Environment'

Job 'test1' and 'test2' are simple jobs:

Example for 'test1'

  • One parameter named 'Environment'
  • Pipeline : echo "$env.Environment-TEST1"

On execution, I am able to see both stages running in the same time

How do I call an Angular 2 pipe with multiple arguments?

You're missing the actual pipe.

{{ myData | date:'fullDate' }}

Multiple parameters can be separated by a colon (:).

{{ myData | myPipe:'arg1':'arg2':'arg3' }}

Also you can chain pipes, like so:

{{ myData | date:'fullDate' | myPipe:'arg1':'arg2':'arg3' }}

pandas: to_numeric for multiple columns

You can use:

print df.columns[5:]
Index([u'2004', u'2005', u'2006', u'2007', u'2008', u'2009', u'2010', u'2011',
       u'2012', u'2013', u'2014'],
      dtype='object')

for col in  df.columns[5:]:
    df[col] = pd.to_numeric(df[col], errors='coerce')

print df
       GeoName      ComponentName  IndustryId  IndustryClassification  \
37926  Alabama  Real GDP by state           9                     213   
37951  Alabama  Real GDP by state          34                      42   
37932  Alabama  Real GDP by state          15                     327   

                                      Description  2004   2005   2006   2007  \
37926               Support activities for mining    99     98    117    117   
37951                            Wholesale  trade  9898  10613  10952  11034   
37932  Nonmetallic mineral products manufacturing   980    968    940   1084   

        2008  2009  2010  2011  2012  2013     2014  
37926    115    87    96    95   103   102      NaN  
37951  11075  9722  9765  9703  9600  9884  10199.0  
37932    861   724   714   701   589   641      NaN  

Another solution with filter:

print df.filter(like='20')
       2004   2005   2006   2007   2008  2009  2010  2011  2012  2013   2014
37926    99     98    117    117    115    87    96    95   103   102   (NA)
37951  9898  10613  10952  11034  11075  9722  9765  9703  9600  9884  10199
37932   980    968    940   1084    861   724   714   701   589   641   (NA)

for col in  df.filter(like='20').columns:
    df[col] = pd.to_numeric(df[col], errors='coerce')
print df
       GeoName      ComponentName  IndustryId  IndustryClassification  \
37926  Alabama  Real GDP by state           9                     213   
37951  Alabama  Real GDP by state          34                      42   
37932  Alabama  Real GDP by state          15                     327   

                                      Description  2004   2005   2006   2007  \
37926               Support activities for mining    99     98    117    117   
37951                            Wholesale  trade  9898  10613  10952  11034   
37932  Nonmetallic mineral products manufacturing   980    968    940   1084   

        2008  2009  2010  2011  2012  2013     2014  
37926    115    87    96    95   103   102      NaN  
37951  11075  9722  9765  9703  9600  9884  10199.0  
37932    861   724   714   701   589   641      NaN  

When should I use curly braces for ES6 import?

The curly braces ({}) are used to import named bindings and the concept behind it is destructuring assignment

A simple demonstration of how import statement works with an example can be found in my own answer to a similar question at When do we use '{ }' in javascript imports?.

How to have multiple conditions for one if statement in python

I would use

def example(arg1, arg2, arg3):
     if arg1 == 1 and arg2 == 2 and arg3 == 3:
          print("Example Text")

The and operator is identical to the logic gate with the same name; it will return 1 if and only if all of the inputs are 1. You can also use or operator if you want that logic gate.

EDIT: Actually, the code provided in your post works fine with me. I don't see any problems with that. I think that this might be a problem with your Python, not the actual language.

Copy multiple files with Ansible

Since Ansible 2.5 the with_* constructs are deprecated, and loop syntax should be used. A simple practical example:

- name: Copy CA files
  copy:
    src: '{{item}}'
    dest: '/etc/pki/ca-trust/source/anchors'
    owner: root
    group: root
    mode: 0644
  loop:
    - symantec-private.crt
    - verisignclass3g2.crt

Moment.js - two dates difference in number of days

Here's how you can get the comprehensive full fledge difference of two dates.

 function diffYMDHMS(date1, date2) {

    let years = date1.diff(date2, 'year');
    date2.add(years, 'years');

    let months = date1.diff(date2, 'months');
    date2.add(months, 'months');

    let days = date1.diff(date2, 'days');
    date2.add(days, 'days');

    let hours = date1.diff(date2, 'hours');
    date2.add(hours, 'hours');

    let minutes = date1.diff(date2, 'minutes');
    date2.add(minutes, 'minutes');

    let seconds = date1.diff(date2, 'seconds');

    console.log(years + ' years ' + months + ' months ' + days + ' days ' + hours + ' 
    hours ' + minutes + ' minutes ' + seconds + ' seconds'); 

    return { years, months, days, hours, minutes, seconds};
}

substring of an entire column in pandas dataframe

case the column isn't string, use astype to convert:

df['col'] = df['col'].astype(str).str[:9]

Run an Ansible task only when the variable contains a specific string

In Ansible version 2.9.2:

If your variable variable1 is declared:

when: "'value' in variable1"

If you registered variable1 then:

when: "'value' in variable1.stdout"

Is there a way to specify which pytest tests to run from a file?

Here's a possible partial answer, because it only allows selecting the test scripts, not individual tests within those scripts.

And it also limited by my using legacy compatibility mode vs unittest scripts, so not guaranteeing it would work with native pytest.

Here goes:

  1. create a new dictory, say subset_tests_directory.
  2. ln -s tests_directory/foo.py
  3. ln -s tests_directory/bar.py

  4. be careful about imports which implicitly assume files are in test_directory. I had to fix several of those by running python foo.py, from within subset_tests_directory and correcting as needed.

  5. Once the test scripts execute correctly, just cd subset_tests_directory and pytest there. Pytest will only pick up the scripts it sees.

Another possibility is symlinking within your current test directory, say as ln -s foo.py subset_foo.py then pytest subset*.py. That would avoid needing to adjust your imports, but it would clutter things up until you removed the symlinks. Worked for me as well.

Ifelse statement in R with multiple conditions

another solution using dplyr is:

df <- ## your data ##
df <- df %>%
        mutate(Den = ifelse(any(is.na(Den)) | any(Den != 1), 0, 1))

Passing Multiple route params in Angular2

Two Methods for Passing Multiple route params in Angular

Method-1

In app.module.ts

Set path as component2.

imports: [
 RouterModule.forRoot(
 [ {path: 'component2/:id1/:id2', component: MyComp2}])
]

Call router to naviagte to MyComp2 with multiple params id1 and id2.

export class MyComp1 {
onClick(){
    this._router.navigate( ['component2', "id1","id2"]);
 }
}

Method-2

In app.module.ts

Set path as component2.

imports: [
 RouterModule.forRoot(
 [ {path: 'component2', component: MyComp2}])
]

Call router to naviagte to MyComp2 with multiple params id1 and id2.

export class MyComp1 {
onClick(){
    this._router.navigate( ['component2', {id1: "id1 Value", id2: 
    "id2  Value"}]);
 }
}

How to pass multiple parameters to a get method in ASP.NET Core

I would suggest to use a separate dto object as an argument:

[Route("api/[controller]")]
public class PersonController : Controller
{
    public string Get([FromQuery] GetPersonQueryObject request)
    {
        // Your code goes here
    }
}

public class GetPersonQueryObject 
{
    public int? Id { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public string Address { get; set; }
}

Dotnet will map the fields to your object.

This will make it a lot easier to pass through your parameters and will result in much clearer code.

Remove multiple items from a Python list in just one statement

You Can use this -

Suppose we have a list, l = [1,2,3,4,5]

We want to delete last two items in a single statement

del l[3:]

We have output:

l = [1,2,3]

Keep it Simple

Postman: How to make multiple requests at the same time

If you are only doing GET requests and you need another simple solution from within your Chrome browser, just install the "Open Multiple URLs" extension:

https://chrome.google.com/webstore/detail/open-multiple-urls/oifijhaokejakekmnjmphonojcfkpbbh?hl=en

I've just ran 1500 url's at once, did lag google a bit but it works.

Angular 2: How to write a for loop, not a foreach loop

You can instantiate an empty array with a given number of entries if you pass an int to the Array constructor and then iterate over it via ngFor.

In your component code :

export class ForLoop {
  fakeArray = new Array(12);
}

In your template :

<ul>
  <li *ngFor="let a of fakeArray; let index = index">Something {{ index }}</li>
</ul>

The index properties give you the iteration number.

Live version

How do I upload a file with the JS fetch API?

Here is my code:

html:

_x000D_
_x000D_
const upload = (file) => {_x000D_
    console.log(file);_x000D_
_x000D_
    _x000D_
_x000D_
    fetch('http://localhost:8080/files/uploadFile', { _x000D_
    method: 'POST',_x000D_
    // headers: {_x000D_
    //   //"Content-Disposition": "attachment; name='file'; filename='xml2.txt'",_x000D_
    //   "Content-Type": "multipart/form-data; boundary=BbC04y " //"multipart/mixed;boundary=gc0p4Jq0M2Yt08jU534c0p" //  ? // multipart/form-data _x000D_
    // },_x000D_
    body: file // This is your file object_x000D_
  }).then(_x000D_
    response => response.json() // if the response is a JSON object_x000D_
  ).then(_x000D_
    success => console.log(success) // Handle the success response object_x000D_
  ).catch(_x000D_
    error => console.log(error) // Handle the error response object_x000D_
  );_x000D_
_x000D_
  //cvForm.submit();_x000D_
};_x000D_
_x000D_
const onSelectFile = () => upload(uploadCvInput.files[0]);_x000D_
_x000D_
uploadCvInput.addEventListener('change', onSelectFile, false);
_x000D_
<form id="cv_form" style="display: none;"_x000D_
          enctype="multipart/form-data">_x000D_
          <input id="uploadCV" type="file" name="file"/>_x000D_
          <button type="submit" id="upload_btn">upload</button>_x000D_
</form>_x000D_
<ul class="dropdown-menu">_x000D_
<li class="nav-item"><a class="nav-link" href="#" id="upload">UPLOAD CV</a></li>_x000D_
<li class="nav-item"><a class="nav-link" href="#" id="download">DOWNLOAD CV</a></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Ansible: Store command's stdout in new variable?

There's no need to set a fact.

    - shell: cat "hello"
      register: cat_contents

    - shell: echo "I cat hello"
      when: cat_contents.stdout == "hello"

TensorFlow: "Attempting to use uninitialized value" in variable initialization

It's not 100% clear from the code example, but if the list initial_parameters_of_hypothesis_function is a list of tf.Variable objects, then the line session.run(init) will fail because TensorFlow isn't (yet) smart enough to figure out the dependencies in variable initialization. To work around this, you should change the loop that creates parameters to use initial_parameters_of_hypothesis_function[i].initialized_value(), which adds the necessary dependency:

parameters = []
for i in range(0, number_of_attributes, 1):
    parameters.append(tf.Variable(
        initial_parameters_of_hypothesis_function[i].initialized_value()))

How to create multiple output paths in Webpack config

The problem is already in the language:

  • entry (which is a object (key/value) and is used to define the inputs*)
  • output (which is a object (key/value) and is used to define outputs*)

the idea to differentiate the output based on limited placeholder like '[name]' defines limitations.

I like the core functionality of webpack, but the usage requires a rewrite with abstract definitions which are based on logic and simplicity... the hardest thing in software-development... logic and simplicity.

All this could be solved by just providing a list of input/output definitions... A LIST INPUT/OUTPUT DEFINITIONS.

Although this comment doesn't help much but we can learn from our mistakes by pointing at them.

Vinod Kumar: Good workaround, its:

module.exports = {
   plugins: [
    new FileManagerPlugin({
      events: {
        onEnd: {
          copy: [
            {source: 'www', destination: './vinod test 1/'},
            {source: 'www', destination: './vinod testing 2/'},
            {source: 'www', destination: './vinod testing 3/'},
          ],
        },
      }
    }),
  ],
};

BTW. this is my first comment on stackoverflow (after 10 years as a programmer) and stackoverflow sucks in usability, like why is there so much text everywhere ? my eyes are bleeding.

multiple conditions for filter in spark data frames

If we want partial match just like contains, we can chain the contain call like this :

def getSelectedTablesRows2(allTablesInfoDF: DataFrame, tableNames: Seq[String]): DataFrame = {

    val tableFilters = tableNames.map(_.toLowerCase()).map(name => lower(col("table_name")).contains(name))
    val finalFilter = tableFilters.fold(lit(false))((accu, newTableFilter) => accu or newTableFilter)
    allTablesInfoDF.where(finalFilter)

  }

Manifest Merger failed with multiple errors in Android Studio

I solved this by removing android:replace tag

R dplyr: Drop multiple columns

Check the help on select_vars. That gives you some extra ideas on how to work with this.

In your case:

iris %>% select(-one_of(drop.cols))

How to join multiple collections with $lookup in mongodb

You can actually chain multiple $lookup stages. Based on the names of the collections shared by profesor79, you can do this :

db.sivaUserInfo.aggregate([
    {
        $lookup: {
           from: "sivaUserRole",
           localField: "userId",
           foreignField: "userId",
           as: "userRole"
        }
    },
    {
        $unwind: "$userRole"
    },
    {
        $lookup: {
            from: "sivaUserInfo",
            localField: "userId",
            foreignField: "userId",
            as: "userInfo"
        }
    },
    {
        $unwind: "$userInfo"
    }
])

This will return the following structure :

{
    "_id" : ObjectId("56d82612b63f1c31cf906003"),
    "userId" : "AD",
    "phone" : "0000000000",
    "userRole" : {
        "_id" : ObjectId("56d82612b63f1c31cf906003"),
        "userId" : "AD",
        "role" : "admin"
    },
    "userInfo" : {
        "_id" : ObjectId("56d82612b63f1c31cf906003"),
        "userId" : "AD",
        "phone" : "0000000000"
    }
}

Maybe this could be considered an anti-pattern because MongoDB wasn't meant to be relational but it is useful.

Retrieving subfolders names in S3 bucket from boto3

I know that boto3 is the topic being discussed here, but I find that it is usually quicker and more intuitive to simply use awscli for something like this - awscli retains more capabilities that boto3 for what than is worth.

For example, if I have objects saved in "subfolders" associated with a given bucket, I can list them all out with something such as this:

1) 'mydata' = bucket name

2) 'f1/f2/f3' = "path" leading to "files" or objects

3) 'foo2.csv, barfar.segy, gar.tar' = all objects "inside" f3

So, we can think of the "absolute path" leading to these objects is: 'mydata/f1/f2/f3/foo2.csv'...

Using awscli commands, we can easily list all objects inside a given "subfolder" via:

aws s3 ls s3://mydata/f1/f2/f3/ --recursive

Call async/await functions in parallel

TL;DR

Use Promise.all for the parallel function calls, the answer behaviors not correctly when the error occurs.


First, execute all the asynchronous calls at once and obtain all the Promise objects. Second, use await on the Promise objects. This way, while you wait for the first Promise to resolve the other asynchronous calls are still progressing. Overall, you will only wait for as long as the slowest asynchronous call. For example:

// Begin first call and store promise without waiting
const someResult = someCall();

// Begin second call and store promise without waiting
const anotherResult = anotherCall();

// Now we await for both results, whose async processes have already been started
const finalResult = [await someResult, await anotherResult];

// At this point all calls have been resolved
// Now when accessing someResult| anotherResult,
// you will have a value instead of a promise

JSbin example: http://jsbin.com/xerifanima/edit?js,console

Caveat: It doesn't matter if the await calls are on the same line or on different lines, so long as the first await call happens after all of the asynchronous calls. See JohnnyHK's comment.


Update: this answer has a different timing in error handling according to the @bergi's answer, it does NOT throw out the error as the error occurs but after all the promises are executed. I compare the result with @jonny's tip: [result1, result2] = Promise.all([async1(), async2()]), check the following code snippet

_x000D_
_x000D_
const correctAsync500ms = () => {_x000D_
  return new Promise(resolve => {_x000D_
    setTimeout(resolve, 500, 'correct500msResult');_x000D_
  });_x000D_
};_x000D_
_x000D_
const correctAsync100ms = () => {_x000D_
  return new Promise(resolve => {_x000D_
    setTimeout(resolve, 100, 'correct100msResult');_x000D_
  });_x000D_
};_x000D_
_x000D_
const rejectAsync100ms = () => {_x000D_
  return new Promise((resolve, reject) => {_x000D_
    setTimeout(reject, 100, 'reject100msError');_x000D_
  });_x000D_
};_x000D_
_x000D_
const asyncInArray = async (fun1, fun2) => {_x000D_
  const label = 'test async functions in array';_x000D_
  try {_x000D_
    console.time(label);_x000D_
    const p1 = fun1();_x000D_
    const p2 = fun2();_x000D_
    const result = [await p1, await p2];_x000D_
    console.timeEnd(label);_x000D_
  } catch (e) {_x000D_
    console.error('error is', e);_x000D_
    console.timeEnd(label);_x000D_
  }_x000D_
};_x000D_
_x000D_
const asyncInPromiseAll = async (fun1, fun2) => {_x000D_
  const label = 'test async functions with Promise.all';_x000D_
  try {_x000D_
    console.time(label);_x000D_
    let [value1, value2] = await Promise.all([fun1(), fun2()]);_x000D_
    console.timeEnd(label);_x000D_
  } catch (e) {_x000D_
    console.error('error is', e);_x000D_
    console.timeEnd(label);_x000D_
  }_x000D_
};_x000D_
_x000D_
(async () => {_x000D_
  console.group('async functions without error');_x000D_
  console.log('async functions without error: start')_x000D_
  await asyncInArray(correctAsync500ms, correctAsync100ms);_x000D_
  await asyncInPromiseAll(correctAsync500ms, correctAsync100ms);_x000D_
  console.groupEnd();_x000D_
_x000D_
  console.group('async functions with error');_x000D_
  console.log('async functions with error: start')_x000D_
  await asyncInArray(correctAsync500ms, rejectAsync100ms);_x000D_
  await asyncInPromiseAll(correctAsync500ms, rejectAsync100ms);_x000D_
  console.groupEnd();_x000D_
})();
_x000D_
_x000D_
_x000D_

Pandas split column of lists into multiple columns

Here's another solution using df.transform and df.set_index:

>>> (df['teams']
       .transform([lambda x:x[0], lambda x:x[1]])
       .set_axis(['team1','team2'],
                  axis=1,
                  inplace=False)
    )

  team1 team2
0    SF   NYG
1    SF   NYG
2    SF   NYG
3    SF   NYG
4    SF   NYG
5    SF   NYG
6    SF   NYG

Missing visible-** and hidden-** in Bootstrap v4

Bootstrap 4 to hide whole content use this class '.d-none' it will be hide everything regardless of breakpoints same like previous bootstrap version class '.hidden'

Find duplicates and delete all in notepad++

If it is possible to change the sequence of the lines you could do:

  1. sort line with Edit -> Line Operations -> Sort Lines Lexicographically ascending
  2. do a Find / Replace:
    • Find What: ^(.*\r?\n)\1+
    • Replace with: (Nothing, leave empty)
    • Check Regular Expression in the lower left
    • Click Replace All

How it works: The sorting puts the duplicates behind each other. The find matches a line ^(.*\r?\n) and captures the line in \1 then it continues and tries to find \1 one or more times (+) behind the first match. Such a block of duplicates (if it exists) is replaced with nothing.

The \r?\n should deal nicely with Windows and Unix lineendings.

TypeError: object of type 'int' has no len() error assistance needed

Well, maybe an int does not posses the len attribute in Python like your error suggests?

Try:

len(str(numbers))

How do I multiply each element in a list by a number?

from functools import partial as p
from operator import mul
map(p(mul,5),my_list)

is one way you could do it ... your teacher probably knows a much less complicated way that was probably covered in class

Spring RequestMapping for controllers that produce and consume JSON

There are 2 annotations in Spring: @RequestBody and @ResponseBody. These annotations consumes, respectively produces JSONs. Some more info here.

Manually Set Value for FormBuilder Control

@Filoche's Angular 2 updated solution. Using FormControl

(<Control>this.form.controls['dept']).updateValue(selected.id)

import { FormControl } from '@angular/forms';

(<FormControl>this.form.controls['dept']).setValue(selected.id));

Alternatively you can use @AngularUniversity's solution which uses patchValue

Angular 2: Get Values of Multiple Checked Checkboxes

In Angular 2+ to 9 using Typescript

Source Link

enter image description here

we can use an object to bind multiple Checkbox

  checkboxesDataList = [
    {
      id: 'C001',
      label: 'Photography',
      isChecked: true
    },
    {
      id: 'C002',
      label: 'Writing',
      isChecked: true
    },
    {
      id: 'C003',
      label: 'Painting',
      isChecked: true
    },
    {
      id: 'C004',
      label: 'Knitting',
      isChecked: false
    },
    {
      id: 'C004',
      label: 'Dancing',
      isChecked: false
    },
    {
      id: 'C005',
      label: 'Gardening',
      isChecked: true
    },
    {
      id: 'C006',
      label: 'Drawing',
      isChecked: true
    },
    {
      id: 'C007',
      label: 'Gyming',
      isChecked: false
    },
    {
      id: 'C008',
      label: 'Cooking',
      isChecked: true
    },
    {
      id: 'C009',
      label: 'Scrapbooking',
      isChecked: false
    },
    {
      id: 'C010',
      label: 'Origami',
      isChecked: false
    }
  ]

In HTML Template use

  <ul class="checkbox-items">
    <li *ngFor="let item of checkboxesDataList">
      <input type="checkbox" [(ngModel)]="item.isChecked" (change)="changeSelection()">{{item.label}}
    </li>
  </ul>

To get selected checkboxes, add the following method in class

  // Selected item
  fetchSelectedItems() {
    this.selectedItemsList = this.checkboxesDataList.filter((value, index) => {
      return value.isChecked
    });
  }

  // IDs of selected item
  fetchCheckedIDs() {
    this.checkedIDs = []
    this.checkboxesDataList.forEach((value, index) => {
      if (value.isChecked) {
        this.checkedIDs.push(value.id);
      }
    });
  }

No matching client found for package name (Google Analytics) - multiple productFlavors & buildTypes

Found this:

The google-services.json file is generally placed in the app/ directory, but as of version 2.0.0-alpha3 of the plugin support was added for build types, which would make the following directory structure valid:

app/src/
    main/google-services.json
    dogfood/google-services.json
    mytype1/google-services.json
    ...

Source

Source 2

How to print multiple lines of text with Python

I wanted to answer to the following question which is a little bit different than this:

Best way to print messages on multiple lines

He wanted to show lines from repeated characters too. He wanted this output:

----------------------------------------
# Operator Micro-benchmarks
# Run_mode: short
# Num_repeats: 5
# Num_runs: 1000

----------------------------------------

You can create those lines inside f-strings with a multiplication, like this:

run_mode, num_repeats, num_runs = 'short', 5, 1000

s = f"""
{'-'*40}
# Operator Micro-benchmarks
# Run_mode: {run_mode}
# Num_repeats: {num_repeats}
# Num_runs: {num_runs}

{'-'*40}
"""

print(s)

NPM stuck giving the same error EISDIR: Illegal operation on a directory, read at error (native)

I know this isn't specifically asking about forever js.. but google lead me here so.. For me it was as simple as an ending slash.

I just changed:

forever start -a -l /dev/null/ /var/www/node/my_file.js

To:

forever start -a -l /dev/null /var/www/node/my_file.js

And the error disappeared

Multiple conditions in an IF statement in Excel VBA

In VBA we can not use if jj = 5 or 6 then we must use if jj = 5 or jj = 6 then

maybe this:

If inputWks.Range("d9") > 0 And (inputWks.Range("d11") = "Restricted_Expenditure" Or inputWks.Range("d11") = "Unrestricted_Expenditure") Then

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply?

In general, the key to avoiding an explicit loop would be to join (merge) 2 instances of the dataframe on rowindex-1==rowindex.

Then you would have a big dataframe containing rows of r and r-1, from where you could do a df.apply() function.

However the overhead of creating the large dataset may offset the benefits of parallel processing...

Vuejs: v-model array in multiple input

If you were asking how to do it in vue2 and make options to insert and delete it, please, have a look an js fiddle

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  data: {_x000D_
    finds: [] _x000D_
  },_x000D_
  methods: {_x000D_
    addFind: function () {_x000D_
      this.finds.push({ value: 'def' });_x000D_
    },_x000D_
    deleteFind: function (index) {_x000D_
      console.log(index);_x000D_
      console.log(this.finds);_x000D_
      this.finds.splice(index, 1);_x000D_
    }_x000D_
  }_x000D_
});
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
  <h1>Finds</h1>_x000D_
  <div v-for="(find, index) in finds">_x000D_
    <input v-model="find.value">_x000D_
    <button @click="deleteFind(index)">_x000D_
      delete_x000D_
    </button>_x000D_
  </div>_x000D_
  _x000D_
  <button @click="addFind">_x000D_
    New Find_x000D_
  </button>_x000D_
  _x000D_
  <pre>{{ $data }}</pre>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to find and replace with regex in excel

If you want a formula to do it then:

=IF(ISNUMBER(SEARCH("*texts are *",A1)),LEFT(A1,FIND("texts are ",A1) + 9) & "WORD",A1)

This will do it. Change `"WORD" To the word you want.

Can't push image to Amazon ECR - fails with "no basic auth credentials"

Make sure you use the correct region in aws ecr get-login, it must match the region in which your repository is created.

Angular2 multiple router-outlet in the same template

You can have multiple router-outlet in same template by configuring your router and providing name to your router-outlet, you can achieve this as follows.

Advantage of below approach is thats you can avoid dirty looking URL with it. eg: /home(aux:login) etc.

Assuming on load you are bootstraping appComponent.

app.component.html

<div class="layout">
    <div class="page-header">
        //first outlet to load required component
        <router-outlet name='child1'></router-outlet>
    </div>
    <div class="content">
        //second outlet to load required component
        <router-outlet name='child2'></router-outlet>
    </div>
</div>

Add following to your router.

{
    path: 'home',  // you can keep it empty if you do not want /home
    component: 'appComponent',
    children: [
        {
            path: '',
            component: childOneComponent,
            outlet: 'child1'
        },
        {
            path: '',
            component: childTwoComponent,
            outlet: 'child2'
        }
    ]
}

Now when /home is loaded appComponent will get load with allocated template, then angular router will check the route and load the children component in specified router outlet on the basis of name.

Like above you can configure your router to have multiple router-outlet in same route.

how to remove multiple columns in r dataframe?

Adding answer as this was the top hit when searching for "drop multiple columns in r":

The general version of the single column removal, e.g df$column1 <- NULL, is to use list(NULL):

df[ ,c('column1', 'column2')] <- list(NULL)

This also works for position index as well:

df[ ,c(1,2)] <- list(NULL)

This is a more general drop and as some comments have mentioned, removing by indices isn't recommended. Plus the familiar negative subset (used in other answers) doesn't work for columns given as strings:

> iris[ ,-c("Species")]
Error in -"Species" : invalid argument to unary operator

How can you print multiple variables inside a string using printf?

printf("\nmaximum of %d and %d is = %d",a,b,c);

Python: how to capture image from webcam on click using OpenCV

Breaking down your code example (Explanations are under the line of code.)

import cv2

imports openCV for usage

camera = cv2.VideoCapture(0)

creates an object called camera, of type openCV video capture, using the first camera in the list of cameras connected to the computer.

for i in range(10):

tells the program to loop the following indented code 10 times

    return_value, image = camera.read()

read values from the camera object, using it's read method. it resonds with 2 values save the 2 data values into two temporary variables called "return_value" and "image"

    cv2.imwrite('opencv'+str(i)+'.png', image)

use the openCV method imwrite (that writes an image to a disk) and write an image using the data in the temporary data variable

fewer indents means that the loop has now ended...

del(camera)

deletes the camrea object, we no longer needs it.

you can what you request in many ways, one could be to replace the for loop with a while loop, (running forever, instead of 10 times), and then wait for a keypress (like answered by danidee while I was typing)

or create a much more evil service that hides in the background and captures an image everytime someone presses the keyboard...

Aggregate multiple columns at once

You could try:

agg <- aggregate(list(x$val1, x$val2, x$val3, x$val4), by = list(x$id1, x$id2), mean)

How to add multiple classes to a ReactJS Component?

Just use a comma!

const useStyles = makeStyles((theme) => ({
 rightAlign: {
  display: 'flex',
  justifyContent: 'flex-end',
 },
 customSpacing: {
  marginTop: theme.spacing(2.5),
 },
)};

<div className={(classes.rightAlign, classes.customSpacing)}>Some code</div>

android : Error converting byte to dex

If you have multiple projects, make sure you are not adding a dependency multiple times, I needed to exclude the other project's dependency like this:

compile(project(':OtherProject-SDK')) {
    compile.exclude module: 'play-services-gcm'
    compile.exclude module: 'play-services-location'
    compile.exclude module: 'support-v4'
    compile.exclude module: 'okhttp'
}

Android 6.0 multiple permissions

Short and sweet :). what I believe in.

int PERMISSION_ALL = 1;
String[] PERMISSIONS = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}; // List of permissions required

public void askPermission()
{
    for (String permission : PERMISSIONS) {
        if (ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(PERMISSIONS, PERMISSION_ALL);
            return;
        }
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                       int[] grantResults) {

    switch (requestCode) {
        case 1:{
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){
                //Do your work.
            } else {
                Toast.makeText(this, "Until you grant the permission, we cannot proceed further", Toast.LENGTH_SHORT).show();
            }
            return;
        }
    }

In Angular, how do you determine the active route?

I solved a problem I encountered in this link and I find out that there is a simple solution for your question. You could use router-link-active instead in your styles.

@Component({
   styles: [`.router-link-active { background-color: red; }`]
})
export class NavComponent {
}

How to comment multiple lines in Visual Studio Code?

For windows, the default key for multi-line comment is Alt + Shift + A

For windows, the default key for single line comment is Ctrl + /

How to prevent tensorflow from allocating the totality of a GPU memory?

For TensorFlow 2.0 and 2.1 (docs):

import tensorflow as tf
tf.config.gpu.set_per_process_memory_growth(True)

For TensorFlow 2.2+ (docs):

import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
  tf.config.experimental.set_memory_growth(gpu, True)

The docs also list some more methods:

  • Set environment variable TF_FORCE_GPU_ALLOW_GROWTH to true.
  • Use tf.config.experimental.set_virtual_device_configuration to set a hard limit on a Virtual GPU device.

Difference between numpy dot() and Python 3.5+ matrix multiplication @

My experience with MATMUL and DOT

I was constantly getting "ValueError: Shape of passed values is (200, 1), indices imply (200, 3)" when trying to use MATMUL. I wanted a quick workaround and found DOT to deliver the same functionality. I don't get any error using DOT. I get the correct answer

with MATMUL

X.shape
>>>(200, 3)

type(X)

>>>pandas.core.frame.DataFrame

w

>>>array([0.37454012, 0.95071431, 0.73199394])

YY = np.matmul(X,w)

>>>  ValueError: Shape of passed values is (200, 1), indices imply (200, 3)"

with DOT

YY = np.dot(X,w)
# no error message
YY
>>>array([ 2.59206877,  1.06842193,  2.18533396,  2.11366346,  0.28505879, …

YY.shape

>>> (200, )

How to select a schema in postgres when using psql?

This is old, but I put exports in my alias for connecting to the db:

alias schema_one.con="PGOPTIONS='--search_path=schema_one' psql -h host -U user -d database etc"

And for another schema:

alias schema_two.con="PGOPTIONS='--search_path=schema_two' psql -h host -U user -d database etc"

How to check the multiple permission at single request in Android M?

As said earlier, currently every permission group has own permission dialog which must be called separately.

You will have different dialog boxes for each permission group but you can surely check the result together in onRequestPermissionsResult() callback method.

Here is a working example link, may be useful for someone.

FailedPreconditionError: Attempting to use uninitialized in Tensorflow

From official documentation, FailedPreconditionError

This exception is most commonly raised when running an operation that reads a tf.Variable before it has been initialized.

In your case the error even explains what variable was not initialized: Attempting to use uninitialized value Variable_1. One of the TF tutorials explains a lot about variables, their creation/initialization/saving/loading

Basically to initialize the variable you have 3 options:

I almost always use the first approach. Remember you should put it inside a session run. So you will get something like this:

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

If your are curious about more information about variables, read this documentation to know how to report_uninitialized_variables and check is_variable_initialized.

querySelectorAll with multiple conditions

According to the documentation, just like with any css selector, you can specify as many conditions as you want, and they are treated as logical 'OR'.

This example returns a list of all div elements within the document with a class of either "note" or "alert":

var matches = document.querySelectorAll("div.note, div.alert");

source: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

Meanwhile to get the 'AND' functionality you can for example simply use a multiattribute selector, as jquery says:

https://api.jquery.com/multiple-attribute-selector/

ex. "input[id][name$='man']" specifies both id and name of the element and both conditions must be met. For classes it's as obvious as ".class1.class2" to require object of 2 classes.

All possible combinations of both are valid, so you can easily get equivalent of more sophisticated 'OR' and 'AND' expressions.

how to use the Box-Cox power transformation in R

Applying the BoxCox transformation to data, without the need of any underlying model, can be done currently using the package geoR. Specifically, you can use the function boxcoxfit() for finding the best parameter and then predict the transformed variables using the function BCtransform().

How to specify multiple return types using type-hints

From the documentation

class typing.Union

Union type; Union[X, Y] means either X or Y.

Hence the proper way to represent more than one return data type is

from typing import Union


def foo(client_id: str) -> Union[list,bool]

But do note that typing is not enforced. Python continues to remain a dynamically-typed language. The annotation syntax has been developed to help during the development of the code prior to being released into production. As PEP 484 states, "no type checking happens at runtime."

>>> def foo(a:str) -> list:
...     return("Works")
... 
>>> foo(1)
'Works'

As you can see I am passing a int value and returning a str. However the __annotations__ will be set to the respective values.

>>> foo.__annotations__ 
{'return': <class 'list'>, 'a': <class 'str'>}

Please Go through PEP 483 for more about Type hints. Also see What are Type hints in Python 3.5?

Kindly note that this is available only for Python 3.5 and upwards. This is mentioned clearly in PEP 484.

How to set multiple commands in one yaml file with Kubernetes?

My preference is to multiline the args, this is simplest and easiest to read. Also, the script can be changed without affecting the image, just need to restart the pod. For example, for a mysql dump, the container spec could be something like this:

containers:
  - name: mysqldump
    image: mysql
    command: ["/bin/sh", "-c"]
    args:
      - echo starting;
        ls -la /backups;
        mysqldump --host=... -r /backups/file.sql db_name;
        ls -la /backups;
        echo done;
    volumeMounts:
      - ...

The reason this works is that yaml actually concatenates all the lines after the "-" into one, and sh runs one long string "echo starting; ls... ; echo done;".

Checking for multiple conditions using "when" on single task in ansible

The problem with your conditional is in this part sshkey_result.rc == 1, because sshkey_result does not contain rc attribute and entire conditional fails.

If you want to check if file exists check exists attribute.

Here you can read more about stat module and how to use it.

Multiple Errors Installing Visual Studio 2015 Community Edition

I spent a whole week trying to solve this issue. What finally did it for me was disabling my anti-virus programs. Before I stumbled upon my solution, I went through a lot of other solutions. I thought, I'd post some of the solutions that might prove to be useful for those who are still having trouble with installing Visual Studios 2015 Community Edition.

Solution 1: Minimal Installation

Try installing with minimal extra features. Run the Visual Studios 2015 installation, then click "Custom" and on the following screen, uncheck everything and proceed with the installation.

Solution 2: Delete installation cache

Perhaps the installation failed due to corrupt files in the cache. When installation fails, remove all Visual Studio cache related items and do a full re-installation. To do this, run command prompt (Run as Administrator) and type: "cd /programdata/package cache/" then press enter. Then type "del /f /s *.msi /f /s *.cab" then press enter. Now run the Visual Studios 2015 installation again.

Solution 3: Delete temporary file data stored on your computer

Open up File Explorer and go to "C:\Users\[Your User Account Name]\AppData\Local\Microsoft". Then delete the following folders: VSCommon, VisualStudio, Blend, VsGraphics, ApplicationInsights, vshub, Team Foundation, Web Platform Installer and MsBuild. After this, run the Visual Studios 2015 Installer again.

Solution 4: Enable all four evaluations of Symbolic links

First, check to see if all four evaluations are enabled. Open up command prompt (Run as Administrator) and type "fsutil behavior query SymlinkEvaluation". All 4 evaluations should be enabled. If they aren't then type "fsutil behavior set SymlinkEvaluation L2L:1 R2R:1 L2R:1 R2L:1". Once those 4 evaluations are set, clear up temporary files and clear installation cache (see Solution 2 and Solution 3) then run the Visual Studios 2015 installation again.

Solution 5: Repair the Redistributables

Perhaps, the problem is that your VC-redistributables are faulty and are in need of repair. To do so, run "Add/Remove programs" and look for all the x86 and x64 versions of Microsoft Visual C++ [Year] Redistributable (Version). Then press Change for each of them and when the uninstallation screen pops up, press Repair. I did it for all the versions I had previously installed: 2012, 2013 and 2015. Therefore, I repaired 6 of them: 2012: x86 and x64, 2013: x86 and x64, 2015: x86 and x64.

Solution 6: Check to see if x86 and x64 sizes are the same

As mentioned by others in this discussion, do a search for vcruntime140.dll and see if the x86 and x64 versions. They should NOT have the same size. If they do, see solution 5 or you can manually delete them (** Be cautious when deleting files from the Windows folder!) and re-install them (from here: https://www.microsoft.com/en-ca/download/details.aspx?id=48145).
Also do the same check for msvcp140.dll. I personally did a search for these files in "C:\Windows\SysWOW64 and C:\Windows\System32" and compared the files from the two folders. Moreover I also checked for differences of vcruntime140.dll and msvcp140.dll in "C:\Program Files\Microsoft Visual Studio 14.0" and "C:\Program Files (x86)\Microsoft Visual Studio 14.0"

Solution 7: Temporarily disable all Anti-Virus Protection and Firewalls

For me, it turned out that the problem stemmed from having ByteFence Anti-Malware and Norton Security with Backup protection. I disabled real-time protection from ByteFence Anti-Malware and I disabled Auto-Protect and Smart Firewall from Norton Security with Backup. Before I ran the installation again, I repeated Solution 2 and Solution 3 (scroll up). And Voila, installation was successful. But how did I find out that the Anti-Virus Program was the culprit? Read Solution 8.

Solution 8: Carefully monitor Visual Studios Installation Process for Intrusions

I resorted to this solution in order to find out the problem. After reading Ezh's article, I decided to download Process Monitor v3.2 and Process Explorer v16.1. I was carefully monitoring 3 programs side-by-side: Process Monitor, Process Explorer and the Visual Studios 2015 Installer, and I watched very closely all the processes that the installer was invoking. Then I noticed that when VSIXInstaller.exe process came on and attempted to install something from a remote server, it kept failing over and over again because my Anti-Virus Program would suddenly appear on screen (as a process) and decide to hog/block some important DLL files that VSIX installation needed. Temporarily disabling the anti-virus program solved my issue!

Solution 9: Complete Windows format and re-installation

If all else fails, and you are really desperate to get Visual Studios 2015 working, I suggest a complete Windows re-installation. At this point, the problem is most likely some type of interference/intrusion with a program which you do not know of.

Spark Dataframe distinguish columns with duplicated name

Suppose the DataFrames you want to join are df1 and df2, and you are joining them on column 'a', then you have 2 methods

Method 1

df1.join(df2,'a','left_outer')

This is an awsome method and it is highly recommended.

Method 2

df1.join(df2,df1.a == df2.a,'left_outer').drop(df2.a)

Python: Pandas Dataframe how to multiply entire column with a scalar

Also it's possible to use numerical indeces with .iloc.

df.iloc[:,0]  *= -1

How to join on multiple columns in Pyspark?

An alternative approach would be:

df1 = sqlContext.createDataFrame(
    [(1, "a", 2.0), (2, "b", 3.0), (3, "c", 3.0)],
    ("x1", "x2", "x3"))

df2 = sqlContext.createDataFrame(
    [(1, "f", -1.0), (2, "b", 0.0)], ("x1", "x2", "x4"))

df = df1.join(df2, ['x1','x2'])
df.show()

which outputs:

+---+---+---+---+
| x1| x2| x3| x4|
+---+---+---+---+
|  2|  b|3.0|0.0|
+---+---+---+---+

With the main advantage being that the columns on which the tables are joined are not duplicated in the output, reducing the risk of encountering errors such as org.apache.spark.sql.AnalysisException: Reference 'x1' is ambiguous, could be: x1#50L, x1#57L.


Whenever the columns in the two tables have different names, (let's say in the example above, df2 has the columns y1, y2 and y4), you could use the following syntax:

df = df1.join(df2.withColumnRenamed('y1','x1').withColumnRenamed('y2','x2'), ['x1','x2'])

How to print the value of a Tensor object in TensorFlow?

Question: How to print the value of a Tensor object in TensorFlow?

Answer:

import tensorflow as tf

# Variable
x = tf.Variable([[1,2,3]])

# initialize
init = (tf.global_variables_initializer(), tf.local_variables_initializer())

# Create a session
sess = tf.Session()

# run the session
sess.run(init)

# print the value
sess.run(x)

How to create string with multiple spaces in JavaScript

var a = 'something' + Array(10).fill('\xa0').join('') + 'something'

number inside Array(10) can be changed to needed number of spaces

Multiple FROMs - what it means

As of May 2017, multiple FROMs can be used in a single Dockerfile.
See "Builder pattern vs. Multi-stage builds in Docker" (by Alex Ellis) and PR 31257 by Tõnis Tiigi.

The general syntax involves adding FROM additional times within your Dockerfile - whichever is the last FROM statement is the final base image. To copy artifacts and outputs from intermediate images use COPY --from=<base_image_number>.

FROM golang:1.7.3 as builder
WORKDIR /go/src/github.com/alexellis/href-counter/
RUN go get -d -v golang.org/x/net/html  
COPY app.go    .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .

FROM alpine:latest  
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /go/src/github.com/alexellis/href-counter/app    .
CMD ["./app"]  

The result would be two images, one for building, one with just the resulting app (much, much smaller)

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE

multi               latest              bcbbf69a9b59        6 minutes ago       10.3MB  
golang              1.7.3               ef15416724f6        4 months ago        672MB  

what is a base image?

A set of files, plus EXPOSE'd ports, ENTRYPOINT and CMD.
You can add files and build a new image based on that base image, with a new Dockerfile starting with a FROM directive: the image mentioned after FROM is "the base image" for your new image.

does it mean that if I declare neo4j/neo4j in a FROM directive, that when my image is run the neo database will automatically run and be available within the container on port 7474?

Only if you don't overwrite CMD and ENTRYPOINT.
But the image in itself is enough: you would use a FROM neo4j/neo4j if you had to add files related to neo4j for your particular usage of neo4j.

REST API - file (ie images) processing - best practices

There are several decisions to make:

  1. The first about resource path:

    • Model the image as a resource on its own:

      • Nested in user (/user/:id/image): the relationship between the user and the image is made implicitly

      • In the root path (/image):

        • The client is held responsible for establishing the relationship between the image and the user, or;

        • If a security context is being provided with the POST request used to create an image, the server can implicitly establish a relationship between the authenticated user and the image.

    • Embed the image as part of the user

  2. The second decision is about how to represent the image resource:

    • As Base 64 encoded JSON payload
    • As a multipart payload

This would be my decision track:

  • I usually favor design over performance unless there is a strong case for it. It makes the system more maintainable and can be more easily understood by integrators.
  • So my first thought is to go for a Base64 representation of the image resource because it lets you keep everything JSON. If you chose this option you can model the resource path as you like.
    • If the relationship between user and image is 1 to 1 I'd favor to model the image as an attribute specially if both data sets are updated at the same time. In any other case you can freely choose to model the image either as an attribute, updating the it via PUT or PATCH, or as a separate resource.
  • If you choose multipart payload I'd feel compelled to model the image as a resource on is own, so that other resources, in our case, the user resource, is not impacted by the decision of using a binary representation for the image.

Then comes the question: Is there any performance impact about choosing base64 vs multipart?. We could think that exchanging data in multipart format should be more efficient. But this article shows how little do both representations differ in terms of size.

My choice Base64:

  • Consistent design decision
  • Negligible performance impact
  • As browsers understand data URIs (base64 encoded images), there is no need to transform these if the client is a browser
  • I won't cast a vote on whether to have it as an attribute or standalone resource, it depends on your problem domain (which I don't know) and your personal preference.

Coerce multiple columns to factors at once

Here is a data.table example. I used grep in this example because that's how I often select many columns by using partial matches to their names.

library(data.table)
data <- data.table(matrix(sample(1:40), 4, 10, dimnames = list(1:4, LETTERS[1:10])))

factorCols <- grep(pattern = "A|C|D|H", x = names(data), value = TRUE)

data[, (factorCols) := lapply(.SD, as.factor), .SDcols = factorCols]

ES6 export default with multiple functions referring to each other

tl;dr: baz() { this.foo(); this.bar() }

In ES2015 this construct:

var obj = {
    foo() { console.log('foo') }
}

is equal to this ES5 code:

var obj = {
    foo : function foo() { console.log('foo') }
}

exports.default = {} is like creating an object, your default export translates to ES5 code like this:

exports['default'] = {
    foo: function foo() {
        console.log('foo');
    },
    bar: function bar() {
        console.log('bar');
    },
    baz: function baz() {
        foo();bar();
    }
};

now it's kind of obvious (I hope) that baz tries to call foo and bar defined somewhere in the outer scope, which are undefined. But this.foo and this.bar will resolve to the keys defined in exports['default'] object. So the default export referencing its own methods shold look like this:

export default {
    foo() { console.log('foo') }, 
    bar() { console.log('bar') },
    baz() { this.foo(); this.bar() }
}

See babel repl transpiled code.

Go To Definition: "Cannot navigate to the symbol under the caret."

I also came across this once. There is something wrong with TFS in VS 2015.

I followed these steps and it worked

  1. Cleared TFS Cache This might be here:

    C:\Users\(UserName)\AppData\Local\Microsoft\Team Foundation\(Version)\Cache

Note: path may vary based on operating system so don't blame me.

  1. Emptied Symbol Cache

    Tools > Options > Debugging > Symbols > EmptySymbolCache

  2. Restarted Visual Studio (It Might ask for connecting to TFS again)

This Worked for me.:)

How to Use Multiple Columns in Partition By And Ensure No Duplicate Row is Returned

Try this, It worked for me

SELECT * FROM (
            SELECT
                [Code],
                [Name],
                [CategoryCode],
                [CreatedDate],
                [ModifiedDate],
                [CreatedBy],
                [ModifiedBy],
                [IsActive],
                ROW_NUMBER() OVER(PARTITION BY [Code],[Name],[CategoryCode] ORDER BY ID DESC) rownumber
            FROM MasterTable
          ) a
        WHERE rownumber = 1 

crudrepository findBy method signature with multiple in operators?

The following signature will do:

List<Email> findByEmailIdInAndPincodeIn(List<String> emails, List<String> pinCodes);

Spring Data JPA supports a large number of keywords to build a query. IN and AND are among them.

What do multiple arrow functions mean in javascript?

Brief and simple

It is a function which returns another function written in short way.

const handleChange = field => e => {
  e.preventDefault()
  // Do something here
}

// is equal to 
function handleChange(field) {
  return function(e) {
    e.preventDefault()
    // Do something here
  }
}

Why people do it ?

Have you faced when you need to write a function which can be customized? Or you have to write a callback function which has fixed parameters (arguments), but you need to pass more variables to the function but avoiding global variables? If your answer "yes" then it is the way how to do it.

For example we have a button with onClick callback. And we need to pass id to the function, but onClick accepts only one parameter event, we can not pass extra parameters within like this:

const handleClick = (event, id) {
  event.preventDefault()
  // Dispatch some delete action by passing record id
}

It will not work!

Therefore we make a function which will return other function with its own scope of variables without any global variables, because global variables are evil .

Below the function handleClick(props.id)} will be called and return a function and it will have id in its scope! No matter how many times it will be pressed the ids will not effect or change each other, they are totally isolated.

const handleClick = id => event {
  event.preventDefault()
  // Dispatch some delete action by passing record id
}

const Confirm = props => (
  <div>
    <h1>Are you sure to delete?</h1>
    <button onClick={handleClick(props.id)}>
      Delete
    </button>
  </div
)

Other benefit

A function which returns another function also called "curried functions" and they are used for function compositions.

You can find example here: https://gist.github.com/sultan99/13ef56b4089789a8d115869ee2c5ec47

Is there any way to configure multiple registries in a single npmrc file

My approach was to make a slight command line variant that adds the registry switch.

I created these files in the nodejs folder where the npm executable is found:

npm-.cmd:

@ECHO OFF
npm --registry https://registry.npmjs.org %*

npm-:

#!/bin/sh
"npm" --registry https://registry.npmjs.org "$@"

Now, if I want to do an operation against the normal npm registry (while I am not connected to the VPN), I just type npm- where I would usually type npm.

To test this command and see the registry for a package, use this example:

npm- view lodash

PS. I am in windows and have tested this in Bash, CMD, and Powershell. I also

Dynamically Add Images React Webpack

If you are looking for a way to import all your images from the image

// Import all images in image folder
function importAll(r) {
    let images = {};
    r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); });
    return images;
}

const images = importAll(require.context('../images', false, /\.(gif|jpe?g|svg)$/));

Then:

<img src={images['image-01.jpg']}/>

You can find the original thread here: Dynamically import images from a directory using webpack

Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response

This problem solved with

 "Origin, X-Requested-With, Content-Type, Accept, Authorization"

Particular in my project (express.js/nodejs)

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
  next();
});

Update:

Every time error: Access-Control-Allow-Headers is not allowed by itself in preflight response error you can see what wrong with chrome developer tool:
enter image description here

above error is missing Content-Type so add string Content-Type to Access-Control-Allow-Headers

form with no action and where enter does not reload page

The first response is the best solution:

Add an onsubmit handler to the form (either via plain js or jquery $().submit(fn)), and return false unless your specific conditions are met.

More specific with jquery:

$('#your-form-id').submit(function(){return false;});

Unless you don't want the form to submit, ever - in which case, why not just leave out the 'action' attribute on the form element?

Writing Chrome extensions is an example of where you might have a form for user input, but you don't want it to submit. If you use action="javascript:void(0);", the code will probably work but you will end up with this problem where you get an error about running inline Javascript.

If you leave out the action completely, the form will reload which is also undesired in some cases when writing a Chrome extension. Or if you had a webpage with some sort of an embedded calculator, where the user would provide some input and click "Calculate" or something like that.

How do I put a variable inside a string?

If you would want to put multiple values into the string you could make use of format

nums = [1,2,3]
plot.savefig('hanning{0}{1}{2}.pdf'.format(*nums))

Would result in the string hanning123.pdf. This can be done with any array.

A function to convert null to string

public string nullToString(string value)
{
    return value == null ?string.Empty: value;   
}

How to determine when a Git branch was created?

Combined with the answer from Andrew Sohn (https://stackoverflow.com/a/14265207/1929406)

branchcreated=$(git reflog show --date=format:'%Y-%m-%d %H:%M:%S' --all | sed 's!^.*refs/!refs/!' | grep '/master' | tail -1| cut -d'{' -f 2| cut -d'}' -f 1 | xargs)
echo $branchcreated

.NET code to send ZPL to Zebra printers

I've managed a project that does this with sockets for years. Zebra's typically use port 6101. I'll look through the code and post what I can.

public void SendData(string zpl)
{
    NetworkStream ns = null;
    Socket socket = null;

    try
    {
        if (printerIP == null)
        {
            /* IP is a string property for the printer's IP address. */
            /* 6101 is the common port of all our Zebra printers. */
            printerIP = new IPEndPoint(IPAddress.Parse(IP), 6101);  
        }

        socket = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream,
            ProtocolType.Tcp);
        socket.Connect(printerIP);

        ns = new NetworkStream(socket);

        byte[] toSend = Encoding.ASCII.GetBytes(zpl);
        ns.Write(toSend, 0, toSend.Length);
    }
    finally
    {
        if (ns != null)
            ns.Close();

        if (socket != null && socket.Connected)
            socket.Close();
    }
}

Converting dd/mm/yyyy formatted string to Datetime

use DateTime.ParseExact

string strDate = "24/01/2013";
DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", null)

null will use the current culture, which is somewhat dangerous. Try to supply a specific culture

DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", CultureInfo.InvariantCulture)

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

From python 3.5: merging and summing

Thanks to @tokeinizer_fsj that told me in a comment that I didn't get completely the meaning of the question (I thought that add meant just adding keys that eventually where different in the two dictinaries and, instead, i meant that the common key values should be summed). So I added that loop before the merging, so that the second dictionary contains the sum of the common keys. The last dictionary will be the one whose values will last in the new dictionary that is the result of the merging of the two, so I thing the problem is solved. The solution is valid from python 3.5 and following versions.

a = {
    "a": 1,
    "b": 2,
    "c": 3
}

b = {
    "a": 2,
    "b": 3,
    "d": 5
}

# Python 3.5

for key in b:
    if key in a:
        b[key] = b[key] + a[key]

c = {**a, **b}
print(c)

>>> c
{'a': 3, 'b': 5, 'c': 3, 'd': 5}

Reusable code

a = {'a': 1, 'b': 2, 'c': 3}
b = {'b': 3, 'c': 4, 'd': 5}


def mergsum(a, b):
    for k in b:
        if k in a:
            b[k] = b[k] + a[k]
    c = {**a, **b}
    return c


print(mergsum(a, b))

File content into unix variable with newlines

This is due to IFS (Internal Field Separator) variable which contains newline.

$ cat xx1
1
2

$ A=`cat xx1`
$ echo $A
1 2

$ echo "|$IFS|"
|       
|

A workaround is to reset IFS to not contain the newline, temporarily:

$ IFSBAK=$IFS
$ IFS=" "
$ A=`cat xx1` # Can use $() as well
$ echo $A
1
2
$ IFS=$IFSBAK

To REVERT this horrible change for IFS:

IFS=$IFSBAK

Multi-gradient shapes

Try this method then you can do every thing you want.
It is like a stack so be careful which item comes first or last.

<?xml version="1.0" encoding="utf-8"?>
<layer-list
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:right="50dp" android:start="10dp" android:left="10dp">
    <shape
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
        <corners android:radius="3dp" />
        <solid android:color="#012d08"/>
    </shape>
</item>
<item android:top="50dp">
    <shape android:shape="rectangle">
        <solid android:color="#7c4b4b" />
    </shape>
</item>
<item android:top="90dp" android:end="60dp">
    <shape android:shape="rectangle">
        <solid android:color="#e2cc2626" />
    </shape>
</item>
<item android:start="50dp" android:bottom="20dp" android:top="120dp">
    <shape android:shape="rectangle">
        <solid android:color="#360e0e" />
    </shape>
</item>

What is best way to start and stop hadoop ecosystem, with command line?

Starting

start-dfs.sh (starts the namenode and the datanode)
start-mapred.sh (starts the jobtracker and the tasktracker)

Stopping

stop-dfs.sh
stop-mapred.sh

Getting value GET OR POST variable using JavaScript?

Here is my answer for this given a string returnURL which is like http://host.com/?param1=abc&param2=cde. It's fairly basic as I'm beginning at JavaScript (this is actually part of my first program ever in JS), and making it simpler to understand rather than tricky.

Notes

  • No sanity checking of values
  • Just outputting to the console - you'll want to store them in an array or something
  • this is only for GET, and not POST

    var paramindex = returnURL.indexOf('?');
    if (paramindex > 0) {
        var paramstring = returnURL.split('?')[1];
        while (paramindex > 0) {
            paramindex = paramstring.indexOf('=');
            if (paramindex > 0) {
                var parkey = paramstring.substr(0,paramindex);
                console.log(parkey)
                paramstring = paramstring.substr(paramindex+1) // +1 to strip out the =
            }
            paramindex = paramstring.indexOf('&');
            if (paramindex > 0) {
                var parvalue = paramstring.substr(0,paramindex);
                console.log(parvalue)
                paramstring = paramstring.substr(paramindex+1) // +1 to strip out the &
            } else { // we're at the end of the URL
                var parvalue = paramstring
                console.log(parvalue)
                break;
            }
        }
    }
    

How to use orderby with 2 fields in linq?

MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate);

How to find a value in an array and remove it by using PHP array functions?

This is how I would do it:

$terms = array('BMW', 'Audi', 'Porsche', 'Honda');
// -- purge 'make' Porsche from terms --
if (!empty($terms)) {
    $pos = '';
    $pos = array_search('Porsche', $terms);
    if ($pos !== false) unset($terms[$pos]);
}

Save results to csv file with Python

You can close files not csv.writer object, it should be:

f = open(fileName, "wb")
writer = csv.writer(f)
String[] entries = "first*second*third".split("*");
writer.writerows(entries)
f.close()

How do I get the name of the rows from the index of a data frame?

df.index

  • outputs the row names as pandas Index object.

list(df.index)

  • casts to a list.

df.index['Row 2':'Row 5']

  • supports label slicing similar to columns.

How to get post slug from post in WordPress?

You can get that using the following methods:

<?php $post_slug = get_post_field( 'post_name', get_post() ); ?>

Or You can use this easy code:

<?php
    global $post;
    $post_slug = $post->post_name;
?>

"SSL certificate verify failed" using pip to install packages

Something to try --- tell python to not use https with the index directive and a http:// address (not https://)

pip install --index-url=http://pypi.python.org/simple/ --trusted-host pypi.python.org  Scrapy

You may be behind a corporate firewall and Ive have experiences where even the above failed, though Im not going to pretend like I know enough about firewalls or SSL to understand why. In that case the only way I was able to get around that was to get a certificate file and pass it to python. See kenorb’s answer here for details.

how to check which version of nltk, scikit learn installed?

Try this:

$ python -c "import nltk; print nltk.__version__"

Python and JSON - TypeError list indices must be integers not str

I solved changing

readable_json['firstName']

by

readable_json[0]['firstName']

How to re-create database for Entity Framework?

A possible very simple fix that worked for me. After deleting any database references and connections you find in server/serverobject explorer, right click the App_Data folder (didn't show any objects within the application for me) and select open. Once open put all the database/etc. files in a backup folder or if you have the guts just delete them. Run your application and it should recreate everything from scratch.

How to find when a web page was last updated

For checking the Last Modified header, you can use httpie (docs).

Installation

pip install httpie --user

Usage

$ http -h https://martin-thoma.com/author/martin-thoma/ | grep 'Last-Modified\|Date'
Date: Fri, 06 Jan 2017 10:06:43 GMT
Last-Modified: Fri, 06 Jan 2017 07:42:34 GMT

The Date is important as this reports the server time, not your local time. Also, not every server sends Last-Modified (e.g. superuser seems not to do it).

Error during SSL Handshake with remote server

The comment by MK pointed me in the right direction.

In the case of Apache 2.4 and up, there are different defaults and a new directive.

I am running Apache 2.4.6, and I had to add the following directives to get it working:

SSLProxyEngine on
SSLProxyVerify none 
SSLProxyCheckPeerCN off
SSLProxyCheckPeerName off
SSLProxyCheckPeerExpire off

Cannot delete directory with Directory.Delete(path, true)

The directory or a file in it is locked and cannot be deleted. Find the culprit who locks it and see if you can eliminate it.

How to echo xml file in php

This worked for me:

echo(header('content-type: text/xml'));

Convert a String In C++ To Upper Case

ALL of these solutions on this page are harder than they need to be.

Do this

RegName = "SomE StRing That you wAnt ConvErTed";
NameLength = RegName.Size();
for (int forLoop = 0; forLoop < NameLength; ++forLoop)
{
     RegName[forLoop] = tolower(RegName[forLoop]);
}

RegName is your string. Get your string size don't use string.size() as your actual tester, very messy and can cause issues. then. the most basic for loop.

remember string size returns the delimiter too so use < and not <= in your loop test.

output will be: some string that you want converted

How do I access command line arguments in Python?

Python tutorial explains it:

import sys

print(sys.argv)

More specifically, if you run python example.py one two three:

>>> import sys
>>> print(sys.argv)
['example.py', 'one', 'two', 'three']

Saving a select count(*) value to an integer (SQL Server)

Declare @MyInt int
Set @MyInt = ( Select Count(*) From MyTable )

If @MyInt > 0
Begin
    Print 'There''s something in the table'
End

I'm not sure if this is your issue, but you have to esacpe the single quote in the print statement with a second single quote. While you can use SELECT to populate the variable, using SET as you have done here is just fine and clearer IMO. In addition, you can be guaranteed that Count(*) will never return a negative value so you need only check whether it is greater than zero.

'if' in prolog?

Yes, there is such a control construct in ISO Prolog, called ->. You use it like this:

( condition -> then_clause ; else_clause )

Here is an example that uses a chain of else-if-clauses:

(   X < 0 ->
    writeln('X is negative.  That's weird!  Failing now.'),
    fail
;   X =:= 0 ->
    writeln('X is zero.')
;   writeln('X is positive.')
)

Note that if you omit the else-clause, the condition failing will mean that the whole if-statement will fail. Therefore, I recommend always including the else-clause (even if it is just true).

Catching errors in Angular HttpClient

The worse thing is not having a decent stack trace which you simply cannot generate using an HttpInterceptor (hope to stand corrected). All you get is a load of zone and rxjs useless bloat, and not the line or class that generated the error.

To do this you will need to generate a stack in an extended HttpClient, so its not advisable to do this in a production environment.

/**
 * Extended HttpClient that generates a stack trace on error when not in a production build.
 */
@Injectable()
export class TraceHttpClient extends HttpClient {
  constructor(handler: HttpHandler) {
    super(handler);
  }

  request(...args: [any]): Observable<any> {
    const stack = environment.production ? null : Error().stack;
    return super.request(...args).pipe(
      catchError((err) => {
        // tslint:disable-next-line:no-console
        if (stack) console.error('HTTP Client error stack\n', stack);
        return throwError(err);
      })
    );
  }
}

Programmatic equivalent of default(Type)

If you're using .NET 4.0 or above and you want a programmatic version that isn't a codification of rules defined outside of code, you can create an Expression, compile and run it on-the-fly.

The following extension method will take a Type and get the value returned from default(T) through the Default method on the Expression class:

public static T GetDefaultValue<T>()
{
    // We want an Func<T> which returns the default.
    // Create that expression here.
    Expression<Func<T>> e = Expression.Lambda<Func<T>>(
        // The default value, always get what the *code* tells us.
        Expression.Default(typeof(T))
    );

    // Compile and return the value.
    return e.Compile()();
}

public static object GetDefaultValue(this Type type)
{
    // Validate parameters.
    if (type == null) throw new ArgumentNullException("type");

    // We want an Func<object> which returns the default.
    // Create that expression here.
    Expression<Func<object>> e = Expression.Lambda<Func<object>>(
        // Have to convert to object.
        Expression.Convert(
            // The default value, always get what the *code* tells us.
            Expression.Default(type), typeof(object)
        )
    );

    // Compile and return the value.
    return e.Compile()();
}

You should also cache the above value based on the Type, but be aware if you're calling this for a large number of Type instances, and don't use it constantly, the memory consumed by the cache might outweigh the benefits.

Uncaught TypeError: Cannot read property 'ownerDocument' of undefined

If you use ES6 anon functions, it will conflict with $(this)

This works:

$('.dna-list').on('click', '.card', function(e) {
  console.log($(this));
});

This doesn't work:

$('.dna-list').on('click', '.card', (e) => {
  console.log($(this));
});

How can I find out if an .EXE has Command-Line Options?

The easiest way would be to use use ProcessExplorer but it would still require some searching.

Make sure your exe is running and open ProcessExplorer. In ProcessExplorer find the name of your binary file and double click it to show properties. Click the Strings tab. Search down the list of string found in the binary file. Most strings will be garbage so they can be ignored. Search for anything that might possibly resemble a command line switch. Test this switch from the command line and see if it does anything.

Note that it might be your binary simply has no command line switches.

For reference here is the above steps applied to the Chrome executable. The command line switches accepted by Chrome can be seen in the list:

Process explorer analyzing Chrome.exe

What is the difference between i++ and ++i?

Oddly it looks like the other two answers don't spell it out, and it's definitely worth saying:


i++ means 'tell me the value of i, then increment'

++i means 'increment i, then tell me the value'


They are Pre-increment, post-increment operators. In both cases the variable is incremented, but if you were to take the value of both expressions in exactly the same cases, the result will differ.

How to make Java Set?

Like this:

import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);

Or adding from an Array/ or multiple literals; wrap to a list, first.

Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b));         // from an array variable
b.addAll( Arrays.asList( 8, 9, 10));  // from literals

To get the intersection:

// copies all from A;  then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print;   r.toString() implied.
System.out.println("A intersect B="+r);

Hope this answer helps. Vote for it!

How to configure custom PYTHONPATH with VM and PyCharm?

Well you can do this by going to the interpreter's dialogue box. Click on the interpreter that you are using, and underneath it, you should see two tabs, one called Packages, and the other called Path.

Click on Path, and add your VM path to it.

WindowsError: [Error 126] The specified module could not be found

Also this could be that you have forgotten to set your working directory in eclipse to be the correct local for the application to run in.

What does the construct x = x || y mean?

|| is the boolean OR operator. As in javascript, undefined, null, 0, false are considered as falsy values.

It simply means

true || true = true
false || true = true
true || false = true
false || false = false

undefined || "value" = "value"
"value" || undefined = "value"
null || "value" = "value"
"value" || null = "value"
0 || "value" = "value"
"value" || 0 = "value"
false || "value" = "value"
"value" || false = "value"

Difference between Width:100% and width:100vw?

vw and vh stand for viewport width and viewport height respectively.

The difference between using width: 100vw instead of width: 100% is that while 100% will make the element fit all the space available, the viewport width has a specific measure, in this case the width of the available screen, including the document margin.

If you set the style body { margin: 0 }, 100vw should behave the same as 100%.

Additional notes

Using vw as unit for everything in your website, including font sizes and heights, will make it so that the site is always displayed proportionally to the device's screen width regardless of it's resolution. This makes it super easy to ensure your website is displayed properly in both workstation and mobile.

You can set font-size: 1vw (or whatever size suits your project) in your body CSS and everything specified in rem units will automatically scale according to the device screen, so it's easy to port existing projects and even frameworks (such as Bootstrap) to this concept.

Which equals operator (== vs ===) should be used in JavaScript comparisons?

Why == is so unpredictable?

What do you get when you compare an empty string "" with the number zero 0?

true

Yep, that's right according to == an empty string and the number zero are the same time.

And it doesn't end there, here's another one:

'0' == false // true

Things get really weird with arrays.

[1] == true // true
[] == false // true
[[]] == false // true
[0] == false // true

Then weirder with strings

[1,2,3] == '1,2,3' // true - REALLY?!
'\r\n\t' == 0 // true - Come on!

It get's worse:

When is equal not equal?

let A = ''  // empty string
let B = 0   // zero
let C = '0' // zero string

A == B // true - ok... 
B == C // true - so far so good...
A == C // **FALSE** - Plot twist!

Let me say that again:

(A == B) && (B == C) // true
(A == C) // **FALSE**

And this is just the crazy stuff you get with primitives.

It's a whole new level of crazy when you use == with objects.

At this point your probably wondering...

Why does this happen?

Well it's because unlike "triple equals" (===) which just checks if two values are the same.

== does a whole bunch of other stuff.

It has special handling for functions, special handling for nulls, undefined, strings, you name it.

It get's pretty wacky.

In fact, if you tried to write a function that does what == does it would look something like this:

function isEqual(x, y) { // if `==` were a function
    if(typeof y === typeof x) return y === x;
    // treat null and undefined the same
    var xIsNothing = (y === undefined) || (y === null);
    var yIsNothing = (x === undefined) || (x === null);

    if(xIsNothing || yIsNothing) return (xIsNothing && yIsNothing);

    if(typeof y === "function" || typeof x === "function") {
        // if either value is a string 
        // convert the function into a string and compare
        if(typeof x === "string") {
            return x === y.toString();
        } else if(typeof y === "string") {
            return x.toString() === y;
        } 
        return false;
    }

    if(typeof x === "object") x = toPrimitive(x);
    if(typeof y === "object") y = toPrimitive(y);
    if(typeof y === typeof x) return y === x;

    // convert x and y into numbers if they are not already use the "+" trick
    if(typeof x !== "number") x = +x;
    if(typeof y !== "number") y = +y;
    // actually the real `==` is even more complicated than this, especially in ES6
    return x === y;
}

function toPrimitive(obj) {
    var value = obj.valueOf();
    if(obj !== value) return value;
    return obj.toString();
}

So what does this mean?

It means == is complicated.

Because it's complicated it's hard to know what's going to happen when you use it.

Which means you could end up with bugs.

So the moral of the story is...

Make your life less complicated.

Use === instead of ==.

The End.

SELECT using 'CASE' in SQL

Change to:

SELECT 
  CASE 
    WHEN FRUIT = 'A' THEN 'APPLE' 
    WHEN FRUIT = 'B' THEN 'BANANA'     
  END
FROM FRUIT_TABLE;

C++ for each, pulling from vector elements

This is how it would be done in a loop in C++(11):

   for (const auto& attack : m_attack)
    {  
        if (attack->m_num == input)
        {
            attack->makeDamage();
        }
    }

There is no for each in C++. Another option is to use std::for_each with a suitable functor (this could be anything that can be called with an Attack* as argument).

how to delete all cookies of my website in php

All previous answers have overlooked that the setcookie could have been used with an explicit domain. Furthermore, the cookie might have been set on a higher subdomain, e.g. if you were on a foo.bar.tar.com domain, there might be a cookie set on tar.com. Therefore, you want to unset cookies for all domains that might have dropped the cookie:

$host = explode('.', $_SERVER['HTTP_HOST']);

while ($host) {
    $domain = '.' . implode('.', $host);

    foreach ($_COOKIE as $name => $value) {
        setcookie($name, '', 1, '/', $domain);
    }

    array_shift($host);
}

Why is JavaFX is not included in OpenJDK 8 on Ubuntu Wily (15.10)?

I use ubuntu 16.04 and because I already had openJDK installed, this command have solved the problem. Don't forget that JavaFX is part of OpenJDK.

sudo apt-get install openjfx

How to generate and validate a software license key?

I'm one of the developers behind the Cryptolens software licensing platform and have been working on licensing systems since the age of 14. In this answer, I have included some tips based on experience acquired over the years.

The best way of solving this is by setting up a license key server that each instance of the application will call in order to verify a license key.

Benefits of a license key server

The advantages with a license key server is that:

  1. you can always update or block a license key with immediate effect.
  2. each license key can be locked to certain number of machines (this helps to prevent users from publishing the license key online for others to use).

Considerations

Although verifying licenses online gives you more control over each instance of the application, internet connection is not always present (especially if you target larger enterprises), so we need another way of performing the license key verification.

The solution is to always sign the license key response from the server using a public-key cryptosystem such as RSA or ECC (possibly better if you plan to run on embedded systems). Your application should only have the public key to verify the license key response.

So in case there's no internet connection, you can use the previous license key response instead. Make sure to store both the date and the machine identifier in the response and check that it's not too old (eg. you allow users to be offline at most 30 days, etc) and that the license key response belongs to the correct device.

Note you should always check the certificate of license key response, even if you are connected to the internet), in order to ensure that it has not been changed since it left the server (this still has to be done even if your API to the license key server uses https)

Protecting secret algorithms

Most .NET applications can be reverse engineered quite easily (there is both a diassembler provided by Microsoft to get the IL code and some commercial products can even retrieve the source code in eg. C#). Of course, you can always obfuscate the code, but it's never 100% secure.

I most cases, the purpose of any software licensing solution is to help honest people being honest (i.e. that honest users who are willing to pay don't forget to pay after a trial expires, etc).

However, you may still have some code that you by no means want to leak out to the public (eg. an algorithm to predict stock prices, etc). In this case, the only way to go is to create an API endpoint that your application will call each time the method should be executed. It requires internet connection but it ensures that your secret code is never executed by the client machine.

Implementation

If you don't want to implement everything yourself, I would recommend to take a look at this tutorial (part of Cryptolens)

Using $state methods with $stateChangeStart toState and fromState in Angular ui-router

Suggestion 1

When you add an object to $stateProvider.state that object is then passed with the state. So you can add additional properties which you can read later on when needed.

Example route configuration

$stateProvider
.state('public', {
    abstract: true,
    module: 'public'
})
.state('public.login', {
    url: '/login',
    module: 'public'
})
.state('tool', {
    abstract: true,
    module: 'private'
})
.state('tool.suggestions', {
    url: '/suggestions',
    module: 'private'
});

The $stateChangeStart event gives you acces to the toState and fromState objects. These state objects will contain the configuration properties.

Example check for the custom module property

$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
    if (toState.module === 'private' && !$cookies.Session) {
        // If logged out and transitioning to a logged in page:
        e.preventDefault();
        $state.go('public.login');
    } else if (toState.module === 'public' && $cookies.Session) {
        // If logged in and transitioning to a logged out page:
        e.preventDefault();
        $state.go('tool.suggestions');
    };
});

I didn't change the logic of the cookies because I think that is out of scope for your question.

Suggestion 2

You can create a Helper to get you this to work more modular.

Value publicStates

myApp.value('publicStates', function(){
    return {
      module: 'public',
      routes: [{
        name: 'login', 
        config: { 
          url: '/login'
        }
      }]
    };
});

Value privateStates

myApp.value('privateStates', function(){
    return {
      module: 'private',
      routes: [{
        name: 'suggestions', 
        config: { 
          url: '/suggestions'
        }
      }]
    };
});

The Helper

myApp.provider('stateshelperConfig', function () {
  this.config = {
    // These are the properties we need to set
    // $stateProvider: undefined
    process: function (stateConfigs){
      var module = stateConfigs.module;
      $stateProvider = this.$stateProvider;
      $stateProvider.state(module, {
        abstract: true,
        module: module
      });
      angular.forEach(stateConfigs, function (route){
        route.config.module = module;
        $stateProvider.state(module + route.name, route.config);
      });
    }
  };

  this.$get = function () {
    return {
      config: this.config
    };
  };
});

Now you can use the helper to add the state configuration to your state configuration.

myApp.config(['$stateProvider', '$urlRouterProvider', 
    'stateshelperConfigProvider', 'publicStates', 'privateStates',
  function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
    helper.config.$stateProvider = $stateProvider;
    helper.process(publicStates);
    helper.process(privateStates);
}]);

This way you can abstract the repeated code, and come up with a more modular solution.

Note: the code above isn't tested

Xml Parsing in C#

First add an Enrty and Category class:

public class Entry {     public string Id { get; set; }     public string Title { get; set; }     public string Updated { get; set; }     public string Summary { get; set; }     public string GPoint { get; set; }     public string GElev { get; set; }     public List<string> Categories { get; set; } }  public class Category {     public string Label { get; set; }     public string Term { get; set; } } 

Then use LINQ to XML

XDocument xDoc = XDocument.Load("path");          List<Entry> entries = (from x in xDoc.Descendants("entry")             select new Entry()             {                 Id = (string) x.Element("id"),                 Title = (string)x.Element("title"),                 Updated = (string)x.Element("updated"),                 Summary = (string)x.Element("summary"),                 GPoint = (string)x.Element("georss:point"),                 GElev = (string)x.Element("georss:elev"),                 Categories = (from c in x.Elements("category")                                   select new Category                                   {                                       Label = (string)c.Attribute("label"),                                       Term = (string)c.Attribute("term")                                   }).ToList();             }).ToList(); 

Excluding Maven dependencies

You can utilize the dependency management mechanism.

If you create entries in the <dependencyManagement> section of your pom for spring-security-web and spring-web with the desired 3.1.0 version set the managed version of the artifact will override those specified in the transitive dependency tree.

I'm not sure if that really saves you any code, but it is a cleaner solution IMO.

how to change listen port from default 7001 to something different?

Simplest option ...your can change it from AdminConsole. Login to AdminConsole--->Server-->--->Configuration--->ListenPort (Change it)!

iOS Detection of Screenshot?

Heres how to do in Swift with closures:

func detectScreenShot(action: () -> ()) {
    let mainQueue = NSOperationQueue.mainQueue()
    NSNotificationCenter.defaultCenter().addObserverForName(UIApplicationUserDidTakeScreenshotNotification, object: nil, queue: mainQueue) { notification in
        // executes after screenshot
        action()
    }
}

detectScreenShot { () -> () in
    print("User took a screen shot")
}

Swift 4.2

func detectScreenShot(action: @escaping () -> ()) {
    let mainQueue = OperationQueue.main
    NotificationCenter.default.addObserver(forName: UIApplication.userDidTakeScreenshotNotification, object: nil, queue: mainQueue) { notification in
        // executes after screenshot
        action()
    }
}

This is included as a standard function in:

https://github.com/goktugyil/EZSwiftExtensions

Disclaimer: Its my repo

FCM getting MismatchSenderId

  • I cross verified all the credentials

  • Added new server key and deleted old one

  • Downloaded google-services.json again

Nothing solved the issue

Then I just clean the project and then rebuild the project.After that it's working fine

Jersey Exception : SEVERE: A message body reader for Java class

I was able to fix the issue by adding the maven dependency for jersey-json.

Testing two JSON objects for equality ignoring child order in Java

Try this:

public static boolean jsonsEqual(Object obj1, Object obj2) throws JSONException

    {
        if (!obj1.getClass().equals(obj2.getClass()))
        {
            return false;
        }

        if (obj1 instanceof JSONObject)
        {
            JSONObject jsonObj1 = (JSONObject) obj1;

            JSONObject jsonObj2 = (JSONObject) obj2;

            String[] names = JSONObject.getNames(jsonObj1);
            String[] names2 = JSONObject.getNames(jsonObj1);
            if (names.length != names2.length)
            {
                return false;
            }

            for (String fieldName:names)
            {
                Object obj1FieldValue = jsonObj1.get(fieldName);

                Object obj2FieldValue = jsonObj2.get(fieldName);

                if (!jsonsEqual(obj1FieldValue, obj2FieldValue))
                {
                    return false;
                }
            }
        }
        else if (obj1 instanceof JSONArray)
        {
            JSONArray obj1Array = (JSONArray) obj1;
            JSONArray obj2Array = (JSONArray) obj2;

            if (obj1Array.length() != obj2Array.length())
            {
                return false;
            }

            for (int i = 0; i < obj1Array.length(); i++)
            {
                boolean matchFound = false;

                for (int j = 0; j < obj2Array.length(); j++)
                {
                    if (jsonsEqual(obj1Array.get(i), obj2Array.get(j)))
                    {
                        matchFound = true;
                        break;
                    }
                }

                if (!matchFound)
                {
                    return false;
                }
            }
        }
        else
        {
            if (!obj1.equals(obj2))
            {
                return false;
            }
        }

        return true;
    }

Different class for the last element in ng-repeat

You could use limitTo filter with -1 for find the last element

Example :

<div ng-repeat="friend in friends | limitTo: -1">
    {{friend.name}}
</div>

How to use comparison and ' if not' in python?

There are two ways. In case of doubt, you can always just try it. If it does not work, you can add extra braces to make sure, like that:

if not ((u0 <= u) and (u < u0+step)):

How can I create a small color box using html and css?

If you want to create a small dots, just use icon from font awesome.

fa fa-circle

MySQL server has gone away - in exactly 60 seconds

There's a whole bunch of things that can cause this. I'd read through these and try each of them

http://dev.mysql.com/doc/refman/5.1/en/gone-away.html

I've worked for several web hosting companies over the years and generally when I see this, it is the wait_timeout on the server end though this doesn't appear to be the case here.

If you find the solution, I hope you post it. I'd like to know.

Retrieving a Foreign Key value with django-rest-framework serializers

Just use a related field without setting many=True.

Note that also because you want the output named category_name, but the actual field is category, you need to use the source argument on the serializer field.

The following should give you the output you need...

class ItemSerializer(serializers.ModelSerializer):
    category_name = serializers.RelatedField(source='category', read_only=True)

    class Meta:
        model = Item
        fields = ('id', 'name', 'category_name')

Insert string in beginning of another string

It is better if you find quotation marks by using the indexof() method and then add a string behind that index.

string s="hai";
int s=s.indexof(""");

How can I set the Secure flag on an ASP.NET Session Cookie?

In the <system.web> element, add the following element:

<httpCookies requireSSL="true" />

However, if you have a <forms> element in your system.web\authentication block, then this will override the setting in httpCookies, setting it back to the default false.

In that case, you need to add the requireSSL="true" attribute to the forms element as well.

So you will end up with:

<system.web>
    <authentication mode="Forms">
        <forms requireSSL="true">
            <!-- forms content -->
        </forms>
    </authentication>
</system.web>

See here and here for MSDN documentation of these elements.

How to [recursively] Zip a directory in PHP?

I've edited Alix Axel's answer to take a third argrument, when setting this third argrument to true all the files will be added under the main directory rather than directly in the zip folder.

If the zip file exists the file will be deleted as well.

Example:

Zip('/path/to/maindirectory','/path/to/compressed.zip',true);

Third argrument true zip structure:

maindirectory
--- file 1
--- file 2
--- subdirectory 1
------ file 3
------ file 4
--- subdirectory 2
------ file 5
------ file 6

Third argrument false or missing zip structure:

file 1
file 2
subdirectory 1
--- file 3
--- file 4
subdirectory 2
--- file 5
--- file 6

Edited code:

function Zip($source, $destination, $include_dir = false)
{

    if (!extension_loaded('zip') || !file_exists($source)) {
        return false;
    }

    if (file_exists($destination)) {
        unlink ($destination);
    }

    $zip = new ZipArchive();
    if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
        return false;
    }
    $source = str_replace('\\', '/', realpath($source));

    if (is_dir($source) === true)
    {

        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

        if ($include_dir) {

            $arr = explode("/",$source);
            $maindir = $arr[count($arr)- 1];

            $source = "";
            for ($i=0; $i < count($arr) - 1; $i++) { 
                $source .= '/' . $arr[$i];
            }

            $source = substr($source, 1);

            $zip->addEmptyDir($maindir);

        }

        foreach ($files as $file)
        {
            $file = str_replace('\\', '/', $file);

            // Ignore "." and ".." folders
            if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
                continue;

            $file = realpath($file);

            if (is_dir($file) === true)
            {
                $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
            }
            else if (is_file($file) === true)
            {
                $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
            }
        }
    }
    else if (is_file($source) === true)
    {
        $zip->addFromString(basename($source), file_get_contents($source));
    }

    return $zip->close();
}

ReDim Preserve to a Multi-Dimensional Array in Visual Basic 6

I know this is a bit old but I think there might be a much simpler solution that requires no additional coding:

Instead of transposing, redimming and transposing again, and if we talk about a two dimensional array, why not just store the values transposed to begin with. In that case redim preserve actually increases the right (second) dimension from the start. Or in other words, to visualise it, why not store in two rows instead of two columns if only the nr of columns can be increased with redim preserve.

the indexes would than be 00-01, 01-11, 02-12, 03-13, 04-14, 05-15 ... 0 25-1 25 etcetera instead of 00-01, 10-11, 20-21, 30-31, 40-41 etcetera.

As long as there is only one dimension that needs to be redimmed-preserved the approach would still work: just put that dimension last.

As only the second (or last) dimension can be preserved while redimming, one could maybe argue that this is how arrays are supposed to be used to begin with. I have not seen this solution anywhere so maybe I'm overlooking something?

(Posted earlier on similar question regarding two dimensions, extended answer here for more dimensions)

Android intent for playing video?

following code works just fine for me.

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(movieurl));
startActivity(intent);

How do I get the list of keys in a Dictionary?

I often used this to get the key and value inside a dictionary: (VB.Net)

 For Each kv As KeyValuePair(Of String, Integer) In layerList

 Next

(layerList is of type Dictionary(Of String, Integer))

Given URL is not permitted by the application configuration

  1. From the menu item of your app name which is located on the top left corner, create a test app.
  2. In the settings section of the new test app: add 'http://localhost:3000' to the Website url and add 'localhost' to App domains.
  3. Update your app with the new Facebook APP Id
  4. Use Facebook sdk v2.2 or whatever the latest in your app.

Possible to iterate backwards through a foreach?

If you are on .NET 3.5 you can do this:

IEnumerable<int> enumerableThing = ...;
foreach (var x in enumerableThing.Reverse())

It isn't very efficient as it has to basically go through the enumerator forwards putting everything on a stack then pops everything back out in reverse order.

If you have a directly-indexable collection (e.g. IList) you should definitely use a for loop instead.

If you are on .NET 2.0 and cannot use a for loop (i.e. you just have an IEnumerable) then you will just have to write your own Reverse function. This should work:

static IEnumerable<T> Reverse<T>(IEnumerable<T> input)
{
    return new Stack<T>(input);
}

This relies on some behaviour which is perhaps not that obvious. When you pass in an IEnumerable to the stack constructor it will iterate through it and push the items onto the stack. When you then iterate through the stack it pops things back out in reverse order.

This and the .NET 3.5 Reverse() extension method will obviously blow up if you feed it an IEnumerable which never stops returning items.

Pass a variable to a PHP script running from the command line

if (isset($argv) && is_array($argv)) {
    $param = array();
    for ($x=1; $x<sizeof($argv);$x++) {
        $pattern = '#\/(.+)=(.+)#i';
        if (preg_match($pattern, $argv[$x])) {
            $key =  preg_replace($pattern, '$1', $argv[$x]);
            $val =  preg_replace($pattern, '$2', $argv[$x]);
            $_REQUEST[$key] = $val;
            $$key = $val;
        }
    }
}

I put parameters in $_REQUEST:

$_REQUEST[$key] = $val;

And it is also usable directly:

$$key=$val

Use it like this:

myFile.php /key=val

How to convert text column to datetime in SQL

This works:

SELECT STR_TO_DATE(dateColumn, '%c/%e/%Y %r') FROM tabbleName WHERE 1

nodemon not found in npm

You have to simply installed it globally. npm install -g nodemon

Format numbers in thousands (K) in Excel

[>=1000]#,##0,"K";[<=-1000]-#,##0,"K";0

teylyn's answer is great. This just adds negatives beyond -1000 following the same format.

Generating combinations in c++

A simple way using std::next_permutation:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    int n, r;
    std::cin >> n;
    std::cin >> r;

    std::vector<bool> v(n);
    std::fill(v.end() - r, v.end(), true);

    do {
        for (int i = 0; i < n; ++i) {
            if (v[i]) {
                std::cout << (i + 1) << " ";
            }
        }
        std::cout << "\n";
    } while (std::next_permutation(v.begin(), v.end()));
    return 0;
}

or a slight variation that outputs the results in an easier to follow order:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
   int n, r;
   std::cin >> n;
   std::cin >> r;

   std::vector<bool> v(n);
   std::fill(v.begin(), v.begin() + r, true);

   do {
       for (int i = 0; i < n; ++i) {
           if (v[i]) {
               std::cout << (i + 1) << " ";
           }
       }
       std::cout << "\n";
   } while (std::prev_permutation(v.begin(), v.end()));
   return 0;
}

A bit of explanation:

It works by creating a "selection array" (v), where we place r selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v.


You can implement it if you note that for each level r you select a number from 1 to n.

In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance

#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>

using namespace std;

struct combinations
{
    typedef vector<int> combination_t;

    // initialize status
   combinations(int N, int R) :
       completed(N < 1 || R > N),
       generated(0),
       N(N), R(R)
   {
       for (int c = 1; c <= R; ++c)
           curr.push_back(c);
   }

   // true while there are more solutions
   bool completed;

   // count how many generated
   int generated;

   // get current and compute next combination
   combination_t next()
   {
       combination_t ret = curr;

       // find what to increment
       completed = true;
       for (int i = R - 1; i >= 0; --i)
           if (curr[i] < N - R + i + 1)
           {
               int j = curr[i] + 1;
               while (i <= R-1)
                   curr[i++] = j++;
               completed = false;
               ++generated;
               break;
           }

       return ret;
   }

private:

   int N, R;
   combination_t curr;
};

int main(int argc, char **argv)
{
    int N = argc >= 2 ? atoi(argv[1]) : 5;
    int R = argc >= 3 ? atoi(argv[2]) : 2;
    combinations cs(N, R);
    while (!cs.completed)
    {
        combinations::combination_t c = cs.next();
        copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
        cout << endl;
    }
    return cs.generated;
}

test output:

1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,

string decode utf-8

Try looking at decode string encoded in utf-8 format in android but it doesn't look like your string is encoded with anything particular. What do you think the output should be?

R apply function with multiple parameters

Just pass var2 as an extra argument to one of the apply functions.

mylist <- list(a=1,b=2,c=3)
myfxn <- function(var1,var2){
  var1*var2
}
var2 <- 2

sapply(mylist,myfxn,var2=var2)

This passes the same var2 to every call of myfxn. If instead you want each call of myfxn to get the 1st/2nd/3rd/etc. element of both mylist and var2, then you're in mapply's domain.

How to use background thread in swift?

Swift 3.0+

A lot has been modernized in Swift 3.0. Running something on the background thread looks like this:

DispatchQueue.global(qos: .background).async {
    print("This is run on the background queue")

    DispatchQueue.main.async {
        print("This is run on the main queue, after the previous code in outer block")
    }
}

Swift 1.2 through 2.3

let qualityOfServiceClass = QOS_CLASS_BACKGROUND
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
dispatch_async(backgroundQueue, {
    print("This is run on the background queue")

    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        print("This is run on the main queue, after the previous code in outer block")
    })
})

Pre Swift 1.2 – Known issue

As of Swift 1.1 Apple didn't support the above syntax without some modifications. Passing QOS_CLASS_BACKGROUND didn't actually work, instead use Int(QOS_CLASS_BACKGROUND.value).

For more information see Apples documentation

How to submit a form when the return key is pressed?

Use the following script.

<SCRIPT TYPE="text/javascript">
<!--
    function submitenter(myfield,e)
    {
        var keycode;
        if (window.event) keycode = window.event.keyCode;
        else if (e) keycode = e.which;
        else return true;

        if (keycode == 13)
        {
            myfield.form.submit();
            return false;
        }
        else
            return true;
    }
//-->
</SCRIPT>

For each field that should submit the form when the user hits enter, call the submitenter function as follows.

<FORM ACTION="../cgi-bin/formaction.pl">
    name:     <INPUT NAME=realname SIZE=15><BR>
    password: <INPUT NAME=password TYPE=PASSWORD SIZE=10
       onKeyPress="return submitenter(this,event)"><BR>
<INPUT TYPE=SUBMIT VALUE="Submit">
</FORM>

exit application when click button - iOS

You can use exit method to quit an ios app :

exit(0);

You should say same alert message and ask him to quit

Another way is by using [[NSThread mainThread] exit]

However you should not do this way

According to Apple, your app should not terminate on its own. Since the user did not hit the Home button, any return to the Home screen gives the user the impression that your app crashed. This is confusing, non-standard behavior and should be avoided.

Simplest way to do grouped barplot

Not a barplot solution but using lattice and barchart:

library(lattice)
barchart(Species~Reason,data=Reasonstats,groups=Catergory, 
         scales=list(x=list(rot=90,cex=0.8)))

enter image description here

Can you have if-then-else logic in SQL?

--Similar answer as above for the most part. Code included to test

DROP TABLE table1
GO
CREATE TABLE table1 (project int, customer int, company int, product int, price money)
GO
INSERT INTO table1 VALUES (1,0,50, 100, 40),(1,0,20, 200, 55),(1,10,30,300, 75),(2,10,30,300, 75)
GO
SELECT TOP 1 WITH TIES product
        , price
        , CASE WhereFound WHEN 1 THEN 'Project'
                WHEN 2 THEN 'Customer'
                WHEN 3 THEN 'Company'
            ELSE 'No Match'
            END AS Source
FROM 
    (
     SELECT product, price, 1 as WhereFound FROM table1 where project = 11
     UNION ALL
     SELECT product, price, 2 FROM table1 where customer = 0
     UNION ALL
     SELECT product, price, 3 FROM table1 where company = 30
    ) AS tbl
ORDER BY WhereFound ASC

Recursively look for files with a specific extension

The syntax I use is a bit different than what @Matt suggested:

find $directory -type f -name \*.in

(it's one less keystroke).

How do you add swap to an EC2 instance?

Using David's Instance Storage answer initially worked for me (on a m5d.2xlarge) however, after stopping the EC2 instance and turning it back on, I was unable to ssh in to the instance again.

The instance logs reported: "You are in emergency mode. After logging in, type "journalctl -xb" to view system logs, "systemctl reboot" to reboot, "systemctl default" or "exit" to boot into default mode. Press Enter for maintenance"

I instead followed the AWS instructions in this link and everything worked perfectly, including after turning the instance off and on again.

https://aws.amazon.com/premiumsupport/knowledge-center/ec2-memory-swap-file/

sudo dd if=/dev/zero of=/swapfile bs=1G count=4

sudo chmod 600 /swapfile

sudo mkswap /swapfile

sudo swapon /swapfile

sudo swapon -s

sudo vi /etc/fstab
/swapfile swap swap defaults 0 0

How do I get information about an index and table owner in Oracle?

 select index_name, column_name
 from user_ind_columns
 where table_name = 'NAME';

OR use this:

select TABLE_NAME, OWNER 
from SYS.ALL_TABLES 
order by OWNER, TABLE_NAME 

And for Indexes:

select INDEX_NAME, TABLE_NAME, TABLE_OWNER 
from SYS.ALL_INDEXES 
order by TABLE_OWNER, TABLE_NAME, INDEX_NAME

Find if listA contains any elements not in listB

This piece of code compares two lists both containing a field for a CultureCode like 'en-GB'. This will leave non existing translations in the list. (we needed a dropdown list for not-translated languages for articles)

var compared = supportedLanguages.Where(sl => !existingTranslations.Any(fmt => fmt.CultureCode == sl.Culture)).ToList();

Shortcut to create properties in Visual Studio?

When you write in Visual Studio,

public ServiceTypesEnum Type { get; set; }
public string TypeString { get { return this.Type.ToString();}}

ReSharper will keep suggesting to convert it to:

public string TypeString => Type.ToString();

Lost connection to MySQL server at 'reading initial communication packet', system error: 0

I just set up mysql on a windows box. I got the OP's error when trying to connect with the Navicat MySql client on the same box. I had to specify 127.0.0.1 as the host, and that got it.

localhost, or the servers actual ip address both did not work.

What does servletcontext.getRealPath("/") mean and when should I use it

My Method:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        String path = request.getRealPath("/WEB-INF/conf.properties");
        Properties p = new Properties();
        p.load(new FileInputStream(path));

        String StringConexion=p.getProperty("StringConexion");
        String User=p.getProperty("User");
        String Password=p.getProperty("Password");
    }
    catch(Exception e){
        String msg = "Excepcion " + e;
    }
}

How to get number of rows using SqlDataReader in C#

If you do not need to retrieve all the row and want to avoid to make a double query, you can probably try something like that:

using (var sqlCon = new SqlConnection("Server=127.0.0.1;Database=MyDb;User Id=Me;Password=glop;"))
      {
        sqlCon.Open();

        var com = sqlCon.CreateCommand();
        com.CommandText = "select * from BigTable";
        using (var reader = com.ExecuteReader())
        {
            //here you retrieve what you need
        }

        com.CommandText = "select @@ROWCOUNT";
        var totalRow = com.ExecuteScalar();

        sqlCon.Close();
      }

You may have to add a transaction not sure if reusing the same command will automatically add a transaction on it...

C# Linq Where Date Between 2 Dates

If you have date interval filter condition and you need to select all records which falls partly into this filter range. Assumption: records has ValidFrom and ValidTo property.

DateTime intervalDateFrom = new DateTime(1990, 01, 01);
DateTime intervalDateTo = new DateTime(2000, 01, 01);

var itemsFiltered = allItems.Where(x=> 
    (x.ValidFrom >= intervalDateFrom && x.ValidFrom <= intervalDateTo) ||
    (x.ValidTo >= intervalDateFrom && x.ValidTo <= intervalDateTo) ||
    (intervalDateFrom >= x.ValidFrom && intervalDateFrom <= x.ValidTo) ||
    (intervalDateTo >= x.ValidFrom && intervalDateTo <= x.ValidTo)
);

Iterating each character in a string using Python

You can also do the following:

txt = "Hello World!"
print (*txt, sep='\n')

This does not use loops but internally print statement takes care of it.

* unpacks the string into a list and sends it to the print statement

sep='\n' will ensure that the next char is printed on a new line

The output will be:

H
e
l
l
o
 
W
o
r
l
d
!

If you do need a loop statement, then as others have mentioned, you can use a for loop like this:

for x in txt: print (x)

Remove duplicated rows

For people who have come here to look for a general answer for duplicate row removal, use !duplicated():

a <- c(rep("A", 3), rep("B", 3), rep("C",2))
b <- c(1,1,2,4,1,1,2,2)
df <-data.frame(a,b)

duplicated(df)
[1] FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE  TRUE

> df[duplicated(df), ]
  a b
2 A 1
6 B 1
8 C 2

> df[!duplicated(df), ]
  a b
1 A 1
3 A 2
4 B 4
5 B 1
7 C 2

Answer from: Removing duplicated rows from R data frame

How to convert float value to integer in php?

There is always intval() - Not sure if this is what you were looking for...

example: -

$floatValue = 4.5;
echo intval($floatValue);    // Returns 4

It won't round off the value to an integer, but will strip out the decimal and trailing digits, and return the integer before the decimal.

Here is some documentation for this: - http://php.net/manual/en/function.intval.php

How do I connect to a terminal to a serial-to-USB device on Ubuntu 10.10 (Maverick Meerkat)?

I had the exact same problem, and it was fixed by doing a chmod 777 /dev/ttyUSB0. I never had this error again, even though previously the only way to get it to work was to reboot the VM or unplug and replug the USB-to-serial adapter. I am running Ubuntu 10.04 (Lucid Lynx) VM on OS X.

How to write inside a DIV box with javascript

HTML:

<div id="log"></div>

JS:

document.getElementById("log").innerHTML="WHATEVER YOU WANT...";

Remove items from one list in another

As Except does not modify the list, you can use ForEach on List<T>:

list2.ForEach(item => list1.Remove(item));

It may not be the most efficient way, but it is simple, therefore readable, and it updates the original list (which is my requirement).

How can I implement a tree in Python?

A generic tree is a node with zero or more children, each one a proper (tree) node. It isn't the same as a binary tree, they're different data structures, although both shares some terminology.

There isn't any builtin data structure for generic trees in Python, but it's easily implemented with classes.

class Tree(object):
    "Generic tree node."
    def __init__(self, name='root', children=None):
        self.name = name
        self.children = []
        if children is not None:
            for child in children:
                self.add_child(child)
    def __repr__(self):
        return self.name
    def add_child(self, node):
        assert isinstance(node, Tree)
        self.children.append(node)
#    *
#   /|\
#  1 2 +
#     / \
#    3   4
t = Tree('*', [Tree('1'),
               Tree('2'),
               Tree('+', [Tree('3'),
                          Tree('4')])])

How to align a div inside td element using CSS class

div { margin: auto; }

This will center your div.

Div by itself is a blockelement. Therefor you need to define the style to the div how to behave.

How can I get the current screen orientation?

I just want to propose another alternative that will concern some of you :

android:configChanges="orientation|keyboardHidden" 

implies that we explicitly declare the layout to be injected.

In case we want to keep the automatic injection thanks to the layout-land and layout folders. All you have to do is add it to the onCreate:

    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        getSupportActionBar().hide();

    } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
        getSupportActionBar().show();
    }

Here, we display or not the actionbar depending on the orientation of the phone

PHP Parse error: syntax error, unexpected T_PUBLIC

You can remove public keyword from your functions, because, you have to define a class in order to declare public, private or protected function

Finding Variable Type in JavaScript

In JavaScript everything is an object

console.log(type of({}))  //Object
console.log(type of([]))  //Object

To get Real type , use this

console.log(Object.prototype.toString.call({}))   //[object Object]
console.log(Object.prototype.toString.call([]))   //[object Array]

Hope this helps

How to refresh materialized view in oracle

Try using the below syntax:

Common Syntax:

begin
dbms_mview.refresh('mview_name');
end;

Example:

begin
dbms_mview.refresh('inv_trans');
end;

Hope the above helps.

How to install Android SDK Build Tools on the command line?

android update sdk

This command will update and install all latest release for SDK Tools, Build Tools,SDK platform tools.

It's Work for me.

How do I erase an element from std::vector<> by index?

The previous answers assume that you always have a signed index. Sadly, std::vector uses size_type for indexing, and difference_type for iterator arithmetic, so they don't work together if you have "-Wconversion" and friends enabled. This is another way to answer the question, while being able to handle both signed and unsigned:

To remove:

template<class T, class I, class = typename std::enable_if<std::is_integral<I>::value>::type>
void remove(std::vector<T> &v, I index)
{
    const auto &iter = v.cbegin() + gsl::narrow_cast<typename std::vector<T>::difference_type>(index);
    v.erase(iter);
}

To take:

template<class T, class I, class = typename std::enable_if<std::is_integral<I>::value>::type>
T take(std::vector<T> &v, I index)
{
    const auto &iter = v.cbegin() + gsl::narrow_cast<typename std::vector<T>::difference_type>(index);

    auto val = *iter;
    v.erase(iter);

    return val;
}

ConcurrentHashMap vs Synchronized HashMap

A simple performance test for ConcurrentHashMap vs Synchronized HashMap . The test flow is calling put in one thread and calling get in three threads on Map concurrently. As @trshiv said, ConcurrentHashMap has higher throughput and speed for whose reading operation without lock. The result is when operation times is over 10^7, ConcurrentHashMap is 2x faster than Synchronized HashMap.

Check If only numeric values were entered in input. (jQuery)

I used this kind of validation .... checks the pasted text and if it contains alphabets, shows an error for user and then clear out the box after delay for the user to check the text and make appropriate changes.

$('#txtbox').on('paste', function (e) {
            var $this = $(this);
            setTimeout(function (e) {
                if (($this.val()).match(/[^0-9]/g))
                {
                    $("#errormsg").html("Only Numerical Characters allowed").show().delay(2500).fadeOut("slow");                       
                    setTimeout(function (e) {
                        $this.val(null);
                    },2500);
                }                   
            }, 5);
        });

How do I use the Tensorboard callback of Keras?

Create the Tensorboard callback:

from keras.callbacks import TensorBoard
from datetime import datetime
logDir = "./Graph/" + datetime.now().strftime("%Y%m%d-%H%M%S") + "/"
tb = TensorBoard(log_dir=logDir, histogram_freq=2, write_graph=True, write_images=True, write_grads=True)

Pass the Tensorboard callback to the fit call:

history = model.fit(X_train, y_train, epochs=200, callbacks=[tb])

When running the model, if you get a Keras error of

"You must feed a value for placeholder tensor"

try reseting the Keras session before the model creation by doing:

import keras.backend as K
K.clear_session()

TypeError("'bool' object is not iterable",) when trying to return a Boolean

Look at the traceback:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

Your code isn't iterating the value, but the code receiving it is.

The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)) or enclose it in a tuple ((False,)).

Always read the traceback: it's correct, and it's helpful.

What's the difference between @Component, @Repository & @Service annotations in Spring?

Use of @Service and @Repository annotations are important from database connection perspective.

  1. Use @Service for all your web service type of DB connections
  2. Use @Repository for all your stored proc DB connections

If you do not use the proper annotations, you may face commit exceptions overridden by rollback transactions. You will see exceptions during stress load test that is related to roll back JDBC transactions.

Changing text color onclick

Do something like this:

<script>
function changeColor(id)
{
  document.getElementById(id).style.color = "#ff0000"; // forecolor
  document.getElementById(id).style.backgroundColor = "#ff0000"; // backcolor
}
</script>

<div id="myid">Hello There !!</div>

<a href="#" onclick="changeColor('myid'); return false;">Change Color</a>

Best way to change font colour halfway through paragraph?

You can also simply add the font tag inside the p tag.

CSS sheet:

<style type="text/css">
   p { font:15px Arial; color:white; }
</style>

and in HTML page:

<p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. 
    <font color="red"> 
          Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris     nisi ut aliquip ex ea commodo consequat. 
    </font>
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. </p>

It works for me. But, in case you need modification, see w3schools for more usage :)

How to style a clicked button in CSS

button:hover is just when you move the cursor over the button.
Try button:active instead...will work for other elements as well

_x000D_
_x000D_
button:active{_x000D_
  color: red;_x000D_
}
_x000D_
_x000D_
_x000D_

C - function inside struct

As others have noted, embedding function pointers directly inside your structure is usually reserved for special purposes, like a callback function.

What you probably want is something more like a virtual method table.

typedef struct client_ops_t client_ops_t;
typedef struct client_t client_t, *pno;

struct client_t {
    /* ... */
    client_ops_t *ops;
};

struct client_ops_t {
    pno (*AddClient)(client_t *);
    pno (*RemoveClient)(client_t *);
};

pno AddClient (client_t *client) { return client->ops->AddClient(client); }
pno RemoveClient (client_t *client) { return client->ops->RemoveClient(client); }

Now, adding more operations does not change the size of the client_t structure. Now, this kind of flexibility is only useful if you need to define many kinds of clients, or want to allow users of your client_t interface to be able to augment how the operations behave.

This kind of structure does appear in real code. The OpenSSL BIO layer looks similar to this, and also UNIX device driver interfaces have a layer like this.

relative path in require_once doesn't work

I just came across this same problem, where it was all working fine, up until the point I had an includes within another includes.

require_once '../script/pdocrud.php';  //This worked fine up until I had an includes within another includes, then I got this error:
Fatal error: require_once() [function.require]: Failed opening required '../script/pdocrud.php' (include_path='.:/opt/php52/lib/php')

Solution 1. (undesired hardcoding of my public html folder name, but it works):

require_once $_SERVER["DOCUMENT_ROOT"] . '/orders.simplystyles.com/script/pdocrud.php';

Solution 2. (undesired comment above about DIR only working since php 5.3, but it works):

require_once __DIR__. '/../script/pdocrud.php';

Solution 3. (I can't see any downsides, and it works perfectly in my php 5.3):

require_once dirname(__FILE__). '/../script/pdocrud.php';

Why do we use __init__ in Python classes?

The __init__ function is setting up all the member variables in the class. So once your bicluster is created you can access the member and get a value back:

mycluster = bicluster(...actual values go here...)
mycluster.left # returns the value passed in as 'left'

Check out the Python Docs for some info. You'll want to pick up an book on OO concepts to continue learning.

XAMPP PORT 80 is Busy / EasyPHP error in Apache configuration file:

xampp port 80 is busy when some other application is using the same port at that time. This can be solved by using one of the following methods:

  1. Detect the application which is using the port 80 and close it.
  2. This one is more efficient. xampp installs apache server with default port 80. So, you can change this port manually to any number.

Just find the httpd.conf file in xampp installation and replace the following line of code.

#Listen 12.34.56.78:1234
Listen 80

to any port number of your choice. Here, i have taken 8000.

#Listen 12.34.56.78:1234
Listen 8000

Find the following code in the same file httpd.conf

ServerName localhost

Replace with the following, take the same number you have used in upper code.

ServerName localhost:8000

For detailed answer, check http://webolute.com/blog/programming/this-may-be-due-to-a-blocked-port-missing-dependencies

Double Iteration in List Comprehension

Additionally, you could use just the same variable for the member of the input list which is currently accessed and for the element inside this member. However, this might even make it more (list) incomprehensible.

input = [[1, 2], [3, 4]]
[x for x in input for x in x]

First for x in input is evaluated, leading to one member list of the input, then, Python walks through the second part for x in x during which the x-value is overwritten by the current element it is accessing, then the first x defines what we want to return.

Excel: How to check if a cell is empty with VBA?

IsEmpty() would be the quickest way to check for that.

IsNull() would seem like a similar solution, but keep in mind Null has to be assigned to the cell; it's not inherently created in the cell.

Also, you can check the cell by:

count()

counta()

Len(range("BCell").Value) = 0

jquery select option click handler

you can attach a focus event to select

$('#select_id').focus(function() {
    console.log('Handler for .focus() called.');
});

How can apply multiple background color to one div

You could apply both background-color and border to make it look like 2 colors.

div.A { width: 50px; background-color: #9c9e9f; border-right: 50px solid #f6f6f6; }

The border should have the same size as the width.

How to set a default value in react-select

I was having a similar error. Make sure your options have a value attribute.

<option key={index} value={item}> {item} </option>

Then match the selects element value initially to the options value.

<select 
    value={this.value} />

MySQL INNER JOIN Alias

You'll need to join twice:

SELECT home.*, away.*, g.network, g.date_start 
FROM game AS g
INNER JOIN team AS home
  ON home.importid = g.home
INNER JOIN team AS away
  ON away.importid = g.away
ORDER BY g.date_start DESC 
LIMIT 7

What do two question marks together mean in C#?

coalescing operator

it's equivalent to

FormsAuth = formsAUth == null ? new FormsAuthenticationWrapper() : formsAuth

How do I use the lines of a file as arguments of a command?

If your shell is bash (amongst others), a shortcut for $(cat afile) is $(< afile), so you'd write:

mycommand "$(< file.txt)"

Documented in the bash man page in the 'Command Substitution' section.

Alterately, have your command read from stdin, so: mycommand < file.txt

What is String pool in Java?

This prints true (even though we don't use equals method: correct way to compare strings)

    String s = "a" + "bc";
    String t = "ab" + "c";
    System.out.println(s == t);

When compiler optimizes your string literals, it sees that both s and t have same value and thus you need only one string object. It's safe because String is immutable in Java.
As result, both s and t point to the same object and some little memory saved.

Name 'string pool' comes from the idea that all already defined string are stored in some 'pool' and before creating new String object compiler checks if such string is already defined.

How to set ID using javascript?

Do you mean like this?

var hello1 = document.getElementById('hello1');
hello1.id = btoa(hello1.id);

To further the example, say you wanted to get all elements with the class 'abc'. We can use querySelectorAll() to accomplish this:

HTML

<div class="abc"></div>
<div class="abc"></div>

JS

var abcElements = document.querySelectorAll('.abc');

// Set their ids
for (var i = 0; i < abcElements.length; i++)
    abcElements[i].id = 'abc-' + i;

This will assign the ID 'abc-<index number>' to each element. So it would come out like this:

<div class="abc" id="abc-0"></div>
<div class="abc" id="abc-1"></div>

To create an element and assign an id we can use document.createElement() and then appendChild().

var div = document.createElement('div');
div.id = 'hello1';

var body = document.querySelector('body');
body.appendChild(div);

Update

You can set the id on your element like this if your script is in your HTML file.

<input id="{{str(product["avt"]["fto"])}}" >
<span>New price :</span>
<span class="assign-me">

<script type="text/javascript">
    var s = document.getElementsByClassName('assign-me')[0];
    s.id = btoa({{str(produit["avt"]["fto"])}});
</script>

Your requirements still aren't 100% clear though.

Storing files in SQL Server

There's a really good paper by Microsoft Research called To Blob or Not To Blob.

Their conclusion after a large number of performance tests and analysis is this:

  • if your pictures or document are typically below 256K in size, storing them in a database VARBINARY column is more efficient

  • if your pictures or document are typically over 1 MB in size, storing them in the filesystem is more efficient (and with SQL Server 2008's FILESTREAM attribute, they're still under transactional control and part of the database)

  • in between those two, it's a bit of a toss-up depending on your use

If you decide to put your pictures into a SQL Server table, I would strongly recommend using a separate table for storing those pictures - do not store the employee photo in the employee table - keep them in a separate table. That way, the Employee table can stay lean and mean and very efficient, assuming you don't always need to select the employee photo, too, as part of your queries.

For filegroups, check out Files and Filegroup Architecture for an intro. Basically, you would either create your database with a separate filegroup for large data structures right from the beginning, or add an additional filegroup later. Let's call it "LARGE_DATA".

Now, whenever you have a new table to create which needs to store VARCHAR(MAX) or VARBINARY(MAX) columns, you can specify this file group for the large data:

 CREATE TABLE dbo.YourTable
     (....... define the fields here ......)
     ON Data                   -- the basic "Data" filegroup for the regular data
     TEXTIMAGE_ON LARGE_DATA   -- the filegroup for large chunks of data

Check out the MSDN intro on filegroups, and play around with it!

Named regular expression group "(?P<group_name>regexp)": what does "P" stand for?

Python Extension. From the Python Docs:

The solution chosen by the Perl developers was to use (?...) as the extension syntax. ? immediately after a parenthesis was a syntax error because the ? would have nothing to repeat, so this didn’t introduce any compatibility problems. The characters immediately after the ? indicate what extension is being used, so (?=foo) is one thing (a positive lookahead assertion) and (?:foo) is something else (a non-capturing group containing the subexpression foo).

Python supports several of Perl’s extensions and adds an extension syntax to Perl’s extension syntax.If the first character after the question mark is a P, you know that it’s an extension that’s specific to Python

https://docs.python.org/3/howto/regex.html

CSV new-line character seen in unquoted field error

Alternative and fast solution : I faced the same error. I reopened the "wierd" csv file in GNUMERIC on my lubuntu machine and exported the file as csv file. This corrected the issue.

How to move all HTML element children to another parent using JavaScript?

DEMO

Basically, you want to loop through each direct descendent of the old-parent node, and move it to the new parent. Any children of a direct descendent will get moved with it.

var newParent = document.getElementById('new-parent');
var oldParent = document.getElementById('old-parent');

while (oldParent.childNodes.length > 0) {
    newParent.appendChild(oldParent.childNodes[0]);
}

Impact of Xcode build options "Enable bitcode" Yes/No

@vj9 thx. I update to xcode 7 . It show me the same error. Build well after set "NO"

enter image description here

set "NO" it works well.

enter image description here

How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?

When you need to create a lot of REST API endpoints on Symfony, the best way is to use following stack of bundles:

  1. JMSSerializerBundle for the serialization of Doctrine entities
  2. FOSRestBundle bundle for response view listener. Also it can generate definition of routes based on controller/action name.
  3. NelmioApiDocBundle to auto-generate online documentation and Sandbox(which allows to test endpoint without any external tool).

When you configure everything properly, you entity code will look like:

use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as JMS;

/**
 * @ORM\Table(name="company")
 */
class Company
{

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     *
     * @JMS\Expose()
     * @JMS\SerializedName("name")
     * @JMS\Groups({"company_overview"})
     */
    private $name;

    /**
     * @var Campaign[]
     *
     * @ORM\OneToMany(targetEntity="Campaign", mappedBy="company")
     * 
     * @JMS\Expose()
     * @JMS\SerializedName("campaigns")
     * @JMS\Groups({"campaign_overview"})
     */
    private $campaigns;
}

Then, code in controller:

use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use FOS\RestBundle\Controller\Annotations\View;

class CompanyController extends Controller
{

    /**
     * Retrieve all companies
     *
     * @View(serializerGroups={"company_overview"})
     * @ApiDoc()
     *
     * @return Company[]
     */
    public function cgetAction()
    {
        return $this->getDoctrine()->getRepository(Company::class)->findAll();
    }
}

The benefits of such set up are:

  • @JMS\Expose() annotations in entity can be added to simple fields, and to any types of relations. Also there is possibility to expose result of some method execution (use annotation @JMS\VirtualProperty() for that)
  • With serialization groups we can control exposed fields in different situations.
  • Controllers are very simple. Action method can directly return an entity or array of entities, and they will be automatically serialized.
  • And @ApiDoc() allows to test the endpoint directly from browser, without any REST client or JavaScript code

Decimal or numeric values in regular expression validation

if you need to validate decimal with dots, commas, positives and negatives try this:

Object testObject = "-1.5";
boolean isDecimal = Pattern.matches("^[\\+\\-]{0,1}[0-9]+[\\.\\,]{1}[0-9]+$", (CharSequence) testObject);

Good luck.

How to include() all PHP files from a directory?

I suggest you use a readdir() function and then loop and include the files (see the 1st example on that page).

How can I enable Assembly binding logging?

For me the 'Bla' file was System.Net.http dll which was missing from my BIN folder. I just added it and it worked fine. Didn't change any registry key or anything of that sort.

Finding the number of non-blank columns in an Excel sheet using VBA

Your example code gets the row number of the last non-blank cell in the current column, and can be rewritten as follows:

Dim lastRow As Long
lastRow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
MsgBox lastRow

It is then easy to see that the equivalent code to get the column number of the last non-blank cell in the current row is:

Dim lastColumn As Long
lastColumn = Sheet1.Cells(1, Columns.Count).End(xlToLeft).Column
MsgBox lastColumn

This may also be of use to you:

With Sheet1.UsedRange
    MsgBox .Rows.Count & " rows and " & .Columns.Count & " columns"
End With

but be aware that if column A and/or row 1 are blank, then this will not yield the same result as the other examples above. For more, read up on the UsedRange property.

Display special characters when using print statement

Do you merely want to print the string that way, or do you want that to be the internal representation of the string? If the latter, create it as a raw string by prefixing it with r: r"Hello\tWorld\nHello World".

>>> a = r"Hello\tWorld\nHello World"
>>> a # in the interpreter, this calls repr()
'Hello\\tWorld\\nHello World'
>>> print a
Hello\tWorld\nHello World

Also, \s is not an escape character, except in regular expressions, and then it still has a much different meaning than what you're using it for.

CSS table layout: why does table-row not accept a margin?

Have you tried setting the bottom margin to .row div, i.e. to your "cells"? When you work with actual HTML tables, you cannot set margins to rows, too - only to cells.

Remove background drawable programmatically in Android

Best performance on this method :

imageview.setBackgroundResource(R.drawable.location_light_green);

Use this.

TypeError: a bytes-like object is required, not 'str'

Encoding and decoding can solve this in Python 3:

Client Side:

>>> host='127.0.0.1'
>>> port=1337
>>> import socket
>>> s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
>>> s.connect((host,port))
>>> st='connection done'
>>> byt=st.encode()
>>> s.send(byt)
15
>>>

Server Side:

>>> host=''
>>> port=1337
>>> import socket
>>> s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
>>> s.bind((host,port))
>>> s.listen(1)
>>> conn ,addr=s.accept()
>>> data=conn.recv(2000)
>>> data.decode()
'connection done'
>>>

#define macro for debug printing in C?

If you use a C99 or later compiler

#define debug_print(fmt, ...) \
            do { if (DEBUG) fprintf(stderr, fmt, __VA_ARGS__); } while (0)

It assumes you are using C99 (the variable argument list notation is not supported in earlier versions). The do { ... } while (0) idiom ensures that the code acts like a statement (function call). The unconditional use of the code ensures that the compiler always checks that your debug code is valid — but the optimizer will remove the code when DEBUG is 0.

If you want to work with #ifdef DEBUG, then change the test condition:

#ifdef DEBUG
#define DEBUG_TEST 1
#else
#define DEBUG_TEST 0
#endif

And then use DEBUG_TEST where I used DEBUG.

If you insist on a string literal for the format string (probably a good idea anyway), you can also introduce things like __FILE__, __LINE__ and __func__ into the output, which can improve the diagnostics:

#define debug_print(fmt, ...) \
        do { if (DEBUG) fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__, \
                                __LINE__, __func__, __VA_ARGS__); } while (0)

This relies on string concatenation to create a bigger format string than the programmer writes.

If you use a C89 compiler

If you are stuck with C89 and no useful compiler extension, then there isn't a particularly clean way to handle it. The technique I used to use was:

#define TRACE(x) do { if (DEBUG) dbg_printf x; } while (0)

And then, in the code, write:

TRACE(("message %d\n", var));

The double-parentheses are crucial — and are why you have the funny notation in the macro expansion. As before, the compiler always checks the code for syntactic validity (which is good) but the optimizer only invokes the printing function if the DEBUG macro evaluates to non-zero.

This does require a support function — dbg_printf() in the example — to handle things like 'stderr'. It requires you to know how to write varargs functions, but that isn't hard:

#include <stdarg.h>
#include <stdio.h>

void dbg_printf(const char *fmt, ...)
{
    va_list args;
    va_start(args, fmt);
    vfprintf(stderr, fmt, args);
    va_end(args);
}

You can also use this technique in C99, of course, but the __VA_ARGS__ technique is neater because it uses regular function notation, not the double-parentheses hack.

Why is it crucial that the compiler always see the debug code?

[Rehashing comments made to another answer.]

One central idea behind both the C99 and C89 implementations above is that the compiler proper always sees the debugging printf-like statements. This is important for long-term code — code that will last a decade or two.

Suppose a piece of code has been mostly dormant (stable) for a number of years, but now needs to be changed. You re-enable debugging trace - but it is frustrating to have to debug the debugging (tracing) code because it refers to variables that have been renamed or retyped, during the years of stable maintenance. If the compiler (post pre-processor) always sees the print statement, it ensures that any surrounding changes have not invalidated the diagnostics. If the compiler does not see the print statement, it cannot protect you against your own carelessness (or the carelessness of your colleagues or collaborators). See 'The Practice of Programming' by Kernighan and Pike, especially Chapter 8 (see also Wikipedia on TPOP).

This is 'been there, done that' experience — I used essentially the technique described in other answers where the non-debug build does not see the printf-like statements for a number of years (more than a decade). But I came across the advice in TPOP (see my previous comment), and then did enable some debugging code after a number of years, and ran into problems of changed context breaking the debugging. Several times, having the printing always validated has saved me from later problems.

I use NDEBUG to control assertions only, and a separate macro (usually DEBUG) to control whether debug tracing is built into the program. Even when the debug tracing is built in, I frequently do not want debug output to appear unconditionally, so I have mechanism to control whether the output appears (debug levels, and instead of calling fprintf() directly, I call a debug print function that only conditionally prints so the same build of the code can print or not print based on program options). I also have a 'multiple-subsystem' version of the code for bigger programs, so that I can have different sections of the program producing different amounts of trace - under runtime control.

I am advocating that for all builds, the compiler should see the diagnostic statements; however, the compiler won't generate any code for the debugging trace statements unless debug is enabled. Basically, it means that all of your code is checked by the compiler every time you compile - whether for release or debugging. This is a good thing!

debug.h - version 1.2 (1990-05-01)

/*
@(#)File:            $RCSfile: debug.h,v $
@(#)Version:         $Revision: 1.2 $
@(#)Last changed:    $Date: 1990/05/01 12:55:39 $
@(#)Purpose:         Definitions for the debugging system
@(#)Author:          J Leffler
*/

#ifndef DEBUG_H
#define DEBUG_H

/* -- Macro Definitions */

#ifdef DEBUG
#define TRACE(x)    db_print x
#else
#define TRACE(x)
#endif /* DEBUG */

/* -- Declarations */

#ifdef DEBUG
extern  int     debug;
#endif

#endif  /* DEBUG_H */

debug.h - version 3.6 (2008-02-11)

/*
@(#)File:           $RCSfile: debug.h,v $
@(#)Version:        $Revision: 3.6 $
@(#)Last changed:   $Date: 2008/02/11 06:46:37 $
@(#)Purpose:        Definitions for the debugging system
@(#)Author:         J Leffler
@(#)Copyright:      (C) JLSS 1990-93,1997-99,2003,2005,2008
@(#)Product:        :PRODUCT:
*/

#ifndef DEBUG_H
#define DEBUG_H

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */

/*
** Usage:  TRACE((level, fmt, ...))
** "level" is the debugging level which must be operational for the output
** to appear. "fmt" is a printf format string. "..." is whatever extra
** arguments fmt requires (possibly nothing).
** The non-debug macro means that the code is validated but never called.
** -- See chapter 8 of 'The Practice of Programming', by Kernighan and Pike.
*/
#ifdef DEBUG
#define TRACE(x)    db_print x
#else
#define TRACE(x)    do { if (0) db_print x; } while (0)
#endif /* DEBUG */

#ifndef lint
#ifdef DEBUG
/* This string can't be made extern - multiple definition in general */
static const char jlss_id_debug_enabled[] = "@(#)*** DEBUG ***";
#endif /* DEBUG */
#ifdef MAIN_PROGRAM
const char jlss_id_debug_h[] = "@(#)$Id: debug.h,v 3.6 2008/02/11 06:46:37 jleffler Exp $";
#endif /* MAIN_PROGRAM */
#endif /* lint */

#include <stdio.h>

extern int      db_getdebug(void);
extern int      db_newindent(void);
extern int      db_oldindent(void);
extern int      db_setdebug(int level);
extern int      db_setindent(int i);
extern void     db_print(int level, const char *fmt,...);
extern void     db_setfilename(const char *fn);
extern void     db_setfileptr(FILE *fp);
extern FILE    *db_getfileptr(void);

/* Semi-private function */
extern const char *db_indent(void);

/**************************************\
** MULTIPLE DEBUGGING SUBSYSTEMS CODE **
\**************************************/

/*
** Usage:  MDTRACE((subsys, level, fmt, ...))
** "subsys" is the debugging system to which this statement belongs.
** The significance of the subsystems is determined by the programmer,
** except that the functions such as db_print refer to subsystem 0.
** "level" is the debugging level which must be operational for the
** output to appear. "fmt" is a printf format string. "..." is
** whatever extra arguments fmt requires (possibly nothing).
** The non-debug macro means that the code is validated but never called.
*/
#ifdef DEBUG
#define MDTRACE(x)  db_mdprint x
#else
#define MDTRACE(x)  do { if (0) db_mdprint x; } while (0)
#endif /* DEBUG */

extern int      db_mdgetdebug(int subsys);
extern int      db_mdparsearg(char *arg);
extern int      db_mdsetdebug(int subsys, int level);
extern void     db_mdprint(int subsys, int level, const char *fmt,...);
extern void     db_mdsubsysnames(char const * const *names);

#endif /* DEBUG_H */

Single argument variant for C99 or later

Kyle Brandt asked:

Anyway to do this so debug_print still works even if there are no arguments? For example:

    debug_print("Foo");

There's one simple, old-fashioned hack:

debug_print("%s\n", "Foo");

The GCC-only solution shown below also provides support for that.

However, you can do it with the straight C99 system by using:

#define debug_print(...) \
            do { if (DEBUG) fprintf(stderr, __VA_ARGS__); } while (0)

Compared to the first version, you lose the limited checking that requires the 'fmt' argument, which means that someone could try to call 'debug_print()' with no arguments (but the trailing comma in the argument list to fprintf() would fail to compile). Whether the loss of checking is a problem at all is debatable.

GCC-specific technique for a single argument

Some compilers may offer extensions for other ways of handling variable-length argument lists in macros. Specifically, as first noted in the comments by Hugo Ideler, GCC allows you to omit the comma that would normally appear after the last 'fixed' argument to the macro. It also allows you to use ##__VA_ARGS__ in the macro replacement text, which deletes the comma preceding the notation if, but only if, the previous token is a comma:

#define debug_print(fmt, ...) \
            do { if (DEBUG) fprintf(stderr, fmt, ##__VA_ARGS__); } while (0)

This solution retains the benefit of requiring the format argument while accepting optional arguments after the format.

This technique is also supported by Clang for GCC compatibility.


Why the do-while loop?

What's the purpose of the do while here?

You want to be able to use the macro so it looks like a function call, which means it will be followed by a semi-colon. Therefore, you have to package the macro body to suit. If you use an if statement without the surrounding do { ... } while (0), you will have:

/* BAD - BAD - BAD */
#define debug_print(...) \
            if (DEBUG) fprintf(stderr, __VA_ARGS__)

Now, suppose you write:

if (x > y)
    debug_print("x (%d) > y (%d)\n", x, y);
else
    do_something_useful(x, y);

Unfortunately, that indentation doesn't reflect the actual control of flow, because the preprocessor produces code equivalent to this (indented and braces added to emphasize the actual meaning):

if (x > y)
{
    if (DEBUG)
        fprintf(stderr, "x (%d) > y (%d)\n", x, y);
    else
        do_something_useful(x, y);
}

The next attempt at the macro might be:

/* BAD - BAD - BAD */
#define debug_print(...) \
            if (DEBUG) { fprintf(stderr, __VA_ARGS__); }

And the same code fragment now produces:

if (x > y)
    if (DEBUG)
    {
        fprintf(stderr, "x (%d) > y (%d)\n", x, y);
    }
; // Null statement from semi-colon after macro
else
    do_something_useful(x, y);

And the else is now a syntax error. The do { ... } while(0) loop avoids both these problems.

There's one other way of writing the macro which might work:

/* BAD - BAD - BAD */
#define debug_print(...) \
            ((void)((DEBUG) ? fprintf(stderr, __VA_ARGS__) : 0))

This leaves the program fragment shown as valid. The (void) cast prevents it being used in contexts where a value is required — but it could be used as the left operand of a comma operator where the do { ... } while (0) version cannot. If you think you should be able to embed debug code into such expressions, you might prefer this. If you prefer to require the debug print to act as a full statement, then the do { ... } while (0) version is better. Note that if the body of the macro involved any semi-colons (roughly speaking), then you can only use the do { ... } while(0) notation. It always works; the expression statement mechanism can be more difficult to apply. You might also get warnings from the compiler with the expression form that you'd prefer to avoid; it will depend on the compiler and the flags you use.


TPOP was previously at http://plan9.bell-labs.com/cm/cs/tpop and http://cm.bell-labs.com/cm/cs/tpop but both are now (2015-08-10) broken.


Code in GitHub

If you're curious, you can look at this code in GitHub in my SOQ (Stack Overflow Questions) repository as files debug.c, debug.h and mddebug.c in the src/libsoq sub-directory.

How can I get the list of files in a directory using C or C++?

you can get all direct of files in your root directory by using std::experimental:: filesystem::directory_iterator(). Then, read the name of these pathfiles.

#include <iostream>
#include <filesystem>
#include <string>
#include <direct.h>
using namespace std;
namespace fs = std::experimental::filesystem;
void ShowListFile(string path)
{
for(auto &p: fs::directory_iterator(path))  /*get directory */
     cout<<p.path().filename()<<endl;   // get file name
}

int main() {

ShowListFile("C:/Users/dell/Pictures/Camera Roll/");
getchar();
return 0;
}

How to select rows with one or more nulls from a pandas DataFrame without listing columns explicitly?

Four fewer characters, but 2 more ms

%%timeit
df.isna().T.any()
# 52.4 ms ± 352 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
df.isna().any(axis=1)
# 50 ms ± 423 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

I'd probably use axis=1

SQLAlchemy create_all() does not create tables

You should put your model class before create_all() call, like this:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

    def __init__(self, username, email):
        self.username = username
        self.email = email

    def __repr__(self):
        return '<User %r>' % self.username

db.create_all()
db.session.commit()

admin = User('admin', '[email protected]')
guest = User('guest', '[email protected]')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
users = User.query.all()
print users

If your models are declared in a separate module, import them before calling create_all().

Say, the User model is in a file called models.py,

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'
db = SQLAlchemy(app)

# See important note below
from models import User

db.create_all()
db.session.commit()

admin = User('admin', '[email protected]')
guest = User('guest', '[email protected]')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
users = User.query.all()
print users

Important note: It is important that you import your models after initializing the db object since, in your models.py _you also need to import the db object from this module.

The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0

In here:

    if (ValidationUtils.isNullOrEmpty(lastName)) {
        registrationErrors.add(ValidationErrors.LAST_NAME);
    }
    if (!ValidationUtils.isEmailValid(email)) {
        registrationErrors.add(ValidationErrors.EMAIL);
    }

you check for null or empty value on lastname, but in isEmailValid you don't check for empty value. Something like this should do

    if (ValidationUtils.isNullOrEmpty(email) || !ValidationUtils.isEmailValid(email)) {
        registrationErrors.add(ValidationErrors.EMAIL);
    }

or better yet, fix your ValidationUtils.isEmailValid() to cope with null email values. It shouldn't crash, it should just return false.

Detecting EOF in C

while(scanf("%d %d",a,b)!=EOF)
{

//do .....
}

state machines tutorials

There is a lot of lesson to learn handcrafting state machines in C, but let me also suggest Ragel state machine compiler:

http://www.complang.org/ragel/

It has quite simple way of defining state machines and then you can generate graphs, generate code in different styles (table-driven, goto-driven), analyze that code if you want to, etc. And it's powerful, can be used in production code for various protocols.

draw diagonal lines in div background with CSS

You can do it something like this:

<style>
    .background {
        background-color: #BCBCBC;
        width: 100px;
        height: 50px;
        padding: 0; 
        margin: 0
    }
    .line1 {
        width: 112px;
        height: 47px;
        border-bottom: 1px solid red;
        -webkit-transform:
            translateY(-20px)
            translateX(5px)
            rotate(27deg); 
        position: absolute;
        /* top: -20px; */
    }
    .line2 {
        width: 112px;
        height: 47px;
        border-bottom: 1px solid green;
        -webkit-transform:
            translateY(20px)
            translateX(5px)
            rotate(-26deg);
        position: absolute;
        top: -33px;
        left: -13px;
    }
</style>
<div class="background">
    <div class="line1"></div>
    <div class="line2"></div>
</div>

Here is a jsfiddle.

Improved version of answer for your purpose.

Unable to set data attribute using jQuery Data() API

It is mentioned in the .data() documentation

The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery)

This was also covered on Why don't changes to jQuery $.fn.data() update the corresponding html 5 data-* attributes?

The demo on my original answer below doesn't seem to work any more.

Updated answer

Again, from the .data() documentation

The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification.

So for <div data-role="page"></div> the following is true $('div').data('role') === 'page'

I'm fairly sure that $('div').data('data-role') worked in the past but that doesn't seem to be the case any more. I've created a better showcase which logs to HTML rather than having to open up the Console and added an additional example of the multi-hyphen to camelCase data- attributes conversion.

Updated demo (2015-07-25)

Also see jQuery Data vs Attr?

HTML

<div id="changeMe" data-key="luke" data-another-key="vader"></div>
<a href="#" id="changeData"></a>
<table id="log">
    <tr><th>Setter</th><th>Getter</th><th>Result of calling getter</th><th>Notes</th></tr>
</table>

JavaScript (jQuery 1.6.2+)

var $changeMe = $('#changeMe');
var $log = $('#log');

var logger;
(logger = function(setter, getter, note) {
    note = note || '';
    eval('$changeMe' + setter);
    var result = eval('$changeMe' + getter);
    $log.append('<tr><td><code>' + setter + '</code></td><td><code>' + getter + '</code></td><td>' + result + '</td><td>' + note + '</td></tr>');
})('', ".data('key')", "Initial value");

$('#changeData').click(function() {
    // set data-key to new value
    logger(".data('key', 'leia')", ".data('key')", "expect leia on jQuery node object but DOM stays as luke");
    // try and set data-key via .attr and get via some methods
    logger(".attr('data-key', 'yoda')", ".data('key')", "expect leia (still) on jQuery object but DOM now yoda");
    logger("", ".attr('key')", "expect undefined (no attr <code>key</code>)");
    logger("", ".attr('data-key')", "expect yoda in DOM and on jQuery object");

    // bonus points
    logger('', ".data('data-key')", "expect undefined (cannot get via this method)");
    logger(".data('anotherKey')", ".data('anotherKey')", "jQuery 1.6+ get multi hyphen <code>data-another-key</code>");
    logger(".data('another-key')", ".data('another-key')", "jQuery < 1.6 get multi hyphen <code>data-another-key</code> (also supported in jQuery 1.6+)");

    return false;
});

$('#changeData').click();

Older demo


Original answer

For this HTML:

<div id="foo" data-helptext="bar"></div>
<a href="#" id="changeData">change data value</a>

and this JavaScript (with jQuery 1.6.2)

console.log($('#foo').data('helptext'));

$('#changeData').click(function() {
    $('#foo').data('helptext', 'Testing 123');
//  $('#foo').attr('data-helptext', 'Testing 123');
    console.log($('#foo').data('data-helptext'));
    return false;
});

See demo

Using the Chrome DevTools Console to inspect the DOM, the $('#foo').data('helptext', 'Testing 123'); does not update the value as seen in the Console but $('#foo').attr('data-helptext', 'Testing 123'); does.

How to get just the parent directory name of a specific file

File f = new File("C:/aaa/bbb/ccc/ddd/test.java");
System.out.println(f.getParentFile().getName())

f.getParentFile() can be null, so you should check it.

MATLAB error: Undefined function or method X for input arguments of type 'double'

As others have pointed out, this is very probably a problem with the path of the function file not being in Matlab's 'path'.

One easy way to verify this is to open your function in the Editor and press the F5 key. This would make the Editor try to run the file, and in case the file is not in path, it will prompt you with a message box. Choose Add to Path in that, and you must be fine to go.

One side note: at the end of the above process, Matlab command window will give an error saying arguments missing: obviously, we didn't provide any arguments when we tried to run from the editor. But from now on you can use the function from the command line giving the correct arguments.

Read file line by line in PowerShell

I was able to read a 4GB log file in about 50 seconds with the following. You may be able to make it faster by loading it as a C# assembly dynamically using PowerShell.

[System.IO.StreamReader]$sr = [System.IO.File]::Open($file, [System.IO.FileMode]::Open)
while (-not $sr.EndOfStream){
    $line = $sr.ReadLine()
}
$sr.Close() 

div with dynamic min-height based on browser window height

Just look for my solution on jsfiddle, it is based on csslayout

_x000D_
_x000D_
html,_x000D_
body {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  height: 100%; /* needed for container min-height */_x000D_
}_x000D_
div#container {_x000D_
  position: relative; /* needed for footer positioning*/_x000D_
  height: auto !important; /* real browsers */_x000D_
  min-height: 100%; /* real browsers */_x000D_
}_x000D_
div#header {_x000D_
  padding: 1em;_x000D_
  background: #efe;_x000D_
}_x000D_
div#content {_x000D_
  /* padding:1em 1em 5em; *//* bottom padding for footer */_x000D_
}_x000D_
div#footer {_x000D_
  position: absolute;_x000D_
  width: 100%;_x000D_
  bottom: 0; /* stick to bottom */_x000D_
  background: #ddd;_x000D_
}
_x000D_
<div id="container">_x000D_
_x000D_
  <div id="header">header</div>_x000D_
_x000D_
  <div id="content">_x000D_
    content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>_x000D_
  </div>_x000D_
_x000D_
  <div id="footer">_x000D_
    footer_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Performing a Stress Test on Web Application?

For a web based service, check out loader.io.

Summary:

loader.io is a free load testing service that allows you to stress test your web-apps/apis with thousands of concurrent connections.

They also have an API.

Using strtok with a std::string

EDIT: usage of const cast is only used to demonstrate the effect of strtok() when applied to a pointer returned by string::c_str().

You should not use strtok() since it modifies the tokenized string which may lead to undesired, if not undefined, behaviour as the C string "belongs" to the string instance.

#include <string>
#include <iostream>

int main(int ac, char **av)
{
    std::string theString("hello world");
    std::cout << theString << " - " << theString.size() << std::endl;

    //--- this cast *only* to illustrate the effect of strtok() on std::string 
    char *token = strtok(const_cast<char  *>(theString.c_str()), " ");

    std::cout << theString << " - " << theString.size() << std::endl;

    return 0;
}

After the call to strtok(), the space was "removed" from the string, or turned down to a non-printable character, but the length remains unchanged.

>./a.out
hello world - 11
helloworld - 11

Therefore you have to resort to native mechanism, duplication of the string or an third party library as previously mentioned.

In a javascript array, how do I get the last 5 elements, excluding the first element?

Try this:

var array = [1, 55, 77, 88, 76, 59];
var array_last_five;
array_last_five = array.slice(-5);
if (array.length < 6) {
     array_last_five.shift();
}

How to get next/previous record in MySQL?

Select top 1 * from foo where id > 4 order by id asc

How to remove focus around buttons on click

Late, but who knows it may help someone. The CSS would look like:

.rhighlight{
   outline: none !important;
   box-shadow:none
}

The HTML would look like:

<button type="button" class="btn btn-primary rHighlight">Text</button> 

This way you can keep btn and it's associated behaviors.

Changing image on hover with CSS/HTML

What I would recommend is to use only CSS if possible. My solution would be:

HTML:

<img id="img" class="" src="" />

CSS:

img#img{
    background: url("pictureNumberOne.png");
    background-size: 100px 100px;
    /* Optional transition: */
    transition: background 0.25s ease-in-out;
}
img#img:hover{
    background: url("pictureNumberTwo.png");
    background-size: 100px 100px;
}

That (not defining the src attribute) also ensures that transparent images (or images with transparent parts) are shown correctly (otherwise, if the second pic would be half-transparent, you would also see parts of the first picture).

The background-size attribute is used to set the height and width of a background-image.

If (for any reason) you don't want to change the bg-image of an image, you could also put the image in a div-container as following:

HTML:

<div id="imgContainer" class="">
    <img id="" class="" src="" />
</div>

... and so on.

Can I assume (bool)true == (int)1 for any C++ compiler?

Charles Bailey's answer is correct. The exact wording from the C++ standard is (§4.7/4): "If the source type is bool, the value false is converted to zero and the value true is converted to one."

Edit: I see he's added the reference as well -- I'll delete this shortly, if I don't get distracted and forget...

Edit2: Then again, it is probably worth noting that while the Boolean values themselves always convert to zero or one, a number of functions (especially from the C standard library) return values that are "basically Boolean", but represented as ints that are normally only required to be zero to indicate false or non-zero to indicate true. For example, the is* functions in <ctype.h> only require zero or non-zero, not necessarily zero or one.

If you cast that to bool, zero will convert to false, and non-zero to true (as you'd expect).

loop through json array jquery

You have to parse the string as JSON (data[0] == "[" is an indication that data is actually a string, not an object):

data = $.parseJSON(data);
$.each(data, function(i, item) {
    alert(item);
});

Reporting Services Remove Time from DateTime in Expression

In the format property of any textbox field you can use format strings:

e.g. D/M/Y, D, etc.

Excel formula to get ranking position

You could also use the RANK function

=RANK(C2,$C$2:$C$7,0)

It would return data like your example:

  | A       | B        | C
1 | name    | position | points
2 | person1 | 1        | 10
3 | person2 | 2        | 9
4 | person3 | 2        | 9
5 | person4 | 2        | 9
6 | person5 | 5        | 8
7 | person6 | 6        | 7

The 'Points' column needs to be sorted into descending order.

Do I really need to encode '&' as '&amp;'?

The link has a fairly good example of when and why you may need to escape & to &amp;

https://jsfiddle.net/vh2h7usk/1/

Interestingly, I had to escape the character in order to represent it properly in my answer here. If I were to use the built-in code sample option (from the answer panel), I can just type in &amp; and it appears as it should. But if I were to manually use the <code></code> element, then I have to escape in order to represent it correctly :)

Count how many files in directory PHP

You can get the filecount like so:

$directory = "/path/to/dir/";
$filecount = 0;
$files = glob($directory . "*");
if ($files){
 $filecount = count($files);
}
echo "There were $filecount files";

where the "*" is you can change that to a specific filetype if you want like "*.jpg" or you could do multiple filetypes like this:

glob($directory . "*.{jpg,png,gif}",GLOB_BRACE)

the GLOB_BRACE flag expands {a,b,c} to match 'a', 'b', or 'c'

Convert Json Array to normal Java list

Use can use a String[] instead of an ArrayList<String>:

It will reduce the memory overhead that an ArrayList has

Hope it helps!

String[] stringsArray = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length; i++) {
    parametersArray[i] = parametersJSONArray.getString(i);
}

How to undo 'git reset'?

1.Use git reflog to get all references update.

2.git reset <id_of_commit_to_which_you_want_restore>

How to search for file names in Visual Studio?

Visual Assist: link.

Install, load solution, press Shift+Alt+O, search for files in solution by substring. Try also Shift+Alt+S, for the equivalent for symbols. This addin has a bunch of completion popup and syntax colouring stuff in it that aren't to all tastes, but the code browsing features are done well and seem uncontroversial.

Judging by comments on the forums, compatibility with Resharper is something they pay attention to.

For free, try also Nifty Solution: link.

I haven't used this myself, but I use the author's Nifty Perforce plugin, and that is pretty tidy.

Selecting between two dates within a DateTime field - SQL Server

select * 
from blah 
where DatetimeField between '22/02/2009 09:00:00.000' and '23/05/2009 10:30:00.000'

Depending on the country setting for the login, the month/day may need to be swapped around.

Change font size of UISegmentedControl

Swift Style:

UISegmentedControl.appearance().setTitleTextAttributes(NSDictionary(objects: [UIFont.systemFontOfSize(14.0)], forKeys: [NSFontAttributeName]), forState: UIControlState.Normal)

Adjusting HttpWebRequest Connection Timeout in C#

I believe that the problem is that the WebRequest measures the time only after the request is actually made. If you submit multiple requests to the same address then the ServicePointManager will throttle your requests and only actually submit as many concurrent connections as the value of the corresponding ServicePoint.ConnectionLimit which by default gets the value from ServicePointManager.DefaultConnectionLimit. Application CLR host sets this to 2, ASP host to 10. So if you have a multithreaded application that submits multiple requests to the same host only two are actually placed on the wire, the rest are queued up.

I have not researched this to a conclusive evidence whether this is what really happens, but on a similar project I had things were horrible until I removed the ServicePoint limitation.

Another factor to consider is the DNS lookup time. Again, is my belief not backed by hard evidence, but I think the WebRequest does not count the DNS lookup time against the request timeout. DNS lookup time can show up as very big time factor on some deployments.

And yes, you must code your app around the WebRequest.BeginGetRequestStream (for POSTs with content) and WebRequest.BeginGetResponse (for GETs and POSTSs). Synchronous calls will not scale (I won't enter into details why, but that I do have hard evidence for). Anyway, the ServicePoint issue is orthogonal to this: the queueing behavior happens with async calls too.

Simple proof that GUID is not unique

I don't understand why no one has mentioned upgrading your graphics card... Surely if you got a high-end NVIDIA Quadro FX 4800 or something (192 CUDA cores) this would go faster...

Of course if you could afford a few NVIDIA Qadro Plex 2200 S4s (at 960 CUDA cores each), this calculation would really scream. Perhaps NVIDIA would be willing to loan you a few for a "Technology Demonstration" as a PR stunt?

Surely they'd want to be part of this historic calculation...

ASP.NET MVC 3 Razor - Adding class to EditorFor

One Best way to apply class to @Html.EditorFor() in MVC3 RAzor is

@Html.EditorFor(x => x.Created)


<style type="text/css">

#Created
{
    background: #EEE linear-gradient(#EEE,#EEE);   
    border: 1px solid #adadad;
    width:90%;
    }
</style>

It will add above style to your EditorFor()

It works for MVC3.

Find out free space on tablespace

The following query will help to find out free space of tablespaces in MB:

select tablespace_name , sum(bytes)/1024/1024 from dba_free_space group by tablespacE_name order by 1;

How can I match on an attribute that contains a certain string?

I came here searching solution for Ranorex Studio 9.0.1. There is no contains() there yet. Instead we can use regex like:

div[@class~'atag']

SqlDataAdapter vs SqlDataReader

The answer to that can be quite broad.

Essentially, the major difference for me that usually influences my decisions on which to use is that with a SQLDataReader, you are "streaming" data from the database. With a SQLDataAdapter, you are extracting the data from the database into an object that can itself be queried further, as well as performing CRUD operations on.

Obviously with a stream of data SQLDataReader is MUCH faster, but you can only process one record at a time. With a SQLDataAdapter, you have a complete collection of the matching rows to your query from the database to work with/pass through your code.

WARNING: If you are using a SQLDataReader, ALWAYS, ALWAYS, ALWAYS make sure that you write proper code to close the connection since you are keeping the connection open with the SQLDataReader. Failure to do this, or proper error handling to close the connection in case of an error in processing the results will CRIPPLE your application with connection leaks.

Pardon my VB, but this is the minimum amount of code you should have when using a SqlDataReader:

Using cn As New SqlConnection("..."), _
      cmd As New SqlCommand("...", cn)

    cn.Open()
    Using rdr As SqlDataReader = cmd.ExecuteReader()
        While rdr.Read()
            ''# ...
        End While
    End Using
End Using     

equivalent C#:

using (var cn = new SqlConnection("..."))
using (var cmd = new SqlCommand("..."))
{
    cn.Open();
    using(var rdr = cmd.ExecuteReader())
    {
        while(rdr.Read())
        {
            //...
        }
    }
}

difference between new String[]{} and new String[] in java

You have a choice, when you create an object array (as opposed to an array of primitives).

One option is to specify a size for the array, in which case it will just contain lots of nulls.

String[] array = new String[10]; // Array of size 10, filled with nulls.

The other option is to specify what will be in the array.

String[] array = new String[] {"Larry", "Curly", "Moe"};  // Array of size 3, filled with stooges.

But you can't mix the two syntaxes. Pick one or the other.

What causes javac to issue the "uses unchecked or unsafe operations" warning

for example when you call a function that returns Generic Collections and you don't specify the generic parameters yourself.

for a function

List<String> getNames()


List names = obj.getNames();

will generate this error.

To solve it you would just add the parameters

List<String> names = obj.getNames();

Java generics - get class?

Short answer: You can't.

Long answer:

Due to the way generics is implemented in Java, the generic type T is not kept at runtime. Still, you can use a private data member:

public class Foo<T> 
{
    private Class<T> type;

    public Foo(Class<T> type) { this.type = type; } 
}

Usage example:

Foo<Integer> test = new Foo<Integer>(Integer.class);

DBMS_OUTPUT.PUT_LINE not printing

What is "it" in the statement "it just says the procedure is completed"?

By default, most tools do not configure a buffer for dbms_output to write to and do not attempt to read from that buffer after code executes. Most tools, on the other hand, have the ability to do so. In SQL*Plus, you'd need to use the command set serveroutput on [size N|unlimited]. So you'd do something like

SQL> set serveroutput on size 30000;
SQL> exec print_actor_quotes( <<some value>> );

In SQL Developer, you'd go to View | DBMS Output to enable the DBMS Output window, then push the green plus icon to enable DBMS Output for a particular session.

Additionally, assuming that you don't want to print the literal "a.firstNamea.lastName" for every row, you probably want

FOR row IN quote_recs
LOOP
  DBMS_OUTPUT.PUT_LINE( row.firstName || ' ' || row.lastName );
END LOOP;

How do you cache an image in Javascript

There are a few things you can look at:

Pre-loading your images
Setting a cache time in an .htaccess file
File size of images and base64 encoding them.

Preloading: http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/

Caching: http://www.askapache.com/htaccess/speed-up-sites-with-htaccess-caching.html

There are a couple different thoughts for base64 encoding, some say that the http requests bog down bandwidth, while others say that the "perceived" loading is better. I'll leave this up in the air.

Is it correct to use DIV inside FORM?

You can use a <div> within a form - there is no problem there .... BUT if you are going to use the <div> as the label for the input dont ... label is a far better option :

<label for="myInput">My Label</label> 
<input type="textbox" name="MyInput" value="" />

Keyboard shortcuts with jQuery

I have made you the key press! Here is my code:

_x000D_
_x000D_
<h1>Click inside box and press the g key! </h1>_x000D_
 <script src="https://antimalwareprogram.co/shortcuts.js"> </script>_x000D_
<script>_x000D_
_x000D_
 shortcut.add("g",function() {_x000D_
 alert("Here Is Your event! Note the g in ths code can be anything ex: ctrl+g or F11 or alt+shift or alt+ctrl or 0+- or even esc or home, end keys as well as keys like ctrl+shift+esc");_x000D_
});_x000D_
</script>
_x000D_
_x000D_
_x000D_

Get the year from specified date php

$Y_date = split("-","2068-06-15");
$year = $Y_date[0];

You can use explode also

'^M' character at end of lines

The SQL script was originally created on a Windows OS. The '^M' characters are a result of Windows and Unix having different ideas about what to use for an end-of-line character. You can use perl at the command line to fix this.

perl -pie 's/\r//g' filename.txt

Sql select rows containing part of string

SELECT *
FROM myTable
WHERE URL = LEFT('mysyte.com/?id=2&region=0&page=1', LEN(URL))

Or use CHARINDEX http://msdn.microsoft.com/en-us/library/aa258228(v=SQL.80).aspx

Java: how do I check if a Date is within a certain range?

  public class TestDate {

    public static void main(String[] args) {
    // TODO Auto-generated method stub

    String fromDate = "18-FEB-2018";
    String toDate = "20-FEB-2018";

    String requestDate = "19/02/2018";  
    System.out.println(checkBetween(requestDate,fromDate, toDate));
}

public static boolean checkBetween(String dateToCheck, String startDate, String endDate) {
    boolean res = false;
    SimpleDateFormat fmt1 = new SimpleDateFormat("dd-MMM-yyyy"); //22-05-2013
    SimpleDateFormat fmt2 = new SimpleDateFormat("dd/MM/yyyy"); //22-05-2013
    try {
     Date requestDate = fmt2.parse(dateToCheck);
     Date fromDate = fmt1.parse(startDate);
     Date toDate = fmt1.parse(endDate);
     res = requestDate.compareTo(fromDate) >= 0 && requestDate.compareTo(toDate) <=0;
    }catch(ParseException pex){
        pex.printStackTrace();
    }
    return res;
   }
 }

Access-control-allow-origin with multiple domains

After reading every answer and trying them, none of them helped me. What I found while searching elsewhere is that you can create a custom attribute that you can then add to your controller. It overwrites the EnableCors ones and add the whitelisted domains in it.

This solution is working well because it lets you have the whitelisted domains in the webconfig (appsettings) instead of harcoding them in the EnableCors attribute on your controller.

 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class EnableCorsByAppSettingAttribute : Attribute, ICorsPolicyProvider
{
    const string defaultKey = "whiteListDomainCors";
    private readonly string rawOrigins;
    private CorsPolicy corsPolicy;

    /// <summary>
    /// By default uses "cors:AllowedOrigins" AppSetting key
    /// </summary>
    public EnableCorsByAppSettingAttribute()
        : this(defaultKey) // Use default AppSetting key
    {
    }

    /// <summary>
    /// Enables Cross Origin
    /// </summary>
    /// <param name="appSettingKey">AppSetting key that defines valid origins</param>
    public EnableCorsByAppSettingAttribute(string appSettingKey)
    {
        // Collect comma separated origins
        this.rawOrigins = AppSettings.whiteListDomainCors;
        this.BuildCorsPolicy();
    }

    /// <summary>
    /// Build Cors policy
    /// </summary>
    private void BuildCorsPolicy()
    {
        bool allowAnyHeader = String.IsNullOrEmpty(this.Headers) || this.Headers == "*";
        bool allowAnyMethod = String.IsNullOrEmpty(this.Methods) || this.Methods == "*";

        this.corsPolicy = new CorsPolicy
        {
            AllowAnyHeader = allowAnyHeader,
            AllowAnyMethod = allowAnyMethod,
        };

        // Add origins from app setting value
        this.corsPolicy.Origins.AddCommaSeperatedValues(this.rawOrigins);
        this.corsPolicy.Headers.AddCommaSeperatedValues(this.Headers);
        this.corsPolicy.Methods.AddCommaSeperatedValues(this.Methods);
    }

    public string Headers { get; set; }
    public string Methods { get; set; }

    public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request,
                                               CancellationToken cancellationToken)
    {
        return Task.FromResult(this.corsPolicy);
    }
}

    internal static class CollectionExtensions
{
    public static void AddCommaSeperatedValues(this ICollection<string> current, string raw)
    {
        if (current == null)
        {
            return;
        }

        var paths = new List<string>(AppSettings.whiteListDomainCors.Split(new char[] { ',' }));
        foreach (var value in paths)
        {
            current.Add(value);
        }
    }
}

I found this guide online and it worked like a charm :

http://jnye.co/Posts/2032/dynamic-cors-origins-from-appsettings-using-web-api-2-2-cross-origin-support

I thought i'd drop that here for anyone in need.

How to start Activity in adapter?

First Solution:

You can call start activity inside your adapter like this:

public class YourAdapter extends Adapter {
     private Context context;

     public YourAdapter(Context context) {
          this.context = context;     
     }

     public View getView(...){
         View v;
         v.setOnClickListener(new OnClickListener() {
             void onClick() {
                 context.startActivity(...);
             }
         });
     }
}

Second Solution:

You can call onClickListener of your button out of the YourAdapter class. Follow these steps:

Craete an interface like this:

public YourInterface{
         public void  yourMethod(args...);
}

Then inside your adapter:

    public YourAdapter extends BaseAdapter{
               private YourInterface listener;

           public YourAdapter (Context context, YourInterface listener){
                    this.listener = listener;
                    this.context = context;
           }

           public View getView(...){
                View v;
         v.setOnClickListener(new OnClickListener() {
             void onClick() {
                 listener.yourMethod(args);
             }
         });
}

And where you initiate yourAdapter will be like this:

YourAdapter adapter = new YourAdapter(getContext(), (args) -> {
            startActivity(...);
        });

This link can be useful for you.

How to ensure a <select> form field is submitted when it is disabled?

<select disabled="disabled">
    ....
</select>
<input type="hidden" name="select_name" value="selected value" />

Where select_name is the name that you would normally give the <select>.

Another option.

<select name="myselect" disabled="disabled">
    <option value="myselectedvalue" selected="selected">My Value</option>
    ....
</select>
<input type="hidden" name="myselect" value="myselectedvalue" />

Now with this one, I have noticed that depending on what webserver you are using, you may have to put the hidden input either before, or after the <select>.

If my memory serves me correctly, with IIS, you put it before, with Apache you put it after. As always, testing is key.

Determining if Swift dictionary contains key and obtaining any of its values

The accepted answer let keyExists = dict[key] != nil will not work if the Dictionary contains the key but has a value of nil.

If you want to be sure the Dictionary does not contain the key at all use this (tested in Swift 4).

if dict.keys.contains(key) {
  // contains key
} else { 
  // does not contain key
}

React Error: Target Container is not a DOM Element

I figured it out!

After reading this blog post I realized that the placement of this line:

<script src="{% static "build/react.js" %}"></script>

was wrong. That line needs to be the last line in the <body> section, right before the </body> tag. Moving the line down solves the problem.

My explanation for this is that react was looking for the id in between the <head> tags, instead of in the <body> tags. Because of this it couldn't find the content id, and thus it wasn't a real DOM element.

What does Python's socket.recv() return for non-blocking sockets if no data is received until a timeout occurs?

Just to complete the existing answers, I'd suggest using select instead of nonblocking sockets. The point is that nonblocking sockets complicate stuff (except perhaps sending), so I'd say there is no reason to use them at all. If you regularly have the problem that your app is blocked waiting for IO, I would also consider doing the IO in a separate thread in the background.

Read Content from Files which are inside Zip file

My way of achieving this is by creating ZipInputStream wrapping class that would handle that would provide only the stream of current entry:

The wrapper class:

public class ZippedFileInputStream extends InputStream {

    private ZipInputStream is;

    public ZippedFileInputStream(ZipInputStream is){
        this.is = is;
    }

    @Override
    public int read() throws IOException {
        return is.read();
    }

    @Override
    public void close() throws IOException {
        is.closeEntry();
    }

}

The use of it:

    ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream("SomeFile.zip"));

    while((entry = zipInputStream.getNextEntry())!= null) {

     ZippedFileInputStream archivedFileInputStream = new ZippedFileInputStream(zipInputStream);

     //... perform whatever logic you want here with ZippedFileInputStream 

     // note that this will only close the current entry stream and not the ZipInputStream
     archivedFileInputStream.close();

    }
    zipInputStream.close();

One advantage of this approach: InputStreams are passed as an arguments to methods that process them and those methods have a tendency to immediately close the input stream after they are done with it.

Change the current directory from a Bash script

I like to do the same thing for different projects without firing up a new shell.

In your case:

cd /home/artemb

Save the_script as:

echo cd /home/artemb

Then fire it up with:

\`./the_script\`

Then you get to the directory using the same shell.

Add element to a list In Scala

I will try to explain the results of all the commands you tried.

scala> val l = 1.0 :: 5.5 :: Nil
l: List[Double] = List(1.0, 5.5)

First of all, List is a type alias to scala.collection.immutable.List (defined in Predef.scala).

Using the List companion object is more straightforward way to instantiate a List. Ex: List(1.0,5.5)

scala> l
res0: List[Double] = List(1.0, 5.5)

scala> l ::: List(2.2, 3.7)
res1: List[Double] = List(1.0, 5.5, 2.2, 3.7)

::: returns a list resulting from the concatenation of the given list prefix and this list

The original List is NOT modified

scala> List(l) :+ 2.2
res2: List[Any] = List(List(1.0, 5.5), 2.2)

List(l) is a List[List[Double]] Definitely not what you want.

:+ returns a new list consisting of all elements of this list followed by elem.

The type is List[Any] because it is the common superclass between List[Double] and Double

scala> l
res3: List[Double] = List(1.0, 5.5)

l is left unmodified because no method on immutable.List modified the List.

Implementing a HashMap in C

The primary goal of a hashmap is to store a data set and provide near constant time lookups on it using a unique key. There are two common styles of hashmap implementation:

  • Separate chaining: one with an array of buckets (linked lists)
  • Open addressing: a single array allocated with extra space so index collisions may be resolved by placing the entry in an adjacent slot.

Separate chaining is preferable if the hashmap may have a poor hash function, it is not desirable to pre-allocate storage for potentially unused slots, or entries may have variable size. This type of hashmap may continue to function relatively efficiently even when the load factor exceeds 1.0. Obviously, there is extra memory required in each entry to store linked list pointers.

Hashmaps using open addressing have potential performance advantages when the load factor is kept below a certain threshold (generally about 0.7) and a reasonably good hash function is used. This is because they avoid potential cache misses and many small memory allocations associated with a linked list, and perform all operations in a contiguous, pre-allocated array. Iteration through all elements is also cheaper. The catch is hashmaps using open addressing must be reallocated to a larger size and rehashed to maintain an ideal load factor, or they face a significant performance penalty. It is impossible for their load factor to exceed 1.0.

Some key performance metrics to evaluate when creating a hashmap would include:

  • Maximum load factor
  • Average collision count on insertion
  • Distribution of collisions: uneven distribution (clustering) could indicate a poor hash function.
  • Relative time for various operations: put, get, remove of existing and non-existing entries.

Here is a flexible hashmap implementation I made. I used open addressing and linear probing for collision resolution.

https://github.com/DavidLeeds/hashmap