Programs & Examples On #Mmo

A massively multiplayer online game (also called MMO and MMOG) is a multiplayer video game which is capable of supporting hundreds or thousands of players simultaneously. By necessity, they are played on the Internet, and usually feature at least one persistent world.

How much should a function trust another function

The addEdge is trusting more than the correction of the addNode method. It's also trusting that the addNode method has been invoked by other method. I'd recommend to include check if m is not null.

How to make a variable accessible outside a function?

$.getJSON is an asynchronous request, meaning the code will continue to run even though the request is not yet done. You should trigger the second request when the first one is done, one of the choices you seen already in ComFreek's answer.

Alternatively you could use jQuery's $.when/.then(), similar to this:

var input = "netuetamundis";  var sID;  $(document).ready(function () {     $.when($.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/" + input + "?api_key=API_KEY_HERE", function () {         obj = name;         sID = obj.id;         console.log(sID);     })).then(function () {         $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function (stats) {             console.log(stats);         });     }); }); 

This would be more open for future modification and separates out the responsibility for the first call to know about the second call.

The first call can simply complete and do it's own thing not having to be aware of any other logic you may want to add, leaving the coupling of the logic separated.

vagrant primary box defined but commands still run against all boxes

The primary flag seems to only work for vagrant ssh for me.

In the past I have used the following method to hack around the issue.

# stage box intended for configuration closely matching production if ARGV[1] == 'stage'     config.vm.define "stage" do |stage|         box_setup stage, \         "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml"     end end 

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class

Just restarting the server with command npm start did the trick. Thanks all for the suggestions.

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

I solved the same issue by following steps:

Check the angular version: Using command: ng version My angular version is: Angular CLI: 7.3.10

After that I have support version of ngx bootstrap from the link: https://www.npmjs.com/package/ngx-bootstrap

In package.json file update the version: "bootstrap": "^4.5.3", "@ng-bootstrap/ng-bootstrap": "^4.2.2",

Now after updating package.json, use the command npm update

After this use command ng serve and my error got resolved

A failure occurred while executing com.android.build.gradle.internal.tasks

If you've tried all the solutions above and still doesn't resolve your issue.

This might not seemed related, but here's my take on it.

Try removing this from your Gradle dependency, I've spend 2 hours of my time because of this roadblock.

implementation "com.squareup.retrofit2:adapter-rxjava2:2.3.0"

How to prevent Google Colab from disconnecting?

Just run the code below after the cell you want to run to save from data loss.

!python

Also to exit from this mode, write

exit()

Understanding esModuleInterop in tsconfig file

in your tsconfig you have to add: "esModuleInterop": true - it should help.

Can't perform a React state update on an unmounted component

Depending on how you open your webpage, you may not be causing a mounting. Such as using a <Link/> back to a page that was already mounted in the virtual DOM, so requiring data from a componentDidMount lifecycle is caught.

Pandas Merging 101

This post will go through the following topics:

  • how to correctly generalize to multiple DataFrames (and why merge has shortcomings here)
  • merging on unique keys
  • merging on non-unqiue keys

BACK TO TOP



Generalizing to multiple DataFrames

Oftentimes, the situation arises when multiple DataFrames are to be merged together. Naively, this can be done by chaining merge calls:

df1.merge(df2, ...).merge(df3, ...)

However, this quickly gets out of hand for many DataFrames. Furthermore, it may be necessary to generalise for an unknown number of DataFrames.

Here I introduce pd.concat for multi-way joins on unique keys, and DataFrame.join for multi-way joins on non-unique keys. First, the setup.

# Setup.
np.random.seed(0)
A = pd.DataFrame({'key': ['A', 'B', 'C', 'D'], 'valueA': np.random.randn(4)})    
B = pd.DataFrame({'key': ['B', 'D', 'E', 'F'], 'valueB': np.random.randn(4)})
C = pd.DataFrame({'key': ['D', 'E', 'J', 'C'], 'valueC': np.ones(4)})
dfs = [A, B, C] 

# Note, the "key" column values are unique, so the index is unique.
A2 = A.set_index('key')
B2 = B.set_index('key')
C2 = C.set_index('key')

dfs2 = [A2, B2, C2]

Multiway merge on unique keys

If your keys (here, the key could either be a column or an index) are unique, then you can use pd.concat. Note that pd.concat joins DataFrames on the index.

# merge on `key` column, you'll need to set the index before concatenating
pd.concat([
    df.set_index('key') for df in dfs], axis=1, join='inner'
).reset_index()

  key    valueA    valueB  valueC
0   D  2.240893 -0.977278     1.0

# merge on `key` index
pd.concat(dfs2, axis=1, sort=False, join='inner')

       valueA    valueB  valueC
key                            
D    2.240893 -0.977278     1.0

Omit join='inner' for a FULL OUTER JOIN. Note that you cannot specify LEFT or RIGHT OUTER joins (if you need these, use join, described below).


Multiway merge on keys with duplicates

concat is fast, but has its shortcomings. It cannot handle duplicates.

A3 = pd.DataFrame({'key': ['A', 'B', 'C', 'D', 'D'], 'valueA': np.random.randn(5)})
pd.concat([df.set_index('key') for df in [A3, B, C]], axis=1, join='inner')
ValueError: Shape of passed values is (3, 4), indices imply (3, 2)

In this situation, we can use join since it can handle non-unique keys (note that join joins DataFrames on their index; it calls merge under the hood and does a LEFT OUTER JOIN unless otherwise specified).

# join on `key` column, set as the index first
# For inner join. For left join, omit the "how" argument.
A.set_index('key').join(
    [df.set_index('key') for df in (B, C)], how='inner').reset_index()

  key    valueA    valueB  valueC
0   D  2.240893 -0.977278     1.0

# join on `key` index
A3.set_index('key').join([B2, C2], how='inner')

       valueA    valueB  valueC
key                            
D    1.454274 -0.977278     1.0
D    0.761038 -0.977278     1.0


Continue Reading

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

* you are here

Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

I encountered the exact problem running on docker container (in build environment). After ssh into the container, I tried running the test manually and still encountered

(unknown error: DevToolsActivePort file doesn't exist)
     (The process started from chrome location /usr/bin/google-chrome-stable is 
      no longer running, so ChromeDriver is assuming that Chrome has crashed.)

When I tried running chrome locally /usr/bin/google-chrome-stable, error message

Running as root without --no-sandbox is not supported

I checked my ChromeOptions and it was missing --no-sandbox, which is why it couldn't spawn chrome.

capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(
  chromeOptions: { args: %w(headless --no-sandbox disable-gpu window-size=1920,1080) }
)

How to set width of mat-table column in angular?

You can easily do this one. In each column you will get a class with the field name prefixed with mat-column, so the class will be like mat-column-yourFieldName. So for that you can set the style like following

.mat-column-yourFieldName {
    flex: none;
    width: 100px;
}

So we can give fixed width for column as per our requirement.

Hope this helps for someone.

ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

In case you need the [] syntax, useful for "edit forms" when you need to pass parameters like id with the route, you would do something like:

[routerLink]="['edit', business._id]"

As for an "about page" with no parameters like yours,

[routerLink]="/about"

or

[routerLink]=['about']

will do the trick.

Could not install packages due to an EnvironmentError: [WinError 5] Access is denied:

Upgrading pip in windows with -

python -m pip install --upgrade pip

and then running pip install with --user option -

pip install --user package_name

solved my problem.

Angular: How to download a file from HttpClient?

After spending much time searching for a response to this answer: how to download a simple image from my API restful server written in Node.js into an Angular component app, I finally found a beautiful answer in this web Angular HttpClient Blob. Essentially it consist on:

API Node.js restful:

   /* After routing the path you want ..*/
  public getImage( req: Request, res: Response) {

    // Check if file exist...
    if (!req.params.file) {
      return res.status(httpStatus.badRequest).json({
        ok: false,
        msg: 'File param not found.'
      })
    }
    const absfile = path.join(STORE_ROOT_DIR,IMAGES_DIR, req.params.file);

    if (!fs.existsSync(absfile)) {
      return res.status(httpStatus.badRequest).json({
        ok: false,
        msg: 'File name not found on server.'
      })
    }
    res.sendFile(path.resolve(absfile));
  }

Angular 6 tested component service (EmployeeService on my case):

  downloadPhoto( name: string) : Observable<Blob> {
    const url = environment.api_url + '/storer/employee/image/' + name;

    return this.http.get(url, { responseType: 'blob' })
      .pipe(
        takeWhile( () => this.alive),
        filter ( image => !!image));
  }

Template

 <img [src]="" class="custom-photo" #photo>

Component subscriber and use:

@ViewChild('photo') image: ElementRef;

public LoadPhoto( name: string) {
    this._employeeService.downloadPhoto(name)
          .subscribe( image => {
            const url= window.URL.createObjectURL(image);
            this.image.nativeElement.src= url;
          }, error => {
            console.log('error downloading: ', error);
          })    
}

Angular 6: How to set response type as text while making http call

You should not use those headers, the headers determine what kind of type you are sending, and you are clearly sending an object, which means, JSON.

Instead you should set the option responseType to text:

addToCart(productId: number, quantity: number): Observable<any> {
  const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');

  return this.http.post(
    'http://localhost:8080/order/addtocart', 
    { dealerId: 13, createdBy: "-1", productId, quantity }, 
    { headers, responseType: 'text'}
  ).pipe(catchError(this.errorHandlerService.handleError));
}

Can not find module “@angular-devkit/build-angular”

I looked inside node_modules and apparently, only dependencies are installed, not devDependencies. With the new NPM, we need to explicitly get the devDependencies:

npm i --only=dev

If you wish to install just the devkit:

npm install @angular-devkit/build-angular

Joint idea with - ken107(github)

Could not find module "@angular-devkit/build-angular"

I resolved this by installing Angular on a 64 bit operating system. I was getting the error because I was initially running it on a 32 bit OS

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

provide all custom services means written by you in component decorator section Example : providers: [serviceName]

note:if you are using service for exchanging data between components. declare providers: [serviceName] in module level

What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that?

In my case, I had to create a new app, reinstall my node packages, and copy my src document over. That worked.

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

UPDATE

The answer is now obsolete. See this answer.


maven-compiler-plugin depends on the old version of ASM which does not support Java 10 (and Java 11) yet. However, it is possible to explicitly specify the right version of ASM:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.7.0</version>
    <configuration>
        <release>10</release>
    </configuration>
    <dependencies>
        <dependency>
            <groupId>org.ow2.asm</groupId>
            <artifactId>asm</artifactId>
            <version>6.2</version> <!-- Use newer version of ASM -->
        </dependency>
    </dependencies>
</plugin>

You can find the latest at https://search.maven.org/search?q=g:org.ow2.asm%20AND%20a:asm&core=gav

did you register the component correctly? For recursive components, make sure to provide the "name" option

I had this error and discovered the issue was because the name of the component was identical to the name of a prop.

import Control from '@/Control.vue';
export default {
    name: 'Question',
    components: {
        Control
    },
    props: ['Control', 'source'],

I was using file components. I changed the Control.vue to InputControl.vue and this warning disappeared.

Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

I had this problem too; and i resolved that in this way:

configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
    def requested = details.requested
    if (requested.group == 'com.android.support') {
        if (!requested.name.startsWith("multidex")) {
            details.useVersion '26.0.1'
        }
    }
  }
}

be careful my min SDk was 26 , you have to change it with yours!

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

Configure Two DataSources in Spring Boot 2.0.* or above

If you need to configure multiple data sources, you have to mark one of the DataSource instances as @Primary, because various auto-configurations down the road expect to be able to get one by type.

If you create your own DataSource, the auto-configuration backs off. In the following example, we provide the exact same feature set as the auto-configuration provides on the primary data source:

@Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSourceProperties firstDataSourceProperties() {
    return new DataSourceProperties();
}

@Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSource firstDataSource() {
    return firstDataSourceProperties().initializeDataSourceBuilder().build();
}

@Bean
@ConfigurationProperties("app.datasource.second")
public BasicDataSource secondDataSource() {
    return DataSourceBuilder.create().type(BasicDataSource.class).build();
}

firstDataSourceProperties has to be flagged as @Primary so that the database initializer feature uses your copy (if you use the initializer).

And your application.propoerties will look something like this:

app.datasource.first.url=jdbc:oracle:thin:@localhost/first
app.datasource.first.username=dbuser
app.datasource.first.password=dbpass
app.datasource.first.driver-class-name=oracle.jdbc.OracleDriver

app.datasource.second.url=jdbc:mariadb://localhost:3306/springboot_mariadb
app.datasource.second.username=dbuser
app.datasource.second.password=dbpass
app.datasource.second.driver-class-name=org.mariadb.jdbc.Driver

The above method is the correct to way to init multiple database in spring boot 2.0 migration and above. More read can be found here.

js 'types' can only be used in a .ts file - Visual Studio Code using @ts-check

Use "javascript.validate.enable": false in your VS Code settings, It doesn't disable ESLINT. I use both ESLINT & Flow. Simply follow the instructions Flow For Vs Code Setup

Adding this line in settings.json. Helps "javascript.validate.enable": false

How do I deal with installing peer dependencies in Angular CLI?

NPM package libraries have a section in the package.json file named peerDependencies. For example; a library built in Angular 8, will usually list Angular 8 as a dependency. This is a true dependency for anyone running less than version 8. But for anyone running version 8, 9 or 10, it's questionable whether any concern should be pursued.

I have been safely ignoring these messages on Angular Updates, but then again we do have Unit and Cypress Tests!

'mat-form-field' is not a known element - Angular 5 & Material2

You're only exporting it in your NgModule, you need to import it too

@NgModule({
  imports: [
    MatButtonModule,
    MatFormFieldModule,
    MatInputModule,
    MatRippleModule,
 ]
  exports: [
    MatButtonModule,
    MatFormFieldModule,
    MatInputModule,
    MatRippleModule,
  ],
  declarations: [
    SearchComponent,
  ],
})export class MaterialModule {};

better yet

const modules = [
        MatButtonModule,
        MatFormFieldModule,
        MatInputModule,
        MatRippleModule
];

@NgModule({
  imports: [...modules],
  exports: [...modules]
  ,
})export class MaterialModule {};

update

You're declaring component (SearchComponent) depending on Angular Material before all Angular dependency are imported

Like BrowserAnimationsModule

Try moving it to MaterialModule, or before it

ng serve not detecting file changes automatically

I had the same problem, using sudo ng serve seemed to "solve" the problem unsatisfactorily. Using sudo is not satisfactory IMO.

I checked my INotify count versus my default limit (8192) using: lsof | grep inotify | wc -l The value returned by the above command was way less than the limit. So the INotify solution didn't seem to apply to my problem.

I also checked permissions and ownership, both seemed ok, comparable to another project that worked.

Out of frustration I restarted VS Code. Basically I closed all instances, I had two running and re-opened both following which the problem went away.

I am leaning towards a possible bug somewhere. This is something to consider before turning your system inside out. Fortunately/Unfortunately this problem hasn't occurred again, I'll dig deeper if it does.

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

The only thing that worked for me was changing

android:screenOrientation="portrait"

to

android:screenOrientation="unspecified"

in the manifest for all translucent activities.

That way it is compatible with all API versions since the translucent activity seems to inherit its orientation from the parent activity as of targetApi: 28.

The style can be left as it is including <item name="android:windowIsTranslucent">true</item>.

Exception : AAPT2 error: check logs for details

This resolved the issue for me... Build|Clean project Refactor|Remove unused resources I am still a beginner at this so I cannot explain why this might have worked. It was an arbitrary choice on my part; it was simple, did not require detailed changes and I just thought it might help :)

How to add CORS request in header in Angular 5

Make the header looks like this for HttpClient in NG5:

let httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'apikey': this.apikey,
        'appkey': this.appkey,
      }),
      params: new HttpParams().set('program_id', this.program_id)
    };

You will be able to make api call with your localhost url, it works for me ..

  • Please never forget your params columnd in the header: such as params: new HttpParams().set('program_id', this.program_id)

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

Do not use authorization instead of authentication. I should get whole access to service all clients with header. The working code is :

public class TokenAuthenticationHandler : AuthenticationHandler<TokenAuthenticationOptions> 
{
    public IServiceProvider ServiceProvider { get; set; }

    public TokenAuthenticationHandler (IOptionsMonitor<TokenAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IServiceProvider serviceProvider) 
        : base (options, logger, encoder, clock) 
    {
        ServiceProvider = serviceProvider;
    }

    protected override Task<AuthenticateResult> HandleAuthenticateAsync () 
    {
        var headers = Request.Headers;
        var token = "X-Auth-Token".GetHeaderOrCookieValue (Request);

        if (string.IsNullOrEmpty (token)) {
            return Task.FromResult (AuthenticateResult.Fail ("Token is null"));
        }           

        bool isValidToken = false; // check token here

        if (!isValidToken) {
            return Task.FromResult (AuthenticateResult.Fail ($"Balancer not authorize token : for token={token}"));
        }

        var claims = new [] { new Claim ("token", token) };
        var identity = new ClaimsIdentity (claims, nameof (TokenAuthenticationHandler));
        var ticket = new AuthenticationTicket (new ClaimsPrincipal (identity), this.Scheme.Name);
        return Task.FromResult (AuthenticateResult.Success (ticket));
    }
}

Startup.cs :

#region Authentication
services.AddAuthentication (o => {
    o.DefaultScheme = SchemesNamesConst.TokenAuthenticationDefaultScheme;
})
.AddScheme<TokenAuthenticationOptions, TokenAuthenticationHandler> (SchemesNamesConst.TokenAuthenticationDefaultScheme, o => { });
#endregion

And mycontroller.cs

[Authorize(AuthenticationSchemes = SchemesNamesConst.TokenAuthenticationDefaultScheme)]
public class MainController : BaseController
{ ... }

I can't find TokenAuthenticationOptions now, but it was empty. I found the same class PhoneNumberAuthenticationOptions :

public class PhoneNumberAuthenticationOptions : AuthenticationSchemeOptions
{
    public Regex PhoneMask { get; set; }// = new Regex("7\\d{10}");
}

You should define static class SchemesNamesConst. Something like:

public static class SchemesNamesConst
{
    public const string TokenAuthenticationDefaultScheme = "TokenAuthenticationScheme";
}

No provider for HttpClient

I found slimier problem. Please import the HttpClientModule in your app.module.ts file as follow:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent
],

imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Angular 5 Service to read local .json file

Assumes, you have a data.json file in the src/app folder of your project with the following values:

[
    {
        "id": 1,
        "name": "Licensed Frozen Hat",
        "description": "Incidunt et magni est ut.",
        "price": "170.00",
        "imageUrl": "https://source.unsplash.com/1600x900/?product",
        "quantity": 56840
    },
    ...
]

3 Methods for Reading Local JSON Files

Method 1: Reading Local JSON Files Using TypeScript 2.9+ import Statement

import { Component, OnInit } from '@angular/core';
import * as data from './data.json';

@Component({
  selector: 'app-root',
  template: `<ul>
      <li *ngFor="let product of products">

      </li>
  </ul>`,
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'Angular Example';

  products: any = (data as any).default;

  constructor(){}
  ngOnInit(){
    console.log(data);
  }
}

Method 2: Reading Local JSON Files Using Angular HttpClient

import { Component, OnInit } from '@angular/core';
import { HttpClient } from "@angular/common/http";


@Component({
  selector: 'app-root',
  template: `<ul>
      <li *ngFor="let product of products">

      </li>
  </ul>`,
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'Angular Example';
  products: any = [];

  constructor(private httpClient: HttpClient){}
  ngOnInit(){
    this.httpClient.get("assets/data.json").subscribe(data =>{
      console.log(data);
      this.products = data;
    })
  }
}

Method 3: Reading Local JSON Files in Offline Angular Apps Using ES6+ import Statement

If your Angular application goes offline, reading the JSON file with HttpClient will fail. In this case, we have one more method to import local JSON files using the ES6+ import statement which supports importing JSON files.

But first we need to add a typing file as follows:

declare module "*.json" {
  const value: any;
  export default value;
}

Add this inside a new file json-typings.d.ts file in the src/app folder.

Now, you can import JSON files just like TypeScript 2.9+.

import * as data from "data.json";

How to reload current page in ReactJS?

Since React eventually boils down to plain old JavaScript, you can really place it anywhere! For instance, you could place it on a componentDidMount() in a React class.

For you edit, you may want to try something like this:

class Component extends React.Component {
  constructor(props) {
    super(props);
    this.onAddBucket = this.onAddBucket.bind(this);
  }
  componentWillMount() {
    this.setState({
      buckets: {},
    })
  }
  componentDidMount() {
    this.onAddBucket();
  }
  onAddBucket() {
    let self = this;
    let getToken = localStorage.getItem('myToken');
    var apiBaseUrl = "...";
    let input = {
      "name" :  this.state.fields["bucket_name"]
    }
    axios.defaults.headers.common['Authorization'] = getToken;
    axios.post(apiBaseUrl+'...',input)
    .then(function (response) {
      if (response.data.status == 200) {
        this.setState({
          buckets: this.state.buckets.concat(response.data.buckets),
        });
      } else {
        alert(response.data.message);
      }
    })
    .catch(function (error) {
      console.log(error);
    });
  }
  render() {
    return (
      {this.state.bucket}
    );
  }
}

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

I am using Android Studio 3.0 and was facing the same problem. I add this to my gradle:

multiDexEnabled true

And it worked!

Example

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.1'
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

And clean the project.

Import data into Google Colaboratory

It has been solved, find details here and please use the function below: https://stackoverflow.com/questions/47212852/how-to-import-and-read-a-shelve-or-numpy-file-in-google-colaboratory/49467113#49467113

from google.colab import files
import zipfile, io, os

    def read_dir_file(case_f):
        # author: yasser mustafa, 21 March 2018  
        # case_f = 0 for uploading one File and case_f = 1 for uploading one Zipped Directory
        uploaded = files.upload()    # to upload a Full Directory, please Zip it first (use WinZip)
        for fn in uploaded.keys():
            name = fn  #.encode('utf-8')
            #print('\nfile after encode', name)
            #name = io.BytesIO(uploaded[name])
        if case_f == 0:    # case of uploading 'One File only'
            print('\n file name: ', name)
            return name
        else:   # case of uploading a directory and its subdirectories and files
            zfile = zipfile.ZipFile(name, 'r')   # unzip the directory 
            zfile.extractall()
            for d in zfile.namelist():   # d = directory
                print('\n main directory name: ', d)
                return d
    print('Done!')

Angular: Cannot Get /

This error can apparently happen for a number of reasons. Here is my experience for those who land here after searching for "Cannot GET /"

I experienced this error when I installed ng-bootstrap v6 into an Angular 8 project. I downgraded ng-bootstrap to v5 and it seems to be okay now, since ng-bootstrap v6 is only compatible with Angular 9.

This happened while working in Visual Studio 2019 with the Angular .NET Core template. At the same time, the output panel of Visual Studio displayed this esoteric sounding error: "TS1086: An accessor cannot be declared in ambient context," which led me here, which, after a little reading, made me think it was a versioning issue. It appears that it was.

I fixed it by changing "@ng-bootstrap/ng-bootstrap": "^6.0.0"," to "@ng-bootstrap/ng-bootstrap": "^5.0.0" in the package.json file and rebuilding.

Angular - res.json() is not a function

Had a similar problem where we wanted to update from deprecated Http module to HttpClient in Angular 7. But the application is large and need to change res.json() in a lot of places. So I did this to have the new module with back support.

return this.http.get(this.BASE_URL + url)
      .toPromise()
      .then(data=>{
        let res = {'results': JSON.stringify(data),
        'json': ()=>{return data;}
      };
       return res; 
      })
      .catch(error => {
        return Promise.reject(error);
      });

Adding a dummy "json" named function from the central place so that all other services can still execute successfully before updating them to accommodate a new way of response handling i.e. without "json" function.

Please add a @Pipe/@Directive/@Component annotation. Error

Another solution is below way and It was my fault that when happened I put HomeService in declaration section in app.module.ts whereas I should put HomeService in Providers section that as you see below HomeService in declaration:[] is not in a correct place and HomeService is in Providers :[] section in a correct place that should be.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule  } from '@angular/core';
import { HttpModule } from '@angular/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './components/home/home.component'; 
import { HomeService } from './components/home/home.service';


@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,  
    HomeService // You will get error here
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    AppRoutingModule
  ],
  providers: [
    HomeService // Right place to set HomeService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

hope this help you.

Unable to merge dex

I had the same problem when I update from com.google.android.gms:play-services:11.2.2 to com.google.android.gms:play-services:11.4.0. This solved it for me:

  1. clean
  2. rebuild

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

You need to only depend on one major version of angular, so update all modules depending on angular 2.x :

  • update @angular/flex-layout to ^2.0.0-beta.9
  • update @angular/material to ^2.0.0-beta.12
  • update angularfire2 to ^4.0.0-rc.2
  • update zone.js to ^0.8.18
  • update webpack to ^3.8.1
  • add @angular/[email protected] (required for @angular/material)
  • replace angular2-google-maps by @agm/[email protected] (new name)

How to Update a Component without refreshing full page - Angular

To update component

 @Injectable()
    export class LoginService{
    private isUserLoggedIn: boolean = false;

    public setLoggedInUser(flag) { // you need set header flag true false from other components on basis of your requirements, header component will be visible as per this flag then
    this.isUserLoggedIn= flag;
    }


public getUserLoggedIn(): boolean {
return this.isUserLoggedIn;
}

Login Component ts
            Login Component{
             constructor(public service: LoginService){}

public login(){
service.setLoggedInUser(true);
}
            }
Inside Header component

 Header Component ts
        HeaderComponent {
         constructor(public service: LoginService){}

         public getUserLoggedIn(): boolean { return this.service.getUserLoggedIn()}
        }

template of header component: Check for user sign in here

<button *ngIf="getUserLoggedIn()">Sign Out</button>
<button *ngIf="!getUserLoggedIn()">Sign In</button>

You can use many approach like show hide using ngIf

App Component ts
AppComponent {
 public showHeader: boolean = true;
}
App Component html
<div *ngIf='showHeader'> // you show hide on basis of this ngIf and header component always get visible with it's lifecycle hook ngOnInit() called all the time when it get visible
<app-header></app-header>
</div>
<router-outlet></router-outlet>
<app-footer></app-footer>

You can also use service

@Injectable()
export class AppService {
private showHeader: boolean = false;

public setHeader(flag) { // you need set header flag true false from other components on basis of your requirements, header component will be visible as per this flag then
this.showHeader = flag;
}

public getHeader(): boolean {
return this.showHeader;
}
}

App Component.ts
    AppComponent {
     constructor(public service: AppService){}
    }

App Component.html
    <div *ngIf='service.showHeader'> // you show hide on basis of this ngIf and header component always get visible with it's lifecycle hook ngOnInit() called all the time when it get visible
    <app-header></app-header>
    </div>
    <router-outlet></router-outlet>
    <app-footer></app-footer>

VSCode cannot find module '@angular/core' or any other modules

Delete Node Modules folder from project folder.Run below command

npm cache clean --force npm install

It should work.

Django - Reverse for '' not found. '' is not a valid view function or pattern name

When you use the url tag you should use quotes for string literals, for example:

{% url 'products' %}

At the moment product is treated like a variable and evaluates to '' in the error message.

Refused to load the font 'data:font/woff.....'it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src'

CSP helps you whitelisting sources that you trust. All other sources are not allowed access to. Read this Q&A carefully, and then make sure that you whitelist the fonts, socket connections and other sources if you trust them.

If you know what you are doing, you can comment out the meta tag to test, probably everything works. But realise that you / your user is being protected here, so keeping the meta tag is probably a good thing.

No resource found that matches the given name: attr 'android:keyboardNavigationCluster'. when updating to Support Library 26.0.0

//Adding this to the root build.gradle solved my problem, thanks @Yalamber
subprojects {
        afterEvaluate { project ->
            if (project.hasProperty("android")) {
                android {
                    compileSdkVersion 26
                    buildToolsVersion '26.0.2'
                }
            }
        }
    }

Adding a HTTP header to the Angular HttpClient doesn't send the header, why?

I was with Angular 8 and the only thing which worked for me was this:

  getCustomHeaders(): HttpHeaders {
    const headers = new HttpHeaders()
      .set('Content-Type', 'application/json')
      .set('Api-Key', 'xxx');
    return headers;
  }

Cannot find the '@angular/common/http' module

Important Update:

HttpModule and Http from @angular/http has been deprecated since Angular V5, should of using HttpClientModule and HttpClient from @angular/common/http instead, refer CHANGELOG.


For Angular version previous from **@4.3.0, You should inject Http from @angular/http, and HttpModule is for importing at your NgModule's import array.

import {HttpModule} from '@angular/http';

@NgModule({
  ...
  imports: [HttpModule]
})

Inject http at component or service

import { Http } from '@angular/http';

constructor(private http: Http) {}

For Angular version after(include) 4.3.0, you can use HttpClient from @angular/common/http instead of Http from @angular/http. Don't forget to import HttpClientModule at your NgModule's import array first.

Refer @echonax's answer.

Get current url in Angular

other.component.ts

So final correct solution is :

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router'; 

/* 'router' it must be in small case */

    @Component({
      selector: 'app-other',
      templateUrl: './other.component.html',
      styleUrls: ['./other.component.css']
    })

    export class OtherComponent implements OnInit {

        public href: string = "";
        url: string = "asdf";

        constructor(private router : Router) {} // make variable private so that it would be accessible through out the component

        ngOnInit() {
            this.href = this.router.url;
            console.log(this.router.url);
        }
    }

Component is not part of any NgModule or the module has not been imported into your module

My case is same as @7guyo mentioned. I'm using lazyloading and was unconsiously doing this:

import { component1Route } from './path/component1.route';

export const entityState: Routes = [
{
   path: 'home',
   children: component1Route
}]

Instead of:

@NgModule({
imports: [
   RouterModule.forChild([
   {
     path: '',
     loadChildren: () => import('./component1/component1.module').then(m => m.ComponentOneModule)
  },
  {
    path: '',
    loadChildren: () => import('./component2/component2.module').then(m => m.ComponentTwoModule)
  }])
  ]})

  export class MainModule {}

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

I also have the same error. I have updated the jackson library version and error has gone.

<!-- Jackson to convert Java object to Json -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.4</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.4</version>
        </dependency>
    </dependencies>

and also check your data classes that have you created getters and setters for all the properties.

'router-outlet' is not a known element

This issue was with me also. Simple trick for it.

 @NgModule({
  imports: [
   .....       
  ],
 declarations: [
  ......
 ],

 providers: [...],
 bootstrap: [...]
 })

use it as in above order.first imports then declarations.It worked for me.

More than one file was found with OS independent path 'META-INF/LICENSE'

I have read all the answers related to getting this message in Android Studio:

More than one file was found with OS independent path 'META-INF/LICENSE'

but in this case excluding classes is no neccessary, we only need to exclude 'META-INF/DEPENDENCIES', this can be done inside the /app/build.gradle:

android{
    ...
    ...
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
    }

}

Python: pandas merge multiple dataframes

Looks like the data has the same columns, so you can:

df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)

merged_df = pd.concat([df1, df2])

VS 2017 Metadata file '.dll could not be found

In my case, there was an error, but it was not properly parsed out by VS and shown in the "Error List" window. To find it, you much view the ol "Output" from build window and parse through the messages starting from top down and resolve the actual error. M$, please fix! This is a huge waste of time of the worlds collective developers.

How to send authorization header with axios

Try this :

axios.get(
    url,
    {headers: {
        "name" : "value"
      }
    }
  )
  .then((response) => {
      var response = response.data;
    },
    (error) => {
      var status = error.response.status
    }
  );

Load local images in React.js

In React.js latest version v17.0.1, we can not require the local image we have to import it. like we use to do before = require('../../src/Assets/images/fruits.png'); Now we have to import it like = import fruits from '../../src/Assets/images/fruits.png';

Before React V17.0.1 we can use require(../) and it is working fine.

How can I get the height of an element using css only

Unfortunately, it is not possible to "get" the height of an element via CSS because CSS is not a language that returns any sort of data other than rules for the browser to adjust its styling.

Your resolution can be achieved with jQuery, or alternatively, you can fake it with CSS3's transform:translateY(); rule.


The CSS Route

If we assume that your target div in this instance is 200px high - this would mean that you want the div to have a margin of 190px?

This can be achieved by using the following CSS:

.dynamic-height {
    -webkit-transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
    transform: translateY(100%);         //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
    margin-top: -10px;
}

In this instance, it is important to remember that translateY(100%) will move the element in question downwards by a total of it's own length.

The problem with this route is that it will not push element below it out of the way, where a margin would.


The jQuery Route

If faking it isn't going to work for you, then your next best bet would be to implement a jQuery script to add the correct CSS for you.

jQuery(document).ready(function($){ //wait for the document to load
    $('.dynamic-height').each(function(){ //loop through each element with the .dynamic-height class
        $(this).css({
            'margin-top' : $(this).outerHeight() - 10 + 'px' //adjust the css rule for margin-top to equal the element height - 10px and add the measurement unit "px" for valid CSS
        });
    });
});

How do you fix the "element not interactable" exception?

For those discovering this now and the above answers didn't work, the issue I had was the screen wasn't big enough. I added this when initializing my ChromeDriver, and it fixed the problem:

options.add_argument("window-size=1200x600")

Jersey stopped working with InjectionManagerFactory not found

The only way I could solve it was via:

org.glassfish.jersey.core jersey-server ${jersey-2-version}

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet</artifactId>
    <version>${jersey-2-version}</version>
</dependency>

<dependency>
    <groupId>org.glassfish.jersey.inject</groupId>
    <artifactId>jersey-hk2</artifactId>
    <version>${jersey-2-version}</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-common -->
<dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-common</artifactId>
    <version>${jersey-2-version}</version>
</dependency>

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet-core</artifactId>
    <version>${jersey-2-version}</version>
</dependency>

So, only if I added jersey-container-servlet and jersey-hk2 would it run without errors

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

In my case, I attempted to upgrade play_servicesand firebase versions to 15.0. Going back to 11.4.2 fixed my issue...

How to fix the error "Windows SDK version 8.1" was not found?

I installed the 8.1 SDK's version:

https://developer.microsoft.com/en-us/windows/downloads/sdk-archive

It used 1GB (a little more) in the installation.


Update October, 9. There's a https error: the sdksetup link is https://go.microsoft.com/fwlink/p/?LinkId=323507

"Save link as" should help.

Invalid self signed SSL cert - "Subject Alternative Name Missing"

To fix this, you need to supply an extra parameter to openssl when you're creating the cert, basically

-sha256 -extfile v3.ext

where v3.ext is a file like so, with %%DOMAIN%% replaced with the same name you use as your Common Name. More info here and over here. Note that typically you'd set the Common Name and %%DOMAIN%% to the domain you're trying to generate a cert for. So if it was www.mysupersite.com, then you'd use that for both.

v3.ext

authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = %%DOMAIN%%

Note: Scripts that address this issue, and create fully trusted ssl certs for use in Chrome, Safari and from Java clients can be found here

Another note: If all you're trying to do is stop chrome from throwing errors when viewing a self signed certificate, you can can tell Chrome to ignore all SSL errors for ALL sites by starting it with a special command line option, as detailed here on SuperUser

How to disable a ts rule for a specific line?

You can use /* tslint:disable-next-line */ to locally disable tslint. However, as this is a compiler error disabling tslint might not help.

You can always temporarily cast $ to any:

delete ($ as any).summernote.options.keyMap.pc.TAB

which will allow you to access whatever properties you want.


Edit: As of Typescript 2.6, you can now bypass a compiler error/warning for a specific line:

if (false) {
    // @ts-ignore: Unreachable code error
    console.log("hello");
}

Note that the official docs "recommend you use [this] very sparingly". It is almost always preferable to cast to any instead as that better expresses intent.

Spring boot: Unable to start embedded Tomcat servlet container

For me, I just had to put a -X flag with mvn. Look at the debug log; there was an issue with Spring while locating the .properties file.

How to uninstall an older PHP version from centOS7

Subscribing to the IUS Community Project Repository

cd ~
curl 'https://setup.ius.io/' -o setup-ius.sh

Run the script:

sudo bash setup-ius.sh

Upgrading mod_php with Apache

This section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section.

Begin by removing existing PHP packages. Press y and hit Enter to continue when prompted.

sudo yum remove php-cli mod_php php-common

Install the new PHP 7 packages from IUS. Again, press y and Enter when prompted.

sudo yum install mod_php70u php70u-cli php70u-mysqlnd

Finally, restart Apache to load the new version of mod_php:

sudo apachectl restart

You can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl:

systemctl status httpd

Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'

try with

<form formGroup="userForm">

instead of

<form [formGroup]="userForm">

Hibernate Error executing DDL via JDBC Statement

you have to be careful because reseved words are not only for table names, also you have to check column names, my mistake was that one of my columns was named "user". If you are using PostgreSQL the correct dialect is: org.hibernate.dialect.PostgreSQLDialect

cheers.

typescript: error TS2693: 'Promise' only refers to a type, but is being used as a value here

I got rid of this same error in index.ts with these combined properties:

In tsconfig.json:

  "compilerOptions": {
    "target": "ES6"

And in package.json:

  "main": "index.ts",
  "scripts": {
    "start": "tsc -p tsconfig.json && node index.js"

Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2

if you have lower version and getting problem importing project with high gradle version and want to run the project without updating gradle than

open your gradle file(Project) and do the small change

  dependencies {
           /*Higher Gradle version*/
//        classpath 'com.android.tools.build:gradle:3.0.0-alpha4'

        /*Add this line and remove the Higher one*/
        classpath 'com.android.tools.build:gradle:2.3.3'
    }

[2.3.3 is stand for your gradle version]

in your case change version to 3.2 or 3.2.0 something like that

Typescript ReferenceError: exports is not defined

my solution is a sum up of everything above with little tricks I added, basically I added this to my html code

<script>var exports = {"__esModule": true};</script>
<script src="js/file.js"></script>

this even allows you to use import instead of require if you're using electron or something, and it works fine with typescript 3.5.1, target: es3 -> esnext.

How to install/start Postman native v4.10.3 on Ubuntu 16.04 LTS 64-bit?

Edit:

If you have snap or want to install it, just do:

$ sudo snap install postman

if you don't have it, install it as:

$ sudo apt update
$ sudo apt install snapd

Another way is create an script:

First create this script:

create a file install-postman.sh, inside of it add:

#!/bin/bash
cd /tmp || exit
echo "Downloading Postman ..."
wget -q https://dl.pstmn.io/download/latest/linux?arch=64 -O postman.tar.gz
tar -xzf postman.tar.gz
rm postman.tar.gz

echo "Installing to opt..."
if [ -d "/opt/Postman" ];then
    sudo rm -rf /opt/Postman
fi
sudo mv Postman /opt/Postman

echo "Creating symbolic link..."
if [ -L "/usr/bin/postman" ];then
    sudo rm -f /usr/bin/postman
fi
sudo ln -s /opt/Postman/Postman /usr/bin/postman

echo "Installation completed successfully."
echo "You can use Postman!"

run it in terminal with:

$ sh install-postman.sh

Then create the desktop launcher:

Postman.desktop

[Desktop Entry]
Encoding=UTF-8
Name=Postman
Exec=postman
Icon=/opt/Postman/resources/app/assets/icon.png
Terminal=false
Type=Application
Categories=Development;

Put this file in your desktop if you want (don't forget give to it execution permissions). Double click, and that's it!

Forever thanks to Aviskase (github acount name).

source -> https://gist.github.com/aviskase/e642248c35e400b56e2489430952369f#file-postman-desktop

Cannot find module '@angular/compiler'

This command is working fine for me ubuntu 16.04 LTS:

npm install --save-dev @angular/cli@latest

Python Selenium Chrome Webdriver

You need to specify the path where your chromedriver is located.

  1. Download chromedriver for your desired platform from here.

  2. Place chromedriver on your system path, or where your code is.

  3. If not using a system path, link your chromedriver.exe (For non-Windows users, it's just called chromedriver):

    browser = webdriver.Chrome(executable_path=r"C:\path\to\chromedriver.exe")
    

    (Set executable_path to the location where your chromedriver is located.)

    If you've placed chromedriver on your System Path, you can shortcut by just doing the following:

    browser = webdriver.Chrome()

  4. If you're running on a Unix-based operating system, you may need to update the permissions of chromedriver after downloading it in order to make it executable:

    chmod +x chromedriver

  5. That's all. If you're still experiencing issues, more info can be found on this other StackOverflow article: Can't use chrome driver for Selenium

Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'

Solution for me (Android Studio) :

1) Use shortcut Ctrl+Shift+Alt+S or File -> Project Structure

2) and increase the level of SDK "Compile SDK Version".

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema

Webpack's configuration file has changed over the years (likely with each major release). The answer to the question:

Why do I get this error

Invalid configuration object. Webpack has been initialised using a 
configuration object that does not match the API schema

is because the configuration file doesn't match the version of webpack being used.

The accepted answer doesn't state this and other answers allude to this but don't state it clearly npm install [email protected], Just change from "loaders" to "rules" in "webpack.config.js", and this. So I decide to provide my answer to this question.

Uninstalling and re-installing webpack, or using the global version of webpack will not fix this problem. Using the correct version of webpack for the configuration file being used is what is important.

If this problem was fixed when using a global version it likely means that your global version was "old" and the webpack.config.js file format your using is "old" so they match and viola things now work. I'm all for things working, but want readers to know why they worked.

Whenever you get a webpack configuration that you hope is going to solve your problem ... ask yourself what version of webpack the configuration is for.

There are a lot of good resources for learning webpack. Some are:

There are a lot more good resources for learning webpack4 by example, please add comments if you know of others. Hopefully, future webpack articles will state the versions being used/explained.

MultipartException: Current request is not a multipart request

In application.properties, please add this:

spring.servlet.multipart.max-file-size=128KB
spring.servlet.multipart.max-request-size=128KB
spring.http.multipart.enabled=false

and in your html form, you need an : enctype="multipart/form-data". For example:

<form method="POST" enctype="multipart/form-data" action="/">

Hope this help!

Vue template or render function not defined yet I am using neither?

The reason you're receiving that error is that you're using the runtime build which doesn't support templates in HTML files as seen here vuejs.org

In essence what happens with vue loaded files is that their templates are compile time converted into render functions where as your base function was trying to compile from your html element.

ARG or ENV, which one to use in this case?

So if want to set the value of an environment variable to something different for every build then we can pass these values during build time and we don't need to change our docker file every time.

While ENV, once set cannot be overwritten through command line values. So, if we want to have our environment variable to have different values for different builds then we could use ARG and set default values in our docker file. And when we want to overwrite these values then we can do so using --build-args at every build without changing our docker file.

For more details, you can refer this.

My kubernetes pods keep crashing with "CrashLoopBackOff" but I can't find any log

I had the need to keep a pod running for subsequent kubectl exec calls and as the comments above pointed out my pod was getting killed by my k8s cluster because it had completed running all its tasks. I managed to keep my pod running by simply kicking the pod with a command that would not stop automatically as in:

kubectl run YOUR_POD_NAME -n YOUR_NAMESPACE --image SOME_PUBLIC_IMAGE:latest --command tailf /dev/null

Typescript react - Could not find a declaration file for module ''react-materialize'. 'path/to/module-name.js' implicitly has an any type

In my case I had a problem with react, so I started doing:

npm install @types/react

and then to the

npm install @types/react-dom

This worked for me

How to upgrade Angular CLI project?

To update Angular CLI to a new version, you must update both the global package and your project's local package.

Global package:

npm uninstall -g @angular/cli
npm cache clean
npm install -g @angular/cli@latest

Local project package:

rm -rf node_modules dist # use rmdir /S/Q node_modules dist in Windows Command Prompt; use rm -r -fo node_modules,dist in Windows PowerShell
npm install --save-dev @angular/cli@latest
npm install

See the reference https://github.com/angular/angular-cli

Angular2 module has no exported member

I got similar issue. The mistake i made was I did not add service in the providers array in app.module.ts. Hope this helps, Thank You.

tsconfig.json: Build:No inputs were found in config file

I have a tsconfig.json file that doesn't apply to any .ts files. It's in a separate folder. Instead I only use it as a base for other tsconfig files via "extends": "../Configs/tsconfig.json". As soon as I renamed the base config file to something else e.g. base-tsconfig.json (and updated the extends statements) the error went away and the extending still worked.

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

use this query in your local DB.

  1. select * from schema_version delete from schema_version where checksum Column = -1729781252;

    Note: -1729781252 is the "Resolved locally" value.

  2. Build and start the server.

can not find module "@angular/material"

Please check Angular Getting started :)

  1. Install Angular Material and Angular CDK
  2. Animations - if you need
  3. Import the component modules

and enjoy the {{Angular}}

Using Pip to install packages to Anaconda Environment

if you're using windows OS open Anaconda Prompt and type activate yourenvname

And if you're using mac or Linux OS open Terminal and type source activate yourenvname

yourenvname here is your desired environment in which you want to install pip package

after typing above command you must see that your environment name is changed from base to your typed environment yourenvname in console output (which means you're now in your desired environment context)

Then all you need to do is normal pip install command e.g pip install yourpackage

By doing so, the pip package will be installed in your Conda environment

Command to run a .bat file

You can use Cmd command to run Batch file.

Here is my way =>

cmd /c ""Full_Path_Of_Batch_Here.cmd" "

More information => cmd /?

try/catch blocks with async/await

A cleaner alternative would be the following:

Due to the fact that every async function is technically a promise

You can add catches to functions when calling them with await

async function a(){
    let error;

    // log the error on the parent
    await b().catch((err)=>console.log('b.failed'))

    // change an error variable
    await c().catch((err)=>{error=true; console.log(err)})

    // return whatever you want
    return error ? d() : null;
}
a().catch(()=>console.log('main program failed'))

No need for try catch, as all promises errors are handled, and you have no code errors, you can omit that in the parent!!

Lets say you are working with mongodb, if there is an error you might prefer to handle it in the function calling it than making wrappers, or using try catches.

selenium - chromedriver executable needs to be in PATH

You can download ChromeDriver here: https://sites.google.com/a/chromium.org/chromedriver/downloads

Then you have multiple options:

  • add it to your system path
  • put it in the same directory as your python script
  • specify the location directly via executable_path

    driver = webdriver.Chrome(executable_path='C:/path/to/chromedriver.exe')
    

Can I pass parameters in computed properties in Vue.Js

You can pass parameters but either it is not a vue.js way or the way you are doing is wrong.

However there are cases when you need to do so.I am going to show you a simple example passing value to computed property using getter and setter.

<template>
    <div>
        Your name is {{get_name}} <!-- John Doe at the beginning -->
        <button @click="name = 'Roland'">Change it</button>
    </div>
</template>

And the script

export default {
    data: () => ({
        name: 'John Doe'
    }),
    computed:{
        get_name: {
            get () {
                return this.name
            },
            set (new_name) {
                this.name = new_name
            }
        },
    }    
}

When the button clicked we are passing to computed property the name 'Roland' and in set() we are changing the name from 'John Doe' to 'Roland'.

Below there is a common use case when computed is used with getter and setter. Say you have the follow vuex store:

export default new Vuex.Store({
  state: {
    name: 'John Doe'
  },
  getters: {
    get_name: state => state.name
  },
  mutations: {
    set_name: (state, payload) => state.name = payload
  },
})

And in your component you want to add v-model to an input but using the vuex store.

<template>
    <div>
        <input type="text" v-model="get_name">
        {{get_name}}
    </div>
</template>
<script>
export default {
    computed:{
        get_name: {
            get () {
                return this.$store.getters.get_name
            },
            set (new_name) {
                this.$store.commit('set_name', new_name)
            }
        },
    }    
}
</script>

Merge two dataframes by index

A silly bug that got me: the joins failed because index dtypes differed. This was not obvious as both tables were pivot tables of the same original table. After reset_index, the indices looked identical in Jupyter. It only came to light when saving to Excel...

Fixed with: df1[['key']] = df1[['key']].apply(pd.to_numeric)

Hopefully this saves somebody an hour!

docker cannot start on windows

I was getting same errors after an install on Windows 10. And I tried restarting but it did not work, so I did the following (do not recommend if you have been working in docker for awhile, this was on a fresh install):

1) Find the whale in your system tray, and right click

2) Go to settings > Reset

3) Reset to factory defaults

I was then able to follow the starting docker tutorial on the website with Windows 10, and now it works like a charm.

Angular2: custom pipe could not be found

I encountered a similar issue, but putting it in my page’s module didn’t work.

I had created a component, which needed a pipe. This component was declared and exported in a ComponentsModule file, which holds all of the app’s custom components.

I had to put my PipesModule in my ComponentsModule as an import, in order for these components to use these pipes and not in the page’s module using that component.

Credits: enter link description here Answer by: tumain

Joining Spark dataframes on the key

inner join with scala

val joinedDataFrame = PersonDf.join(ProfileDf ,"personId")
joinedDataFrame.show

How to add a boolean datatype column to an existing table in sql?

The answer given by P????? creates a nullable bool, not a bool, which may be fine for you. For example in C# it would create: bool? AdminApprovednot bool AdminApproved.

If you need to create a bool (defaulting to false):

    ALTER TABLE person
    ADD AdminApproved BIT
    DEFAULT 0 NOT NULL;

Selenium using Python - Geckodriver executable needs to be in PATH

This error message...

FileNotFoundError: [WinError 2] The system cannot find the file specified

...implies that your program was unable to locate the specified file and while handling the exception the following exception occurred:

selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.

... which implies that your program was unable to locate the GeckoDriver in the process of initiating/spawnning a new Browsing Context i.e. Firefox Browser session.


You can download the latest GeckoDriver from mozilla / geckodriver, unzip/untar and store the GeckoDriver binary/executable anywhere with in your system passing the absolute path of the GeckoDriver through the key executable_path as follows:

from selenium import webdriver

driver = webdriver.Firefox(executable_path='/path/to/geckodriver')
driver.get('http://google.com/')

In case is not installed at the default location (i.e. installed at a custom location) additionally you need to pass the absolute path of firefox binary through the attribute binary_location as follows:

# An Windows example
from selenium import webdriver
from selenium.webdriver.firefox.options import Options

options = Options()
options.binary_location = r'C:\Program Files\Mozilla Firefox\firefox.exe'
driver = webdriver.Firefox(firefox_options=options, executable_path=r'C:\WebDrivers\geckodriver.exe')
driver.get('http://google.com/')

Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed

For those who use Gradle instead of Maven, add this to the dependencies in your build file:

compile('javax.xml.bind:jaxb-api:2.3.0')

Didn't find class "com.google.firebase.provider.FirebaseInitProvider"?

I had the same issue and solved just add a piece of code, If you are getting this issue means you had already completed all the steps that need to use Firebase. You just need to create a class that extends the Application (public class Application_CrashReport extends Application ) and add this class in mainifest file and In that class just override the below method

  @Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
}

and add MultiDex.install(this); in that method means

  @Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    MultiDex.install(this);
}

Note :- Don't forget to follow above steps

How do I activate a Spring Boot profile when running from IntelliJ?

Try this. Edit your build.gradle file as followed.

ext { profile = project.hasProperty('profile') ? project['profile'] : 'local' }

Angular 2 : No NgModule metadata found

I found that the cause of this problem in my case, was that I've combined my Angular app with a node.js application in the same source tree, and in the root tsconfig.json I had:

"files": [ "./node_modules/@types/node/index.d.ts" ]

I changed this to

"compilerOptions": { "types": ["node"] }

And then to prevent node types being uses in your angular app, add this to tsconfig.app.json:

"compilerOptions": { "types": [] }

Apache POI error loading XSSFWorkbook class

commons-collections4-x.x.jar definitely solve this problem but Apache has removed the Interface ListValuedMap from commons-Collections4-4.0.jar so use updated version 4.1 it has the required classes and Interfaces.

Refer here if you want to read Excel (2003 or 2007+) using java code.

http://www.codejava.net/coding/how-to-read-excel-files-in-java-using-apache-poi

TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

This

<div #myForm="ngForm"></div>

Also causes the error and can be fixed by including the ngForm directive.

<div ngForm #myForm="ngForm"></div>

<ng-container> vs <template>

In my case it acts like a <div> or <span> however even <span> messes up with my AngularFlex styling but ng-container doesn't.

CUSTOM_ELEMENTS_SCHEMA added to NgModule.schemas still showing Error

For me, I needed to look at :

1. If 'cl-header' is an Angular component, then verify that it is part of this module.

This means that your component isn't included in the app.module.ts. Make sure it's imported and then included in the declarations section.

import { NgModule }      from '@angular/core';

import { BrowserModule } from '@angular/platform-browser';

import { AppComponent }  from './app.component';

import { UtilModule } from "./modules/util_modules/util.module";
import { RoutingModule } from "./modules/routing_modules/routing.module";

import { HeaderComponent } from "./app/components/header.component";

@NgModule({
    bootstrap: [AppComponent],
    declarations: [
        AppComponent,
        HeaderComponent
    ],
    imports: [BrowserModule, UtilModule, RoutingModule]
})
export class AppModule { }

Updates were rejected because the tip of your current branch is behind its remote counterpart

It must be because of commit is ahead of your current push.

  1. git pull origin "name of branch you want to push"
  2. git rebase

If git rebase is successful, then good. Otherwise, you have resolve all merge conflicts locally and keep it continuing until rebase with remote is successful.

  1. git rebase --continue

Angular2 RC6: '<component> is not a known element'

In your planner component, you must be missing import HeaderAreaComponent like this-

import { HeaderAreaComponent } from '../header-area.component'; 
//change path according your project

Also, make sure - All the components and pipes must be declared via an NgModule.

See if this helps.

Error: Unexpected value 'undefined' imported by the module

As long as you are sure you are not doing anything wrong, kindly terminate "ng serve" and restart it. By so doing, the compiler does all of its work and the app serves as expected. Prior experiences with modules have taught me to either create them when "ng serve" is not running or to restart the terminal once I'm done.

Restarting "ng serve" also works when you're emitting a new component to another component, it's possible the compiler has not recognised your new component, simply restart "ng serve"

This worked for me just a few minutes ago.

The pipe ' ' could not be found angular2 custom pipe

Note : Only if you are not using angular modules

For some reason this is not in the docs but I had to import the custom pipe in the component

import {UsersPipe} from './users-filter.pipe'

@Component({
    ...
    pipes:      [UsersPipe]
})

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

If you use the Angular CLI to create your components, let's say CarComponent, it attaches app to the selector name (i.e app-car) and this throws the above error when you reference the component in the parent view. Therefore you either have to change the selector name in the parent view to let's say <app-car></app-car> or change the selector in the CarComponent to selector: 'car'

docker entrypoint running bash script gets "permission denied"

This is an old question asked two years prior to my answer, I am going to post what worked for me anyways.

In my working directory I have two files: Dockerfile & provision.sh

Dockerfile:

FROM centos:6.8

# put the script in the /root directory of the container
COPY provision.sh /root

# execute the script inside the container
RUN /root/provision.sh

EXPOSE 80

# Default command
CMD ["/bin/bash"]

provision.sh:

#!/usr/bin/env bash

yum upgrade

I was able to make the file in the docker container executable by setting the file outside the container as executable chmod 700 provision.sh then running docker build . .

Angular 2: Can't bind to 'ngModel' since it isn't a known property of 'input'

I encountered a similar error after upgrading to RC5; i.e. Angular 2: Can't bind to 'ngModel' since it isn't a known property of 'input'.

The code on Plunker show you using Angular2 RC4, but the example code at https://angular.io/docs/ts/latest/cookbook/dynamic-form.html is using NGModule which is part of RC5. NGModules is a breaking change from RC4 to RC5.

This page explains the migration from RC4 to RC5: https://angular.io/docs/ts/latest/cookbook/rc4-to-rc5.html

I hope this addresses the error you're getting and help get you going in the right direction.

In short, I had to create an NGModule in app.module.ts:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';

import { AppComponent }  from './app.component';

@NgModule({
    imports:      [ BrowserModule, FormsModule ],
    declarations: [ AppComponent ],
    bootstrap:    [ AppComponent ]
})
export class AppModule { }

I then changed main.ts to use the module:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

Of course, I also needed to update the dependencies in package.json. Here's my dependencies from package.json. Admittedly, I've hobbled them together from other sources (maybe the ng docs examples), so your mileage may vary:

...
"dependencies": {
    "@angular/common": "2.0.0-rc.5",
    "@angular/compiler": "2.0.0-rc.5",
    "@angular/core": "2.0.0-rc.5",
    "@angular/forms": "0.3.0",
    "@angular/http": "2.0.0-rc.5",
    "@angular/platform-browser": "2.0.0-rc.5",
    "@angular/platform-browser-dynamic": "2.0.0-rc.5",
    "@angular/router": "3.0.0-rc.1",
    "@angular/router-deprecated": "2.0.0-rc.2",
    "@angular/upgrade": "2.0.0-rc.5",
    "systemjs": "0.19.27",
    "core-js": "^2.4.0",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.6",
    "zone.js": "^0.6.12",
    "angular2-in-memory-web-api": "0.0.15",
    "bootstrap": "^3.3.6"
  },
...

I hope this helps better. :-)

ASP.NET Core 1.0 on IIS error 502.5

I got the same problem and the reason in my case was that the EF core was trying to read connection string from appsettings.development.json file. I opened it and found the connection string was commented.

//{
//  "ConnectionStrings": {
//    "DefaultConnection": "Server=vaio;Database=Goldentaurus;Trusted_Connection=True;",
//    "IdentityConnection": "Server=vaio;Database=GTIdentity;Trusted_Connection=True;"
//  }
//}

I then uncommitted them like below and the problem solved:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=vaio;Database=Goldentaurus;Trusted_Connection=True;",
    "IdentityConnection": "Server=vaio;Database=GTIdentity;Trusted_Connection=True;"
  }
}

How to merge two arrays of objects by ID using lodash?

If both arrays are in the correct order; where each item corresponds to its associated member identifier then you can simply use.

var merge = _.merge(arr1, arr2);

Which is the short version of:

var merge = _.chain(arr1).zip(arr2).map(function(item) {
    return _.merge.apply(null, item);
}).value();

Or, if the data in the arrays is not in any particular order, you can look up the associated item by the member value.

var merge = _.map(arr1, function(item) {
    return _.merge(item, _.find(arr2, { 'member' : item.member }));
});

You can easily convert this to a mixin. See the example below:

_x000D_
_x000D_
_.mixin({_x000D_
  'mergeByKey' : function(arr1, arr2, key) {_x000D_
    var criteria = {};_x000D_
    criteria[key] = null;_x000D_
    return _.map(arr1, function(item) {_x000D_
      criteria[key] = item[key];_x000D_
      return _.merge(item, _.find(arr2, criteria));_x000D_
    });_x000D_
  }_x000D_
});_x000D_
_x000D_
var arr1 = [{_x000D_
  "member": 'ObjectId("57989cbe54cf5d2ce83ff9d6")',_x000D_
  "bank": 'ObjectId("575b052ca6f66a5732749ecc")',_x000D_
  "country": 'ObjectId("575b0523a6f66a5732749ecb")'_x000D_
}, {_x000D_
  "member": 'ObjectId("57989cbe54cf5d2ce83ff9d8")',_x000D_
  "bank": 'ObjectId("575b052ca6f66a5732749ecc")',_x000D_
  "country": 'ObjectId("575b0523a6f66a5732749ecb")'_x000D_
}];_x000D_
_x000D_
var arr2 = [{_x000D_
  "member": 'ObjectId("57989cbe54cf5d2ce83ff9d8")',_x000D_
  "name": 'yyyyyyyyyy',_x000D_
  "age": 26_x000D_
}, {_x000D_
  "member": 'ObjectId("57989cbe54cf5d2ce83ff9d6")',_x000D_
  "name": 'xxxxxx',_x000D_
  "age": 25_x000D_
}];_x000D_
_x000D_
var arr3 = _.mergeByKey(arr1, arr2, 'member');_x000D_
_x000D_
document.body.innerHTML = JSON.stringify(arr3, null, 4);
_x000D_
body { font-family: monospace; white-space: pre; }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.0/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

How to get current available GPUs in tensorflow?

There is also a method in the test util. So all that has to be done is:

tf.test.is_gpu_available()

and/or

tf.test.gpu_device_name()

Look up the Tensorflow docs for arguments.

What is the best way to access redux store outside a react component?

An easy way to have access to the token, is to put the token in the LocalStorage or the AsyncStorage with React Native.

Below an example with a React Native project

authReducer.js

import { AsyncStorage } from 'react-native';
...
const auth = (state = initialState, action) => {
  switch (action.type) {
    case SUCCESS_LOGIN:
      AsyncStorage.setItem('token', action.payload.token);
      return {
        ...state,
        ...action.payload,
      };
    case REQUEST_LOGOUT:
      AsyncStorage.removeItem('token');
      return {};
    default:
      return state;
  }
};
...

and api.js

import axios from 'axios';
import { AsyncStorage } from 'react-native';

const defaultHeaders = {
  'Content-Type': 'application/json',
};

const config = {
  ...
};

const request = axios.create(config);

const protectedRequest = options => {
  return AsyncStorage.getItem('token').then(token => {
    if (token) {
      return request({
        headers: {
          ...defaultHeaders,
          Authorization: `Bearer ${token}`,
        },
        ...options,
      });
    }
    return new Error('NO_TOKEN_SET');
  });
};

export { request, protectedRequest };

For web you can use Window.localStorage instead of AsyncStorage

Visual Studio Code Automatic Imports

If anyone has run into this issue recently, I found I had to add a setting to use my workspace's version of typescript for the auto-imports to work. To do this, add this line to your workspace settings:

{
  "typescript.tsdk": "./node_modules/typescript/lib"
}

Then, with a typescript file open in vscode, click the typescript version number in the lower right-hand corner. When the options at the top appear, choose "use workspace version", then reload vscode.

Now auto-imports should work.

Error when trying to inject a service into an angular component "EXCEPTION: Can't resolve all parameters for component", why?

In my case, that was the TypeScript version that I upgraded to a major version and assignation assertions that I added to some Class properties.

Reverting the changes solved this for me. (details here)

Angular 2 - Setting selected value on dropdown list

In my case i was returning string value from my api eg: "35" and in my HTML i was using

       <mat-select placeholder="State*" formControlName="states" [(ngModel)]="selectedState" (ngModelChange)="getDistricts()">
            <mat-option *ngFor="let state of formInputs.states" [value]="state.stateId">
              {{ state.stateName }}
            </mat-option>
          </mat-select>

Like others mentioned in the comment value will only accept integer values i guess. So what I did is I converted my string value to integer in my component class like below

          var x = user.state;
          var y: number = +x;

and then assigned it like

  this.EditProfileForm.get('states').setValue(y);

Now the correct values is getting setting by default.

MySQL fails on: mysql "ERROR 1524 (HY000): Plugin 'auth_socket' is not loaded"

You can try with the below commands:

hduser@master:~$ sudo /etc/init.d/mysql stop
[ ok ] Stopping mysql (via systemctl): mysql.service.
hduser@master:~$ sudo /etc/init.d/mysql start
[ ok ] Starting mysql (via systemctl): mysql.service.

Hide strange unwanted Xcode logs

OS_ACTIVITY_MODE didn't work for me (it may have been because I typo'd disable as disabled, but isn't that more natural?!?), or at least didn't prevent a great deal of messages. So here's the real deal with the environment variables.

https://llvm.org/svn/llvm-project/lldb/trunk/source/Plugins/Platform/MacOSX/PlatformDarwin.cpp

lldb_private::Error
PlatformDarwin::LaunchProcess(lldb_private::ProcessLaunchInfo &launch_info) {
  // Starting in Fall 2016 OSes, NSLog messages only get mirrored to stderr
  // if the OS_ACTIVITY_DT_MODE environment variable is set.  (It doesn't
  // require any specific value; rather, it just needs to exist).
  // We will set it here as long as the IDE_DISABLED_OS_ACTIVITY_DT_MODE flag
  // is not set.  Xcode makes use of IDE_DISABLED_OS_ACTIVITY_DT_MODE to tell
  // LLDB *not* to muck with the OS_ACTIVITY_DT_MODE flag when they
  // specifically want it unset.
  const char *disable_env_var = "IDE_DISABLED_OS_ACTIVITY_DT_MODE";
  auto &env_vars = launch_info.GetEnvironmentEntries();
  if (!env_vars.ContainsEnvironmentVariable(disable_env_var)) {
    // We want to make sure that OS_ACTIVITY_DT_MODE is set so that
    // we get os_log and NSLog messages mirrored to the target process
    // stderr.
    if (!env_vars.ContainsEnvironmentVariable("OS_ACTIVITY_DT_MODE"))
      env_vars.AppendArgument(llvm::StringRef("OS_ACTIVITY_DT_MODE=enable"));
  }

  // Let our parent class do the real launching.
  return PlatformPOSIX::LaunchProcess(launch_info);
}

So setting OS_ACTIVITY_DT_MODE to "NO" in the environment variables (GUI method explained in Schemes screenshot in main answer) makes it work for me.

As far as NSLog being the dumping ground for system messages, errors, and your own debugging: a real logging approach is probably called for anyway, e.g. https://github.com/fpillet/NSLogger .

OR

Drink the new Kool-Aid: http://asciiwwdc.com/2016/sessions/721 https://developer.apple.com/videos/play/wwdc2016/721/ It's not surprising that there are some hitches after overhauling the entire logging API.

ADDENDUM

Anyway, NSLog is just a shim:

https://developer.apple.com/library/content/releasenotes/Miscellaneous/RN-Foundation-OSX10.12/

NSLog / CFLog

NSLog is now just a shim to os_log in most circumstances.

Only makes sense now to quote the source for the other env variable. Quite a disparate place, this time from Apple internals. Not sure why they are overlapping. [Incorrect comment about NSLog removed]

[Edited 22 Sep]: I wonder what "release" and "stream" do differently than "debug". Not enough source.

https://github.com/macosforge/libdispatch/blob/8e63547ea4e5abbfe55c0c3064181c4950a791d3/src/voucher.c

e = getenv("OS_ACTIVITY_MODE");
if (e) {
    if (strcmp(e, "release") == 0) {
        mode = voucher_activity_mode_release;
    } else if (strcmp(e, "debug") == 0) {
        mode = voucher_activity_mode_debug;
    } else if (strcmp(e, "stream") == 0) {
        mode = voucher_activity_mode_stream;
    } else if (strcmp(e, "disable") == 0) {
        mode = voucher_activity_mode_disable;
    }
}

How do I select and store columns greater than a number in pandas?

Sample DF:

In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))

In [80]: df
Out[80]:
    a   b   c
0   6  11  11
1  14   7   8
2  13   5  11
3  13   7  11
4  13   5   9
5   5  11   9
6   9   8   6
7   5  11  10
8   8  10  14
9   7  14  13

present only those rows where b > 10

In [81]: df[df.b > 10]
Out[81]:
   a   b   c
0  6  11  11
5  5  11   9
7  5  11  10
9  7  14  13

Minimums (for all columns) for the rows satisfying b > 10 condition

In [82]: df[df.b > 10].min()
Out[82]:
a     5
b    11
c     9
dtype: int32

Minimum (for the b column) for the rows satisfying b > 10 condition

In [84]: df.loc[df.b > 10, 'b'].min()
Out[84]: 11

UPDATE: starting from Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.

Static image src in Vue.js template

This solution is for Vue-2 users:

  1. In vue-2 if you don't like to keep your files in static folder (relevant info), or
  2. In vue-2 & vue-cli-3 if you don't like to keep your files in public folder (static folder is renamed to public):

The simple solution is :)

<img src="@/assets/img/clear.gif" /> // just do this:
<img :src="require(`@/assets/img/clear.gif`)" // or do this:
<img :src="require(`@/assets/img/${imgURL}`)" // if pulling from: data() {return {imgURL: 'clear.gif'}}

If you like to keep your static images in static/assets/img or public/assets/img folder, then just do:

<img src="./assets/img/clear.gif" />
<img src="/assets/img/clear.gif" /> // in some case without dot ./

Adb install failure: INSTALL_CANCELED_BY_USER

For MIUI OS Device

1) Go to Setting

2) Scroll down to Additional Setting

3) You will find Developer option at bottom

4) Turn this on - Install via USB: Toggle On

By turning this on, It is working charm in my MIUI8 device.

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexForDebug'

Well in my case i was accessing an static array of a class by reference of that class, but as we know we can directly access static member via class name. So when I replaced reference with class name where I was accessing that array. It fixed this error.

angular2 submit form by pressing enter without submit button

Edit:

  <form (submit)="submit()" >
    <input />
    <button type="submit" style="display:none">hidden submit</button>
  </form>

In order to use this method, you need to have a submit button even if it's not displayed "Thanks for Toolkit's answer"

Old Answer:

Yes, exactly as you wrote it, except the event name is (submit) instead of (ngSubmit):

<form [ngFormModel]="xxx" (submit)="xxxx()">
  <input [(ngModel)]="lxxR"   ngControl="xxxxx"/>
</form>

tsc throws `TS2307: Cannot find module` for a local file

The vscode codebase does not use relative paths, but everything works fine for them

Really depends on your module loader. If you are using systemjs with baseurl then it would work. VSCode uses its own custom module loader (based on an old version of requirejs).

Recommendation

Use relative paths as that is what commonjs supports. If you move files around you will get a typescript compile time error (a good thing) so you will be better off than a great majority of pure js projects out there (on npm).

Error:Execution failed for task ':app:transformClassesWithDexForDebug' in android studio

A temporary solution is to place the code below in the module build.gradle :

android { 
    aaptOptions.cruncherEnabled = false
    aaptOptions.useNewCruncher = false
}

And Sync the Project.

JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory

I found some issue about that kind of error

  1. Database username or password not match in the mysql or other other database. Please set application.properties like this

  

# =============================== # = DATA SOURCE # =============================== # Set here configurations for the database connection # Connection url for the database please let me know "[email protected]" spring.datasource.url = jdbc:mysql://localhost:3306/bookstoreapiabc # Username and secret spring.datasource.username = root spring.datasource.password = # Keep the connection alive if idle for a long time (needed in production) spring.datasource.testWhileIdle = true spring.datasource.validationQuery = SELECT 1 # =============================== # = JPA / HIBERNATE # =============================== # Use spring.jpa.properties.* for Hibernate native properties (the prefix is # stripped before adding them to the entity manager). # Show or not log for each sql query spring.jpa.show-sql = true # Hibernate ddl auto (create, create-drop, update): with "update" the database # schema will be automatically updated accordingly to java entities found in # the project spring.jpa.hibernate.ddl-auto = update # Allows Hibernate to generate SQL optimized for a particular DBMS spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

Issue no 2.

Your local server has two database server and those database server conflict. this conflict like this mysql server & xampp or lampp or wamp server. Please one of the database like mysql server because xampp or lampp server automatically install mysql server on this machine

Add Favicon with React and Webpack

Browsers look for your favicon in /favicon.ico, so that's where it needs to be. You can double check if you've positioned it in the correct place by navigating to [address:port]/favicon.ico and seeing if your icon appears.

In dev mode, you are using historyApiFallback, so will need to configure webpack to explicitly return your icon for that route:

historyApiFallback: {
    index: '[path/to/index]',
    rewrites: [
        // shows favicon
        { from: /favicon.ico/, to: '[path/to/favicon]' }
    ]
}

In your server.js file, try explicitly rewriting the url:

app.configure(function() {
    app.use('/favicon.ico', express.static(__dirname + '[route/to/favicon]'));
});

(or however your setup prefers to rewrite urls)

I suggest generating a true .ico file rather than using a .png, since I've found that to be more reliable across browsers.

#1292 - Incorrect date value: '0000-00-00'

The error is because of the sql mode which can be strict mode as per latest MYSQL 5.7 documentation.

For more information read this.

Hope it helps.

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.

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

To me it happened in DogController that autowired DogService that autowired DogRepository. Dog class used to have field name but I changed it to coolName, but didn't change methods in DogRepository: Dog findDogByName(String name). I change that method to Dog findDogByCoolName(String name) and now it works.

Add jars to a Spark Job - spark-submit

When using spark-submit with --master yarn-cluster, the application jar along with any jars included with the --jars option will be automatically transferred to the cluster. URLs supplied after --jars must be separated by commas. That list is included in the driver and executor classpaths

Example :

spark-submit --master yarn-cluster --jars ../lib/misc.jar, ../lib/test.jar --class MainClass MainApp.jar

https://spark.apache.org/docs/latest/submitting-applications.html

Angular 2: import external js file into component

Here is a simple way i did it in my project.

lets say you need to use clipboard.min.js and for the sake of the example lets say that inside clipboard.min.js there is a function that called test2().

in order to use test2() function you need:

  1. make a reference to the .js file inside you index.html.
  2. import clipboard.min.js to your component.
  3. declare a variable that will use you to call the function.

here are only the relevant parts from my project (see the comments):

index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Angular QuickStart</title>
    <base href="/src/">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">

    <!-- Polyfill(s) for older browsers -->
    <script src="/node_modules/core-js/client/shim.min.js"></script>


    <script src="/node_modules/zone.js/dist/zone.js"></script>
    <script src="/node_modules/systemjs/dist/system.src.js"></script>

    <script src="systemjs.config.js"></script>
    <script>
        System.import('main.js').catch(function (err) { console.error(err); });
    </script>

    <!-- ************ HERE IS THE REFERENCE TO clipboard.min.js -->
    <script src="app/txtzone/clipboard.min.js"></script>
</head>

<body>
    <my-app>Loading AppComponent content here ...</my-app>
</body>
</html>

app.component.ts:

import '../txtzone/clipboard.min.js';
declare var test2: any; // variable as the name of the function inside clipboard.min.js

@Component({
    selector: 'txt-zone',
    templateUrl: 'app/txtzone/Txtzone.component.html',
    styleUrls: ['app/txtzone/TxtZone.css'],
})



export class TxtZoneComponent implements AfterViewInit {

    // call test2
    callTest2()
    {   
        new test2(); // the javascript function will execute
    }

}

Combine [NgStyle] With Condition (if..else)

You can use this as follows:

<div [style.background-image]="value ? 'url(' + imgLink + ')' : 'url(' + defaultLink + ')'"></div>

The number of method references in a .dex file cannot exceed 64k API 17

For me Upgrading Gradle works.Look for update at Android Website then add it in your build.gradle (Project) like this

 dependencies {
        classpath 'com.android.tools.build:gradle:2.2.0-alpha4'   
          ....
    }

then sync project with gradle file plus it might be happened sometimes because of java.exe (in my case) just force kill java.exe from task manager in windows then re run program

angular2 manually firing click event on particular element

This worked for me:

<button #loginButton ...

and inside the controller:

@ViewChild('loginButton') loginButton;
...
this.loginButton.getNativeElement().click();

Install pip in docker

An alternative is to use the Alpine Linux containers, e.g. python:2.7-alpine. They offer pip out of the box (and have a smaller footprint which leads to faster builds etc).

Importing Pandas gives error AttributeError: module 'pandas' has no attribute 'core' in iPython Notebook

I got the same error for pandas latest version. Then saw this warning

FutureWarning: 'pandas.tools.plotting.scatter_matrix' is deprecated, import 'pandas.plotting.scatter_matrix' instead.

This shall work for you.

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

My answer provides a ways to run a subset of test in different scenarios.

Run all tests in a project

pytest

Run tests in a Single Directory

To run all the tests from one directory, use the directory as a parameter to pytest:

pytest tests/my-directory

Run tests in a Single Test File/Module

To run a file full of tests, list the file with the relative path as a parameter to pytest:

pytest tests/my-directory/test_demo.py

Run a Single Test Function

To run a single test function, add :: and the test function name:

pytest -v tests/my-directory/test_demo.py::test_specific_function

-v is used so you can see which function was run.

Run a Single Test Class

To run just a class, do like we did with functions and add ::, then the class name to the file parameter:

pytest -v tests/my-directory/test_demo.py::TestClassName

Run a Single Test Method of a Test Class

If you don't want to run all of a test class, just one method, just add another :: and the method name:

pytest -v tests/my-directory/test_demo.py::TestClassName::test_specific_method

Run a Set of Tests Based on Test Name

The -k option enables you to pass in an expression to run tests that have certain names specified by the expression as a substring of the test name. It is possible to use and, or, and not to create complex expressions.

For example, to run all of the functions that have _raises in their name:

pytest -v -k _raises

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.

Just add those below line in pom.xml file on the top of <modelversion> tag:

<repositories>
  <repository>
    <id>central</id>
    <name>Central Repository</name>
    <url>http://repo.maven.apache.org/maven2</url>
    <layout>default</layout>
    <snapshots>
      <enabled>false</enabled>
    </snapshots>
  </repository>
</repositories>

Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

You don't need hibernate-entitymanager-xxx.jar, because of you use a Hibernate session approach (not JPA). You need to close the SessionFactory too and rollback a transaction on errors. But, the problem, of course, is not with those.

This is returned by a database

#
org.postgresql.util.PSQLException: FATAL: password authentication failed for user "sa"
#

Looks like you've provided an incorrect username or (and) password.

Execution failed for task ':app:processDebugResources' even with latest build tools

as a quick fix to this question, make sure your compile Sdk verion, your buildtoolsversion, your appcompat, and finally your support library are all running on the same sdk version, for further clarity take a look at the image i just uploaded. Cheers. Follow the red annotations and get rid of that trouble.

enter image description here

The request was rejected because no multipart boundary was found in springboot

The "Postman - REST Client" is not suitable for doing post action with setting content-type.You can try to use "Advanced REST client" or others.

Additionally, headers was replace by consumes and produces since Spring 3.1 M2, see https://spring.io/blog/2011/06/13/spring-3-1-m2-spring-mvc-enhancements. And you can directly use produces = MediaType.MULTIPART_FORM_DATA_VALUE.

Disable Tensorflow debugging information

You can disable all debugging logs using os.environ :

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' 
import tensorflow as tf

Tested on tf 0.12 and 1.0

In details,

0 = all messages are logged (default behavior)
1 = INFO messages are not printed
2 = INFO and WARNING messages are not printed
3 = INFO, WARNING, and ERROR messages are not printed

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

Add this line to ProGuard-rules.pro file:

-keepparameternames

That helped me while obfuscating library. I was getting zip exception when I add library as dependency.

Implementing autocomplete

I'd like to add something that no one has yet mentioned: ng2-input-autocomplete

NPM: https://www.npmjs.com/package/ng2-input-autocomplete

GitHub: https://github.com/liuy97/ng2-input-autocomplete#readme

github: server certificate verification failed

I also was having this error when trying to clone a repository from Github on a Windows Subsystem from Linux console:

fatal: unable to access 'http://github.com/docker/getting-started.git/': server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

The solution from @VonC on this thread didn't work for me.

The solution from this Fabian Lee's article solved it for me:

openssl s_client -showcerts -servername github.com -connect github.com:443 </dev/null 2>/dev/null | sed -n -e '/BEGIN\ CERTIFICATE/,/END\ CERTIFICATE/ p'  > github-com.pem
cat github-com.pem | sudo tee -a /etc/ssl/certs/ca-certificates.crt

Angular: Cannot find a differ supporting object '[object Object]'

If you don't have an array but you are trying to use your observable like an array even though it's a stream of objects, this won't work natively. I show how to fix this below.

If you are trying to use an observable whose source is of type BehaviorSubject, change it to ReplaySubject then in your component subscribe to it like this:

Component

this.messages$ = this.chatService.messages$.pipe(scan((acc, val) => [...acc, val], []));

Html

<div class="message-list" *ngFor="let item of messages$ | async">

Angular2: How to load data before rendering the component?

You can pre-fetch your data by using Resolvers in Angular2+, Resolvers process your data before your Component fully be loaded.

There are many cases that you want to load your component only if there is certain thing happening, for example navigate to Dashboard only if the person already logged in, in this case Resolvers are so handy.

Look at the simple diagram I created for you for one of the way you can use the resolver to send the data to your component.

enter image description here

Applying Resolver to your code is pretty simple, I created the snippets for you to see how the Resolver can be created:

import { Injectable } from '@angular/core';
import { Router, Resolve, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';
import { MyData, MyService } from './my.service';

@Injectable()
export class MyResolver implements Resolve<MyData> {
  constructor(private ms: MyService, private router: Router) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<MyData> {
    let id = route.params['id'];

    return this.ms.getId(id).then(data => {
      if (data) {
        return data;
      } else {
        this.router.navigate(['/login']);
        return;
      }
    });
  }
}

and in the module:

import { MyResolver } from './my-resolver.service';

@NgModule({
  imports: [
    RouterModule.forChild(myRoutes)
  ],
  exports: [
    RouterModule
  ],
  providers: [
    MyResolver
  ]
})
export class MyModule { }

and you can access it in your Component like this:

/////
 ngOnInit() {
    this.route.data
      .subscribe((data: { mydata: myData }) => {
        this.id = data.mydata.id;
      });
  }
/////

And in the Route something like this (usually in the app.routing.ts file):

////
{path: 'yourpath/:id', component: YourComponent, resolve: { myData: MyResolver}}
////

How to import local packages in go?

Well, I figured out the problem. Basically Go starting path for import is $HOME/go/src

So I just needed to add myapp in front of the package names, that is, the import should be:

import (
    "log"
    "net/http"
    "myapp/common"
    "myapp/routers"
)

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

I have used MySQL DB for Hive MetaStore. Please follow the below steps:

  • in hive-site.xml the metastore should be proper
<property>
 <name>javax.jdo.option.ConnectionURL</name> 
 <value>jdbc:mysql://localhost/metastorecreateDatabaseIfNotExist=true&amp;useSSL=false</value>
</property>
  • go to the mysql: mysql -u hduser -p
  • then run drop database metastore
  • then come out from MySQL and execute schematool -initSchema dbType mysql

Now error will go.

How to use SqlClient in ASP.NET Core?

Try this one Open your projectname.csproj file its work for me.

<PackageReference Include="System.Data.SqlClient" Version="4.6.0" />

You need to add this Reference "ItemGroup" tag inside.

How can I enable the MySQLi extension in PHP 7?

For all docker users, just run docker-php-ext-install mysqli from inside your php container.

Update: More information on https://hub.docker.com/_/php in the section "How to install more PHP extensions".

AttributeError: 'dict' object has no attribute 'predictors'

#Try without dot notation
sample_dict = {'name': 'John', 'age': 29}
print(sample_dict['name']) # John
print(sample_dict['age']) # 29

NPM vs. Bower vs. Browserify vs. Gulp vs. Grunt vs. Webpack

What is webpack & webpack-dev-server? Official documentation says it's a module bundler but for me it's just a task runner. What's the difference?

webpack-dev-server is a live reloading web server that Webpack developers use to get immediate feedback what they do. It should only be used during development.

This project is heavily inspired by the nof5 unit test tool.

Webpack as the name implies will create a SINGLE package for the web. The package will be minimized, and combined into a single file (we still live in HTTP 1.1 age). Webpack does the magic of combining the resources (JavaScript, CSS, images) and injecting them like this: <script src="assets/bundle.js"></script>.

It can also be called module bundler because it must understand module dependencies, and how to grab the dependencies and to bundle them together.

Where would you use browserify? Can't we do the same with node/ES6 imports?

You could use Browserify on the exact same tasks where you would use Webpack. – Webpack is more compact, though.

Note that the ES6 module loader features in Webpack2 are using System.import, which not a single browser supports natively.

When would you use gulp/grunt over npm + plugins?

You can forget Gulp, Grunt, Brokoli, Brunch and Bower. Directly use npm command line scripts instead and you can eliminate extra packages like these here for Gulp:

var gulp        = require('gulp'),
  minifyCSS     = require('gulp-minify-css'),
  sass          = require('gulp-sass'),
  browserify    = require('gulp-browserify'),
  uglify        = require('gulp-uglify'),
  rename        = require('gulp-rename'),
  jshint        = require('gulp-jshint'),
  jshintStyle   = require('jshint-stylish'),
  replace       = require('gulp-replace'),
  notify        = require('gulp-notify'),

You can probably use Gulp and Grunt config file generators when creating config files for your project. This way you don't need to install Yeoman or similar tools.

TypeError: ufunc 'add' did not contain a loop with signature matching types

You have a numpy array of strings, not floats. This is what is meant by dtype('<U9') -- a little endian encoded unicode string with up to 9 characters.

try:

return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))

However, you don't need numpy here at all. You can really just do:

return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)

Or if you're really set on using numpy.

return np.asarray(listOfEmb, dtype=float).mean()

How to clear form after submit in Angular 2?

Hm, now (23 Jan 2017 with angular 2.4.3) I made it work like this:

newHero() {
    return this.model = new Hero(42, 'APPLIED VALUE', '');
}
<button type="button" class="btn btn-default" (click)="heroForm.resetForm(newHero())">New Hero</button>

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

check that, in your "google-services.json" file your package_name is available or not

Detect change to ngModel on a select tag (Angular 2)

Update:

Separate the event and property bindings:

<select [ngModel]="selectedItem" (ngModelChange)="onChange($event)">
onChange(newValue) {
    console.log(newValue);
    this.selectedItem = newValue;  // don't forget to update the model here
    // ... do other stuff here ...
}

You could also use

<select [(ngModel)]="selectedItem" (ngModelChange)="onChange($event)">

and then you wouldn't have to update the model in the event handler, but I believe this causes two events to fire, so it is probably less efficient.


Old answer, before they fixed a bug in beta.1:

Create a local template variable and attach a (change) event:

<select [(ngModel)]="selectedItem" #item (change)="onChange(item.value)">

plunker

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

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'
}

How does one set up the Visual Studio Code compiler/debugger to GCC?

You need to install C compiler, C/C++ extension, configure launch.json and tasks.json to be able to debug C code.

This article would guide you how to do it: https://medium.com/@jerrygoyal/run-debug-intellisense-c-c-in-vscode-within-5-minutes-3ed956e059d6

Can't type in React input text field

Once I ran into a similar error. Let me describe it.

Edit.js

   // components returns edit form 
   
   function EditVideo({id}) {
   .....
   
   // onChange event listener 
    const handleChange = (e) => {
       setTextData({
           ...textData,
           [e.target.name]: e.target.value.trim()
        });
     }
  
   ....
   ...
   }
)

ImportEdit.js

   import Edit from './Edit';
   
    function ImportEdit() {
    ......
     ...
    return (
        <div>
            <EditVideo id={id}/>
        </div>
       )
    }

    export default ImportEdit

The Problem was: I was unable to use spacebar (i.e. if i press spacekey, i didn't see space input)

The Bug: .trim()

.trim() method was trimming all the white space i typed

Note: Edit.js worked fine when used sepeartely without import

Global npm install location on windows?

If you're just trying to find out where npm is installing your global module (the title of this thread), look at the output when running npm install -g sample_module

$ npm install -g sample_module C:\Users\user\AppData\Roaming\npm\sample_module -> C:\Users\user\AppData\Roaming\npm\node_modules\sample_module\bin\sample_module.js + [email protected] updated 1 package in 2.821s

Getting "Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?" when installing lxml through pip

I got the same error for python 32 bit. After install 64bit, the problem was fixed.

Error:Execution failed for task ':app:transformClassesWithDexForDebug'

By changing

compile 'com.google.android.gms:play-services:8.1.0'

to only needed files, the problem can be solved This Issue is generated because of exceeding files in th build.gradle file.

AngularJS POST Fails: Response for preflight has invalid HTTP status code 404

You have enabled CORS and enabled Access-Control-Allow-Origin : * in the server.If still you get GET method working and POST method is not working then it might be because of the problem of Content-Type and data problem.

First AngularJS transmits data using Content-Type: application/json which is not serialized natively by some of the web servers (notably PHP). For them we have to transmit the data as Content-Type: x-www-form-urlencoded

Example :-

        $scope.formLoginPost = function () {
            $http({
                url: url,
                method: "POST",
                data: $.param({ 'username': $scope.username, 'Password': $scope.Password }),
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            }).then(function (response) {
                // success
                console.log('success');
                console.log("then : " + JSON.stringify(response));
            }, function (response) { // optional
                // failed
                console.log('failed');
                console.log(JSON.stringify(response));
            });
        };

Note : I am using $.params to serialize the data to use Content-Type: x-www-form-urlencoded. Alternatively you can use the following javascript function

function params(obj){
    var str = "";
    for (var key in obj) {
        if (str != "") {
            str += "&";
        }
        str += key + "=" + encodeURIComponent(obj[key]);
    }
    return str;
}

and use params({ 'username': $scope.username, 'Password': $scope.Password }) to serialize it as the Content-Type: x-www-form-urlencoded requests only gets the POST data in username=john&Password=12345 form.

Tensorflow image reading & display

Load names with tf.train.match_filenames_once get the number of files to iterate over with tf.size open session and enjoy ;-)

import tensorflow as tf
import numpy as np
import matplotlib;
from PIL import Image

matplotlib.use('Agg')
import matplotlib.pyplot as plt


filenames = tf.train.match_filenames_once('./images/*.jpg')
count_num_files = tf.size(filenames)
filename_queue = tf.train.string_input_producer(filenames)

reader=tf.WholeFileReader()
key,value=reader.read(filename_queue)
img = tf.image.decode_jpeg(value)

init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)
    num_files = sess.run(count_num_files)
    for i in range(num_files):
        image=img.eval()
        print(image.shape)
        Image.fromarray(np.asarray(image)).save('te.jpeg')

Tensorflow installation error: not a supported wheel on this platform

Make sure that the wheel is, well, supported by your platform. Pip uses the wheel's filename to determine compatibility. The format is:

tensorflow-{version}-{python version}-none-{your platform}.whl

I didn't realize that x86_64 refers to x64, I thought it meant either x86 or x64, so I banged my head against this futilely for some time. Tensorflow is not available for 32 bit systems, unless you want to compile it yourself.

How to Delete a topic in apache kafka

Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable to true) on all brokers first.

Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable is by default true.

Follow this step by step process for manual deletion of topics

  1. Stop Kafka server
  2. Delete the topic directory, on each broker (as defined in the logs.dirs and log.dir properties) with rm -rf command
  3. Connect to Zookeeper instance: zookeeper-shell.sh host:port
  4. From within the Zookeeper instance:
    1. List the topics using: ls /brokers/topics
    2. Remove the topic folder from ZooKeeper using: rmr /brokers/topics/yourtopic
    3. Exit the Zookeeper instance (Ctrl+C)
  5. Restart Kafka server
  6. Confirm if it was deleted or not by using this command kafka-topics.sh --list --zookeeper host:port

How do I completely rename an Xcode project (i.e. inclusive of folders)?

XCode 11.0+.

It's really simple now. Just go to Project Navigator left panel of the XCode window.
Press Enter to make it active for rename, just like you change the folder name.
enter image description here

Just change the new name here, and XCode will ask you for renaming other pieces of stuff.

enter image description here.

Tap on Rename here and you are done.
If you are confused about your root folder name that why it's not changed, well it's just a folder. just renamed it with a new name.
enter image description here

error: ORA-65096: invalid common user or role name in oracle

Create user dependency upon the database connect tools

sql plus
SQL> connect as sysdba;
Enter user-name: sysdba
Enter password:
Connected.
SQL> ALTER USER hr account unlock identified by hr;
User altered
 then create user on sql plus and sql developer

Conflict with dependency 'com.android.support:support-annotations'. Resolved versions for app (23.1.0) and test app (23.0.1) differ

You can force the annotation library in your test using:

androidTestCompile 'com.android.support:support-annotations:23.1.0'

Something like this:

  // Force usage of support annotations in the test app, since it is internally used by the runner module.
  androidTestCompile 'com.android.support:support-annotations:23.1.0'
  androidTestCompile 'com.android.support.test:runner:0.4.1'
  androidTestCompile 'com.android.support.test:rules:0.4.1'
  androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
  androidTestCompile 'com.android.support.test.espresso:espresso-intents:2.2.1'
  androidTestCompile 'com.android.support.test.espresso:espresso-web:2.2.1'

Another solution is to use this in the top level file:

configurations.all {
    resolutionStrategy.force 'com.android.support:support-annotations:23.1.0'
}

Webpack not excluding node_modules

From your config file, it seems like you're only excluding node_modules from being parsed with babel-loader, but not from being bundled.

In order to exclude node_modules and native node libraries from bundling, you need to:

  1. Add target: 'node' to your webpack.config.js. This will exclude native node modules (path, fs, etc.) from being bundled.
  2. Use webpack-node-externals in order to exclude other node_modules.

So your result config file should look like:

var nodeExternals = require('webpack-node-externals');
...
module.exports = {
    ...
    target: 'node', // in order to ignore built-in modules like path, fs, etc. 
    externals: [nodeExternals()], // in order to ignore all modules in node_modules folder 
    ...
};

HikariCP - connection is not available

From stack trace:

HikariPool: Timeout failure pool HikariPool-0 stats (total=20, active=20, idle=0, waiting=0) Means pool reached maximum connections limit set in configuration.

The next line: HikariPool-0 - Connection is not available, request timed out after 30000ms. Means pool waited 30000ms for free connection but your application not returned any connection meanwhile.

Mostly it is connection leak (connection is not closed after borrowing from pool), set leakDetectionThreshold to the maximum value that you expect SQL query would take to execute.

otherwise, your maximum connections 'at a time' requirement is higher than 20 !

com.android.build.transform.api.TransformException

Simply go to Build - Edit Build Types - Properties Tab - Build Type Version and downgrade it to ver 23.0.1. Click ok. This works for android studio 1.5. It worked for me.

java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration

This error is because of multiple project having the offending resources.

Try out adding the dependencies projects other way around. (like in pom.xml or external depandancies)

enter image description here

Get div's offsetTop positions in React

Eugene's answer uses the correct function to get the data, but for posterity I'd like to spell out exactly how to use it in React v0.14+ (according to this answer):

  import ReactDOM from 'react-dom';
  //...
  componentDidMount() {
    var rect = ReactDOM.findDOMNode(this)
      .getBoundingClientRect()
  }

Is working for me perfectly, and I'm using the data to scroll to the top of the new component that just mounted.

Best way to verify string is empty or null

You can make use of Optional and Apache commons Stringutils library

Optional.ofNullable(StringUtils.noEmpty(string1)).orElse(string2);

here it will check if the string1 is not null and not empty else it will return string2

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

This was asked on the www-style list, and Tab Atkins (spec editor) provided an answer explaining why. I'll elaborate on that a bit here.

To start out, let's initially assume our flex container is single-line (flex-wrap: nowrap). In this case, there's clearly an alignment difference between the main axis and the cross axis -- there are multiple items stacked in the main axis, but only one item stacked in the cross axis. So it makes sense to have a customizeable-per-item "align-self" in the cross axis (since each item is aligned separately, on its own), whereas it doesn't make sense in the main axis (since there, the items are aligned collectively).

For multi-line flexbox, the same logic applies to each "flex line". In a given line, items are aligned individually in the cross axis (since there's only one item per line, in the cross axis), vs. collectively in the main axis.


Here's another way of phrasing it: so, all of the *-self and *-content properties are about how to distribute extra space around things. But the key difference is that the *-self versions are for cases where there's only a single thing in that axis, and the *-content versions are for when there are potentially many things in that axis. The one-thing vs. many-things scenarios are different types of problems, and so they have different types of options available -- for example, the space-around / space-between values make sense for *-content, but not for *-self.

SO: In a flexbox's main axis, there are many things to distribute space around. So a *-content property makes sense there, but not a *-self property.

In contrast, in the cross axis, we have both a *-self and a *-content property. One determines how we'll distribute space around the many flex lines (align-content), whereas the other (align-self) determines how to distribute space around individual flex items in the cross axis, within a given flex line.

(I'm ignoring *-items properties here, since they simply establish defaults for *-self.)

Change the location of the ~ directory in a Windows install of Git Bash

I'd share what I did, which works not only for Git, but MSYS/MinGW as well.

The HOME environment variable is not normally set for Windows applications, so creating it through Windows did not affect anything else. From the Computer Properties (right-click on Computer - or whatever it is named - in Explorer, and select Properties, or Control Panel -> System and Security -> System), choose Advanced system settings, then Environment Variables... and create a new one, HOME, and assign it wherever you like.

If you can't create new environment variables, the other answer will still work. (I went through the details of how to create environment variables precisely because it's so dificult to find.)

SSL error SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

If you are using macOS sierra there is a update in PHP version. you need to have Entrust.net Certificate Authority (2048) file added to the PHP code. more info check accepted answer here Push Notification in PHP using PEM file

Deploying Maven project throws java.util.zip.ZipException: invalid LOC header (bad signature)

Here is an small detector written in Java , just copy and run :)

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarFile;
import java.util.stream.Collectors;

public class JarValidator {

    public static void main(String[] args) throws IOException {
        Path repositoryPath = Paths.get("C:\\Users\\goxr3plus\\.m2");

        // Check if the main Repository Exists
        if (Files.exists(repositoryPath)) {

            // Create a class instance
            JarValidator jv = new JarValidator();

            List<String> jarReport = new ArrayList<>();
            jarReport.add("Repository to process: " + repositoryPath.toString());

            // Get all the directory files
            List<Path> jarFiles = jv.getFiles(repositoryPath, ".jar");
            jarReport.add("Number of jars to process: " + jarFiles.size());
            jarReport.addAll(jv.openJars(jarFiles, true));

            // Print the report
            jarReport.stream().forEach(System.out::println);

        } else {
            System.out.println("Repository path " + repositoryPath + " does not exist.");
        }
    }

    /**
     * Get all the files from the given directory matching the specified extension
     * 
     * @param filePath      Absolute File Path
     * @param fileExtension File extension
     * @return A list of all the files contained in the directory
     * @throws IOException
     */
    private List<Path> getFiles(Path filePath, String fileExtension) throws IOException {
        return Files.walk(filePath).filter(p -> p.toString().endsWith(fileExtension)).collect(Collectors.toList());
    }

    /**
     * Try to open all the jar files
     * 
     * @param jarFiles
     * @return A List of Messages for Corrupted Jars
     */
    private List<String> openJars(List<Path> jarFiles, boolean showOkayJars) {
        int[] badJars = { 0 };
        List<String> messages = new ArrayList<>();

        // For Each Jar
        jarFiles.forEach(path -> {

            try (JarFile file = new JarFile(path.toFile())) {
                if (showOkayJars)
                    messages.add("OK : " + path.toString());
            } catch (IOException ex) {
                messages.add(path.toAbsolutePath() + " threw exception: " + ex.toString());
                badJars[0]++;
            }
        });

        messages.add("Total bad jars = " + badJars[0]);
        return messages;
    }

}

Output

Repository to process: C:\Users\goxr3plus\.m2
Number of jars to process: 4920
C:\Users\goxr3plus\.m2\repository\bouncycastle\isoparser-1.1.18.jar threw exception: java.util.zip.ZipException: zip END header not found
Total bad jars = 1
BUILD SUCCESSFUL (total time: 2 seconds)

Android "gps requires ACCESS_FINE_LOCATION" error, even though my manifest file contains this

My simple solution is this

if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) ==
        PackageManager.PERMISSION_GRANTED &&
        ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) ==
        PackageManager.PERMISSION_GRANTED) {
    googleMap.setMyLocationEnabled(true);
    googleMap.getUiSettings().setMyLocationButtonEnabled(true);
} else {
    Toast.makeText(this, R.string.error_permission_map, Toast.LENGTH_LONG).show();
}

or you can open permission dialog in else like this

} else {
   ActivityCompat.requestPermissions(this, new String[] {
      Manifest.permission.ACCESS_FINE_LOCATION, 
      Manifest.permission.ACCESS_COARSE_LOCATION }, 
      TAG_CODE_PERMISSION_LOCATION);
}

A better way to check if a path exists or not in PowerShell

This is my powershell newbie way of doing this

if ((Test-Path ".\Desktop\checkfile.txt") -ne "True") {
    Write-Host "Damn it"
} else {
    Write-Host "Yay"
}

RecyclerView and java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder in Samsung devices

I got the same problem and I have read that this happened in Samsung phones only...But the reality showed that this happens in a lot of brands.

After testing I realized that this happens only when you scroll fast the RecyclerView and then you go back either with the back button or the Up button. So I put inside Up button and onBackpressed the below snippet:

someList = new ArrayList<>();
mainRecyclerViewAdapter = new MainRecyclerViewAdapter(this, someList, this);
recyclerViewMain.setAdapter(mainRecyclerViewAdapter);
finish();

With this solution you just load a new Arraylist to the adapter and new adapter to recyclerView and then you finish activity.

Hope it helps someone

How to append rows in a pandas dataframe in a for loop?

Suppose your data looks like this:

import pandas as pd
import numpy as np

np.random.seed(2015)
df = pd.DataFrame([])
for i in range(5):
    data = dict(zip(np.random.choice(10, replace=False, size=5),
                    np.random.randint(10, size=5)))
    data = pd.DataFrame(data.items())
    data = data.transpose()
    data.columns = data.iloc[0]
    data = data.drop(data.index[[0]])
    df = df.append(data)
print('{}\n'.format(df))
# 0   0   1   2   3   4   5   6   7   8   9
# 1   6 NaN NaN   8   5 NaN NaN   7   0 NaN
# 1 NaN   9   6 NaN   2 NaN   1 NaN NaN   2
# 1 NaN   2   2   1   2 NaN   1 NaN NaN NaN
# 1   6 NaN   6 NaN   4   4   0 NaN NaN NaN
# 1 NaN   9 NaN   9 NaN   7   1   9 NaN NaN

Then it could be replaced with

np.random.seed(2015)
data = []
for i in range(5):
    data.append(dict(zip(np.random.choice(10, replace=False, size=5),
                         np.random.randint(10, size=5))))
df = pd.DataFrame(data)
print(df)

In other words, do not form a new DataFrame for each row. Instead, collect all the data in a list of dicts, and then call df = pd.DataFrame(data) once at the end, outside the loop.

Each call to df.append requires allocating space for a new DataFrame with one extra row, copying all the data from the original DataFrame into the new DataFrame, and then copying data into the new row. All that allocation and copying makes calling df.append in a loop very inefficient. The time cost of copying grows quadratically with the number of rows. Not only is the call-DataFrame-once code easier to write, it's performance will be much better -- the time cost of copying grows linearly with the number of rows.

Difference between PACKETS and FRAMES

A packet is a general term for a formatted unit of data carried by a network. It is not necessarily connected to a specific OSI model layer.

For example, in the Ethernet protocol on the physical layer (layer 1), the unit of data is called an "Ethernet packet", which has an Ethernet frame (layer 2) as its payload. But the unit of data of the Network layer (layer 3) is also called a "packet".

A frame is also a unit of data transmission. In computer networking the term is only used in the context of the Data link layer (layer 2).

Another semantical difference between packet and frame is that a frame envelops your payload with a header and a trailer, just like a painting in a frame, while a packet usually only has a header.

But in the end they mean roughly the same thing and the distinction is used to avoid confusion and repetition when talking about the different layers.

Confusing "duplicate identifier" Typescript error message

Update: Version 1.0 of Typings changed the output structure and the below answer relates to pre 1.0 version.

If you are using Typings and exclude in your tsconfig.json, you may run into the issue of duplicate types and need something like the following:

{
  "exclude": [
    "typings/browser.d.ts",
    "typings/browser",
    "node_modules"
  ]
}

To simplify integration with TypeScript, two files - typings/main.d.ts and typings/browser.d.ts - are generated which reference all the typings installed in the project only one of which can be used at a time.

So depending on which version you need, you should exclude (or include) the "browser" or the "main" type files, but not both, as this is where the duplicates come from.

This Typings issue discusses it more.

Microsoft.ReportViewer.Common Version=12.0.0.0

I was getting this error after deploying on IIS Server PC.

  1. First Install Microsoft SQL Server 2014 Feature Pack

https://www.microsoft.com/en-us/download/details.aspx?id=42295enter link description here

  1. Install Microsoft Report Viewer 2015 Runtime redistributable package

https://www.microsoft.com/en-us/download/details.aspx?id=45496

It may require restart your computer.

Cordova - Error code 1 for command | Command failed for

Faced same problem. Problem lies in required version not installed. Hack is simple Goto Platforms>platforms.json Edit platforms.json in front of android modify the version to the one which is installed on system.

Android Studio - Device is connected but 'offline'

Disabling and Enabling the Developer options and debug mode on the Android phone settings fixed the issue.

"Multiple definition", "first defined here" errors

I am adding this A because I got caught with a bizarre version of this which really had me scratching my head for about a hour until I spotted the root cause. My load was failing because of multiple repeats of this format

<path>/linit.o:(.rodata1.libs+0x50): multiple definition of `lua_lib_BASE'
<path>/linit.o:(.rodata1.libs+0x50): first defined here

I turned out to be a bug in my Makefile magic where I had a list of C files and using vpath etc., so the compiles would pick them up from the correct directory in hierarchy. However one C file was repeated in the list, at the end of one line and the start of the next so the gcc load generated by the make had the .o file twice on the command line. Durrrrh. The multiple definitions were from multiple occurances of the same file. The linker ignored duplicates apart from static initialisers!

Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved

For all the Windows users, try moving your codebase to a shorter windows path for eg: C:/myProj

Deeply nested Maven jar files can create a longer file path in windows. Since windows OS, by default, limits the file path length to 260 characters, it throws exception when trying to read a file located at a path that becomes more than 260 characters.

You can change this default to increase this limit to more than 260 chracters. Search around the web and you will find many posts on how to do that.

You can face similar problem while using npm packages also.

Ubuntu apt-get unable to fetch packages

I have been fighting the same thing for a while.

after all the research, this is the best solution.....

add the following to your resolve.conf file /etc/resolv.conf
nameserver 8.8.8.8
nameserver 8.8.4.4

https://serverfault.com/questions/717226/ubuntu14-04-unable-to-apt-get-update/771826#771826

HTML: Select multiple as dropdown

You probably need to some plugin like Jquery multiselect dropdown. Here is a demo.

Also you need to close your option tags like this:

<select name="test" multiple>
    <option>123</option>
    <option>456</option>
    <option>789</option>
</select>

JSFIDDLE DEMO

How to get local server host and port in Spring Boot?

For Spring 2

val hostName = InetAddress.getLocalHost().hostName

var webServerPort: Int = 0
@Configuration
class ApplicationListenerWebServerInitialized : ApplicationListener<WebServerInitializedEvent> {
    override fun onApplicationEvent(event: WebServerInitializedEvent) {
        webServerPort = event.webServer.port
    }
}

then you can use also webServerPort from anywhere...

Java finished with non-zero exit value 2 - Android Gradle

There are two alternatives that'll work for sure:

  1. Clean your project and then build.

If the above method didn't worked, try the next.

  1. Add the following to build.gradle file at app level

    defaultConfig {   
    
    multiDexEnabled true
    
    }
    

Writing a new line to file in PHP (line feed)

Replace '\n' with "\n". The escape sequence is not recognized when you use '.

See the manual.

For the question of how to write line endings, see the note here. Basically, different operating systems have different conventions for line endings. Windows uses "\r\n", unix based operating systems use "\n". You should stick to one convention (I'd chose "\n") and open your file in binary mode (fopen should get "wb", not "w").

How to make/get a multi size .ico file?

'@icon sushi' is a portable utility that can create multiple icon ico file for free.

Drag & drop the different icon sizes, select them all and choose file -> create multiple icon.

You can download if from http://www.towofu.net/soft/e-aicon.php

SQL SERVER DATETIME FORMAT

case when isdate(inputdate) = 1 
then convert(datetime, cast(inputdate,datetime2), 103)
else
case when isdate(inputdate) = 0 
then convert(datetime, cast(inputdate,datetime2), 103)

Go back button in a page

onclick="history.go(-1)" Simply

Wordpress plugin install: Could not create directory

CentOS7 or Ubuntu 16


1.

WordPress uses ftp to install themes and plugins.
So the ftpd should have been configured to create-directory

vim /etc/pure-ftpd.confg

and if it is no then should be yes

# Are anonymous users allowed to create new directories?
AnonymousCanCreateDirs       yes

lastly

sudo systemctl restart pure-ftpd

2.

Maybe there is an ownership issue with the parent directories. Find the Web Server user name and group name if it is Apache Web Server

apachectl -S

it will print

...
...
User: name="apache" id=997
Group: name="apache" id=1000

on Ubuntu it is

User: name="www-data" id=33 not_used
Group: name="www-data" id=33 not_used

then

sudo chown -R apache:apache directory-name

3.

Sometimes it is because of directories permissions. So try

sudo chmod -R 755 directory-name

in some cases 755 does not work. (It should & I do not no why) so try

sudo chmod -R 777 directory-name

4.

Maybe it is because of php safe mode. So turn it off in the root of your domain

vim php.ini

then add

safe_mode = Off

NOTE:
For not entering FTP username and password each time installing a theme we can configure WordPress to use it directly by adding

define('FS_METHOD','direct');

to the wp-config.php file.

IE9 jQuery AJAX with CORS returns "Access is denied"

Update as of early 2015. xDomain is a widely used library to supports CORS on IE9 with limited extra coding.

https://github.com/jpillora/xdomain

Store multiple values in single key in json

{
    "success": true,
    "data": {
        "BLR": {
            "origin": "JAI",
            "destination": "BLR",
            "price": 127,
            "transfers": 0,
            "airline": "LB",
            "flight_number": 655,
            "departure_at": "2017-06-03T18:20:00Z",
            "return_at": "2017-06-07T08:30:00Z",
            "expires_at": "2017-03-05T08:40:31Z"
        }
    }
};

How can I get form data with JavaScript/jQuery?

This will append all form fields to the JavaScript object "res":

var res = {};
$("#form input, #form select, #form textarea").each(function(i, obj) {
    res[obj.name] = $(obj).val();
})

What is Cache-Control: private?

The Expires entity-header field gives the date/time after which the response is considered stale.The Cache-control:maxage field gives the age value (in seconds) bigger than which response is consider stale.

Althought above header field give a mechanism to client to decide whether to send request to the server. In some condition, the client send a request to sever and the age value of response is bigger then the maxage value ,dose it means server needs to send the resource to client? Maybe the resource never changed.

In order to resolve this problem, HTTP1.1 gives last-modifided head. The server gives the last modified date of the response to client. When the client need this resource, it will send If-Modified-Since head field to server. If this date is before the modified date of the resouce, the server will sends the resource to client and gives 200 code.Otherwise,it will returns 304 code to client and this means client can use the resource it cached.

Provide an image for WhatsApp link sharing

I'd recommend always have a look at https://developers.facebook.com/tools/debug/sharing to validate your properties as Facebook often changes it's policies, compliances and API.

If you work with Messenger bots or other FB apps, you may need the property fb:app_id for link images to work in Whatsapp. More at Facebook developers webmasters site. https://developers.facebook.com/docs/sharing/webmasters

Replace new lines with a comma delimiter with Notepad++?

A regex match with \s+ worked for me:

enter image description here

What is the use of static variable in C#? When to use it? Why can't I declare the static variable inside method?

Static classes don't require you to create an object of that class/instantiate them, you can prefix the C# keyword static in front of the class name, to make it static.

Remember: we're not instantiating the Console class, String class, Array Class.

class Book
{
    public static int myInt = 0;
}

public class Exercise
{
    static void Main()
    {
        Book book = new Book();
       //Use the class name directly to call the property myInt, 
      //don't use the object to access the value of property myInt

        Console.WriteLine(Book.myInt);

        Console.ReadKey();

    }
}

Flushing buffers in C

Flushing the output buffers:

printf("Buffered, will be flushed");
fflush(stdout); // Prints to screen or whatever your standard out is

or

fprintf(fd, "Buffered, will be flushed");
fflush(fd);  //Prints to a file

Can be a very helpful technique. Why would you want to flush an output buffer? Usually when I do it, it's because the code is crashing and I'm trying to debug something. The standard buffer will not print everytime you call printf() it waits until it's full then dumps a bunch at once. So if you're trying to check if you're making it to a function call before a crash, it's helpful to printf something like "got here!", and sometimes the buffer hasn't been flushed before the crash happens and you can't tell how far you've really gotten.

Another time that it's helpful, is in multi-process or multi-thread code. Again, the buffer doesn't always flush on a call to a printf(), so if you want to know the true order of execution of multiple processes you should fflush the buffer after every print.

I make a habit to do it, it saves me a lot of headache in debugging. The only downside I can think of to doing so is that printf() is an expensive operation (which is why it doesn't by default flush the buffer).


As far as flushing the input buffer (stdin), you should not do that. Flushing stdin is undefined behavior according to the C11 standard §7.21.5.2 part 2:

If stream points to an output stream ... the fflush function causes any unwritten data for that stream ... to be written to the file; otherwise, the behavior is undefined.

On some systems, Linux being one as you can see in the man page for fflush(), there's a defined behavior but it's system dependent so your code will not be portable.

Now if you're worried about garbage "stuck" in the input buffer you can use fpurge() on that. See here for more on fflush() and fpurge()

smtpclient " failure sending mail"

I experienced the same issue when sending high volume email. Setting the deliveryMethod property to PickupDirectoryFromIis fixed it for me. Also don't create a new SmtpClient everytime.

MySQL - Select the last inserted row easiest way

SELECT ID from bugs WHERE user=Me ORDER BY CREATED_STAMP DESC; BY CREATED_STAMP DESC fetches those data at index first which last created.

I hope it will resolve your problem

How to debug a Flask app

For Windows users:

Open Powershell and cd into your project directory.

Use these commandos in Powershell, all the other stuff won't work in Powershell.

$env:FLASK_APP = "app"  
$env:FLASK_ENV = "development"

SQL Query to concatenate column values from multiple rows in Oracle

For those who must solve this problem using Oracle 9i (or earlier), you will probably need to use SYS_CONNECT_BY_PATH, since LISTAGG is not available.

To answer the OP, the following query will display the PID from Table A and concatenate all the DESC columns from Table B:

SELECT pid, SUBSTR (MAX (SYS_CONNECT_BY_PATH (description, ', ')), 3) all_descriptions
FROM (
       SELECT ROW_NUMBER () OVER (PARTITION BY pid ORDER BY pid, seq) rnum, pid, description
       FROM (
              SELECT a.pid, seq, description
              FROM table_a a, table_b b
              WHERE a.pid = b.pid(+)
             )
      )
START WITH rnum = 1
CONNECT BY PRIOR rnum = rnum - 1 AND PRIOR pid = pid
GROUP BY pid
ORDER BY pid;

There may also be instances where keys and values are all contained in one table. The following query can be used where there is no Table A, and only Table B exists:

SELECT pid, SUBSTR (MAX (SYS_CONNECT_BY_PATH (description, ', ')), 3) all_descriptions
FROM (
       SELECT ROW_NUMBER () OVER (PARTITION BY pid ORDER BY pid, seq) rnum, pid, description
       FROM (
              SELECT pid, seq, description
              FROM table_b
             )
      )
START WITH rnum = 1
CONNECT BY PRIOR rnum = rnum - 1 AND PRIOR pid = pid
GROUP BY pid
ORDER BY pid;

All values can be reordered as desired. Individual concatenated descriptions can be reordered in the PARTITION BY clause, and the list of PIDs can be reordered in the final ORDER BY clause.


Alternately: there may be times when you want to concatenate all the values from an entire table into one row.

The key idea here is using an artificial value for the group of descriptions to be concatenated.

In the following query, the constant string '1' is used, but any value will work:

SELECT SUBSTR (MAX (SYS_CONNECT_BY_PATH (description, ', ')), 3) all_descriptions
FROM (
       SELECT ROW_NUMBER () OVER (PARTITION BY unique_id ORDER BY pid, seq) rnum, description
       FROM (
              SELECT '1' unique_id, b.pid, b.seq, b.description
              FROM table_b b
             )
      )
START WITH rnum = 1
CONNECT BY PRIOR rnum = rnum - 1;

Individual concatenated descriptions can be reordered in the PARTITION BY clause.

Several other answers on this page have also mentioned this extremely helpful reference: https://oracle-base.com/articles/misc/string-aggregation-techniques

How can one run multiple versions of PHP 5.x on a development LAMP server?

Understanding that you're probably talking about a local/desktop machine and would probably like to continue talking about a local/desktop machine, I'll throw an alternative out there for you just in case it might help you or someone else:

Set up multiple virtual server instances in the cloud, and share your code between them as a git repository (or mercurial, I suppose, though I have no personal experience all you really need is something decentralized). This has the benefit of giving you as close to a production experience as possible, and if you have experience setting up servers then it's not that complicated (or expensive, if you just want to spin a server up, do what you need to do, then spin it down again, then you're talking about a few cents up to say 50 cents, up to a few bucks if you just leave it running).

I do all of my project development in the cloud these days and I've found it much simpler to manage the infrastructure than I ever did when using local/non-virtualized installs, and it makes this sort of side-by-side scenario fairly straight forward. I just wanted to throw the idea out there if you hadn't considered it.

css ellipsis on second line

I'm not a JS pro, but I figured out a couple ways you could do this.

The HTML:

<p id="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi elementum consequat tortor et euismod. Nam commodo consequat libero vel lobortis. Morbi ac nisi at leo vehicula consectetur.</p>

Then with jQuery you truncate it down to a specific character count but leave the last word like this:

// Truncate but leave last word
var myTag = $('#truncate').text();
if (myTag.length > 100) {
  var truncated = myTag.trim().substring(0, 100).split(" ").slice(0, -1).join(" ") + "…";
  $('#truncate').text(truncated);
}

The result looks like this:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi
elementum consequat tortor et…

Or, you can simply truncate it down to a specific character count like this:

// Truncate to specific character
var myTag = $('#truncate').text();
if (myTag.length > 15) {
  var truncated = myTag.trim().substring(0, 100) + "…";
  $('#truncate').text(truncated);
}

The result looks like this:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi
elementum consequat tortor et euismod…

Hope that helps a bit.

Here is the jsFiddle.

How do you access the value of an SQL count () query in a Java program

I have done it this way (example):

String query="SELECT count(t1.id) from t1, t2 where t1.id=t2.id and t2.email='"[email protected]"'";
int count=0;
try {
    ResultSet rs = DatabaseService.statementDataBase().executeQuery(query);
    while(rs.next())
        count=rs.getInt(1);
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    //...
}

Equivalent VB keyword for 'break'

In case you're inside a Sub of Function and you want to exit it, you can use :

Exit Sub

or

Exit Function 

ArrayAdapter in android to create simple listview

The TextView resource id it needs is for a TextView layout file, so it won't be in the same activity.

You can create it by going to File > New > XML > XML Layout File, and enter the widget type, which is 'TextView' in the root tag field.

Source: https://www.kompulsa.com/the-simplest-way-to-implement-an-android-listview/

How do I install Eclipse with C++ in Ubuntu 12.10 (Quantal Quetzal)?

I was in the same boat. Installed Eclipse, realized need CDT.

sudo apt-get install eclipse eclipse-cdt g++

This just adds the CDT package on top of existing installation - no un-installation etc. required.

Mockito How to mock and assert a thrown exception?

Use Mockito's doThrow and then catch the desired exception to assert it was thrown later.

@Test
public void fooShouldThrowMyException() {
    // given
    val myClass = new MyClass();
    val arg = mock(MyArgument.class);
    doThrow(MyException.class).when(arg).argMethod(any());
    Exception exception = null;

    // when
    try {
        myClass.foo(arg);
    } catch (MyException t) {
        exception = t;
    }

    // then
    assertNotNull(exception);
}

Getting a slice of keys from a map

For example,

package main

func main() {
    mymap := make(map[int]string)
    keys := make([]int, 0, len(mymap))
    for k := range mymap {
        keys = append(keys, k)
    }
}

To be efficient in Go, it's important to minimize memory allocations.

PHP strtotime +1 month adding an extra month

It's jumping to March because today is 29th Jan, and adding a month gives 29th Feb, which doesn't exist, so it's moving to the next valid date.

This will happen on the 31st of a lot of months as well, but is obviously more noticable in the case of January to Feburary because Feb is shorter.

If you're not interested in the day of month and just want it to give the next month, you should specify the input date as the first of the current month. This will always give you the correct answer if you add a month.

For the same reason, if you want to always get the last day of the next month, you should start by calculating the first of the month after the one you want, and subtracting a day.

Google Maps API: open url by clicking on marker

the previous answers didn't work out for me well. I had persisting problems by setting the marker. So i changed the code slightly.

   <!DOCTYPE html>
   <html>
   <head>
     <meta http-equiv="content-type" content="text/html; charset=ANSI" />
     <title>Google Maps Multiple Markers</title>
     <script src="http://maps.google.com/maps/api/js?sensor=false"
      type="text/javascript"></script>
   </head>
   <body>
     <div id="map" style="width: 1500px; height: 1000px;"></div>

     <script type="text/javascript">
       var locations = [
         ['Goettingen',  51.54128040000001,  9.915803500000038, 'http://www.google.de'],
         ['Kassel', 51.31271139999999,  9.479746100000057,0, 'http://www.stackoverflow.com'],
         ['Witzenhausen', 51.33996819999999,  9.855564299999969,0, 'www.http://developer.mozilla.org.de']

 ];

var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 10,
 center: new google.maps.LatLng(51.54376, 9.910419999999931),
 mapTypeId: google.maps.MapTypeId.ROADMAP
});

var infowindow = new google.maps.InfoWindow();

var marker, i;

for (i = 0; i < locations.length; i++) {
  marker = new google.maps.Marker({
   position: new google.maps.LatLng(locations[i][1], locations[i][2]),
   map: map,
   url: locations[i][4]
  });

 google.maps.event.addListener(marker, 'mouseover', (function(marker, i) {
   return function() {
     infowindow.setContent(locations[i][0]);
     infowindow.open(map, marker);
   }
 })(marker, i));

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
   return function() {
     infowindow.setContent(locations[i][0]);
     infowindow.open(map, marker);
     window.location.href = this.url;
   }
 })(marker, i));

    }

     </script>
   </body>
   </html>

This way worked out for me! You can create Google Maps routing links from your Datebase to to use it as an interactive routing map.

Display List in a View MVC

Your action method considers model type asList<string>. But, in your view you are waiting for IEnumerable<Standings.Models.Teams>. You can solve this problem with changing the model in your view to List<string>.

But, the best approach would be to return IEnumerable<Standings.Models.Teams> as a model from your action method. Then you haven't to change model type in your view.

But, in my opinion your models are not correctly implemented. I suggest you to change it as:

public class Team
{
    public int Position { get; set; }
    public string HomeGround {get; set;}
    public string NickName {get; set;}
    public int Founded { get; set; }
    public string Name { get; set; }
}

Then you must change your action method as:

public ActionResult Index()
{
    var model = new List<Team>();

    model.Add(new Team { Name = "MU"});
    model.Add(new Team { Name = "Chelsea"});
    ...

    return View(model);
}

And, your view:

@model IEnumerable<Standings.Models.Team>

@{
     ViewBag.Title = "Standings";
}

@foreach (var item in Model)
{
    <div>
        @item.Name
        <hr />
    </div>
}

Using HeapDumpOnOutOfMemoryError parameter for heap dump for JBoss

I found it hard to decipher what is meant by "working directory of the VM". In my example, I was using the Java Service Wrapper program to execute a jar - the dump files were created in the directory where I had placed the wrapper program, e.g. c:\myapp\bin. The reason I discovered this is because the files can be quite large and they filled up the hard drive before I discovered their location.

invalid multibyte char (US-ASCII) with Rails and Ruby 1.9

If you want to add magic comments on all the source files of a project easily, you can use the magic_encoding gem

sudo gem install magic_encoding

then just call magic_encoding in the terminal from the root of your app.

Is it possible to have SSL certificate for IP address, not domain name?

The short answer is yes, as long as it is a public IP address.

Issuance of certificates to reserved IP addresses is not allowed, and all certificates previously issued to reserved IP addresses were revoked as of 1 October 2016.

According to the CA Browser forum, there may be compatibility issues with certificates for IP addresses unless the IP address is in both the commonName and subjectAltName fields. This is due to legacy SSL implementations which are not aligned with RFC 5280, notably, Windows OS prior to Windows 10.


Sources:

  1. Guidance on IP Addresses In Certificates CA Browser Forum
  2. Baseline Requirements 1.4.1 CA Browser Forum
  3. The (soon to be) not-so Common Name unmitigatedrisk.com
  4. RFC 5280 IETF

Note: an earlier version of this answer stated that all IP address certificates would be revoked on 1 October 2016. Thanks to Navin for pointing out the error.

Sort list in C# with LINQ

Like this?

In LINQ:

var sortedList = originalList.OrderBy(foo => !foo.AVC)
                             .ToList();

Or in-place:

originalList.Sort((foo1, foo2) => foo2.AVC.CompareTo(foo1.AVC));

As Jon Skeet says, the trick here is knowing that false is considered to be 'smaller' than true.

If you find that you are doing these ordering operations in lots of different places in your code, you might want to get your type Foo to implement the IComparable<Foo> and IComparable interfaces.

How do I convert number to string and pass it as argument to Execute Process Task?

Expression: "Total Count: " + (DT_WSTR, 11)@[User::int32Value]

for Int32 -- (-2,147,483,648 to 2,147,483,647)

ES6 exporting/importing in index file

Simply:

// Default export (recommended)
export {default} from './MyClass' 

// Default export with alias
export {default as d1} from './MyClass' 

// In >ES7, it could be
export * from './MyClass'

// In >ES7, with alias
export * as d1 from './MyClass'

Or by functions names :

// export by function names
export { funcName1, funcName2, …} from './MyClass'

// export by aliases
export { funcName1 as f1, funcName2 as f2, …} from './MyClass'

More infos: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export

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

Running npm init -y makes your package.json with all the defaults.
You can then change package.json accordingly
This saves time many a times by preventing pressing enter on every command in npm init

Amazon AWS Filezilla transfer permission denied

To allow user ec2-user (Amazon AWS) write access to the public web directory (/var/www/html),
enter this command via Putty or Terminal, as the root user sudo:

chown -R ec2-user /var/www/html

Make sure permissions on that entire folder were correct:

chmod -R 755 /var/www/html

Doc's:

Setting up amazon ec2-instances

Connect to Amazon EC2 file directory using Filezilla and SFTP (Video)

Understanding and Using File Permissions

How to create a List with a dynamic object type

Just use dynamic as the argument:

var list = new List<dynamic>();

Order data frame rows according to vector with specific order

If you don't want to use any libraries and you have reoccurrences in your data, you can use which with sapply as well.

new_order <- sapply(target, function(x,df){which(df$name == x)}, df=df)
df        <- df[new_order,]

Index (zero based) must be greater than or equal to zero

In this line:

Aboutme.Text = String.Format("{2}", reader.GetString(0));

The token {2} is invalid because you only have one item in the parms. Use this instead:

Aboutme.Text = String.Format("{0}", reader.GetString(0));

Rails DateTime.now without Time

You can use just:

Date.current

How should I import data from CSV into a Postgres table using pgAdmin 3?

You may have a table called 'test'

COPY test(gid, "name", the_geom)
FROM '/home/data/sample.csv'
WITH DELIMITER ','
CSV HEADER

difference between variables inside and outside of __init__()

Variable set outside __init__ belong to the class. They're shared by all instances.

Variables created inside __init__ (and all other method functions) and prefaced with self. belong to the object instance.

C char* to int conversion

atoi can do that for you

Example:

char string[] = "1234";
int sum = atoi( string );
printf("Sum = %d\n", sum ); // Outputs: Sum = 1234

how to select rows based on distinct values of A COLUMN only

Try this - you need a CTE (Common Table Expression) that partitions (groups) your data by distinct e-mail address, and sorts each group by ID - smallest first. Then you just select the first entry for each group - that should give you what you're looking for:

;WITH DistinctMails AS
(
    SELECT ID, MailID, EMailAddress, NAME,
        ROW_NUMBER() OVER(PARTITION BY EMailAddress ORDER BY ID) AS 'RowNum'
    FROM dbo.YourMailTable
)
SELECT *
FROM DistinctMails
WHERE RowNum = 1

This works on SQL Server 2005 and newer (you didn't mention what version you're using...)

Overriding fields or properties in subclasses

You can go with option 3 if you modify your abstract base class to require the property value in the constructor, you won't miss any paths. I'd really consider this option.

abstract class Aunt
{
    protected int MyInt;
    protected Aunt(int myInt)
    {
        MyInt = myInt;
    }

}

Of course, you then still have the option of making the field private and then, depending on the need, exposing a protected or public property getter.

How do I use CREATE OR REPLACE?

Following script should do the trick on Oracle:

BEGIN
  EXECUTE IMMEDIATE 'drop TABLE tablename';
EXCEPTION
  WHEN OTHERS THEN
    IF sqlcode != -0942 THEN RAISE; 
    END IF;
END;

com.sun.jdi.InvocationException occurred invoking method

Removing hashCode() and equals() solved my issue. In my case, I used Apache's commons-lang hash code and equals builders for creating non-static classes manually, so the compiler didn't throw any exception. But at runtime it caused the invocation exception.

Can't connect to localhost on SQL Server Express 2012 / 2016

The problem for me was that I was not specifying .\. I was only specifying the name of the instance:

  • did not work: SQL2016
  • worked: .\SQL2016

Why is a primary-foreign key relation required when we can join without it?

A primary key is not required. A foreign key is not required either. You can construct a query joining two tables on any column you wish as long as the datatypes either match or are converted to match. No relationship needs to explicitly exist.

To do this you use an outer join:

select tablea.code, tablea.name, tableb.location from tablea left outer join 
tableb on tablea.code = tableb.code

join with out relation

SQL join

Trouble using ROW_NUMBER() OVER (PARTITION BY ...)

I would do something like this:

;WITH x 
 AS (SELECT *, 
            Row_number() 
              OVER( 
                partition BY employeeid 
                ORDER BY datestart) rn 
     FROM   employeehistory) 
SELECT * 
FROM   x x1 
   LEFT OUTER JOIN x x2 
                ON x1.rn = x2.rn + 1 

Or maybe it would be x2.rn - 1. You'll have to see. In any case, you get the idea. Once you have the table joined on itself, you can filter, group, sort, etc. to get what you need.

What is the difference between Dim, Global, Public, and Private as Modular Field Access Modifiers?

Dim and Private work the same, though the common convention is to use Private at the module level, and Dim at the Sub/Function level. Public and Global are nearly identical in their function, however Global can only be used in standard modules, whereas Public can be used in all contexts (modules, classes, controls, forms etc.) Global comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public.

What is the difference between tree depth and height?

The answer by Daniel A.A. Pelsmaeker and Yesh analogy is excellent. I would like to add a bit more from hackerrank tutorial. Hope it helps a bit too.

  • The depth(or level) of a node is its distance(i.e. no of edges) from tree's root node.
  • The height is number of edges between root node and furthest leaf.
  • height(node) = 1 + max(height(node.leftSubtree),height(node.rightSubtree)).
    Keep in mind the following points before reading the example ahead.
  • Any node has a height of 1.
  • Height of empty subtree is -1.
  • Height of single element tree or leaf node is 0.
    Example to calculate height of tree

Can I change a column from NOT NULL to NULL without dropping it?

For MYSQL

ALTER TABLE myTable MODIFY myColumn {DataType} NULL

Get URL query string parameters

Here is my function to rebuild parts of the REFERRER's query string.

If the calling page already had a query string in its own URL, and you must go back to that page and want to send back some, not all, of that $_GET vars (e.g. a page number).

Example: Referrer's query string was ?foo=1&bar=2&baz=3 calling refererQueryString( 'foo' , 'baz' ) returns foo=1&baz=3":

function refererQueryString(/* var args */) {

    //Return empty string if no referer or no $_GET vars in referer available:
    if (!isset($_SERVER['HTTP_REFERER']) ||
        empty( $_SERVER['HTTP_REFERER']) ||
        empty(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY ))) {

        return '';
    }

    //Get URL query of referer (something like "threadID=7&page=8")
    $refererQueryString = parse_url(urldecode($_SERVER['HTTP_REFERER']), PHP_URL_QUERY);

    //Which values do you want to extract? (You passed their names as variables.)
    $args = func_get_args();

    //Get '[key=name]' strings out of referer's URL:
    $pairs = explode('&',$refererQueryString);

    //String you will return later:
    $return = '';

    //Analyze retrieved strings and look for the ones of interest:
    foreach ($pairs as $pair) {
        $keyVal = explode('=',$pair);
        $key = &$keyVal[0];
        $val = urlencode($keyVal[1]);
        //If you passed the name as arg, attach current pair to return string:
        if(in_array($key,$args)) {
            $return .= '&'. $key . '=' .$val;
        }
    }

    //Here are your returned 'key=value' pairs glued together with "&":
    return ltrim($return,'&');
}

//If your referer was 'page.php?foo=1&bar=2&baz=3'
//and you want to header() back to 'page.php?foo=1&baz=3'
//(no 'bar', only foo and baz), then apply:

header('Location: page.php?'.refererQueryString('foo','baz'));

Can not change UILabel text color

UIColor's RGB components are scaled between 0 and 1, not up to 255.

Try

categoryTitle.textColor = [UIColor colorWithRed:(188/255.f) green:... blue:... alpha:1.0];

In Swift:

categoryTitle.textColor = UIColor(red: 188/255.0, green: ..., blue: ..., alpha: 1)

Convert String array to ArrayList

Using Collections#addAll()

String[] words = {"ace","boom","crew","dog","eon"};
List<String> arrayList = new ArrayList<>(); 
Collections.addAll(arrayList, words); 

Git pull - Please move or remove them before you can merge

Apparently the files were added in remote repository, no matter what was the content of .gitignore file in the origin.

As the files exist in the remote repository, git has to pull them to your local work tree as well and therefore complains that the files already exist.

.gitignore is used only for scanning for the newly added files, it doesn't have anything to do with the files which were already added.

So the solution is to remove the files in your work tree and pull the latest version. Or the long-term solution is to remove the files from the repository if they were added by mistake.

A simple example to remove files from the remote branch is to

$git checkout <brachWithFiles>
$git rm -r *.extension
$git commit -m "fixin...."
$git push

Then you can try the $git merge again

Pass data to layout that are common to all pages

Presumably, the primary use case for this is to get a base model to the view for all (or the majority of) controller actions.

Given that, I've used a combination of several of these answers, primary piggy backing on Colin Bacon's answer.

It is correct that this is still controller logic because we are populating a viewmodel to return to a view. Thus the correct place to put this is in the controller.

We want this to happen on all controllers because we use this for the layout page. I am using it for partial views that are rendered in the layout page.

We also still want the added benefit of a strongly typed ViewModel

Thus, I have created a BaseViewModel and BaseController. All ViewModels Controllers will inherit from BaseViewModel and BaseController respectively.

The code:

BaseController

public class BaseController : Controller
{
    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);

        var model = filterContext.Controller.ViewData.Model as BaseViewModel;

        model.AwesomeModelProperty = "Awesome Property Value";
        model.FooterModel = this.getFooterModel();
    }

    protected FooterModel getFooterModel()
    {
        FooterModel model = new FooterModel();
        model.FooterModelProperty = "OMG Becky!!! Another Awesome Property!";
    }
}

Note the use of OnActionExecuted as taken from this SO post

HomeController

public class HomeController : BaseController
{
    public ActionResult Index(string id)
    {
        HomeIndexModel model = new HomeIndexModel();

        // populate HomeIndexModel ...

        return View(model);
    }
}

BaseViewModel

public class BaseViewModel
{
    public string AwesomeModelProperty { get; set; }
    public FooterModel FooterModel { get; set; }
}

HomeViewModel

public class HomeIndexModel : BaseViewModel
{

    public string FirstName { get; set; }

    // other awesome properties
}

FooterModel

public class FooterModel
{
    public string FooterModelProperty { get; set; }
}

Layout.cshtml

@model WebSite.Models.BaseViewModel
<!DOCTYPE html>
<html>
<head>
    < ... meta tags and styles and whatnot ... >
</head>
<body>
    <header>
        @{ Html.RenderPartial("_Nav", Model.FooterModel.FooterModelProperty);}
    </header>

    <main>
        <div class="container">
            @RenderBody()
        </div>

        @{ Html.RenderPartial("_AnotherPartial", Model); }
        @{ Html.RenderPartial("_Contact"); }
    </main>

    <footer>
        @{ Html.RenderPartial("_Footer", Model.FooterModel); }
    </footer>

    < ... render scripts ... >

    @RenderSection("scripts", required: false)
</body>
</html>

_Nav.cshtml

@model string
<nav>
    <ul>
        <li>
            <a href="@Model" target="_blank">Mind Blown!</a>
        </li>
    </ul>
</nav>

Hopefully this helps.

how to achieve transfer file between client and server using java socket

Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.

http://www.rgagnon.com/javadetails/java-0542.html

Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.

package filesendtest;

import java.io.*;
import java.net.*;

class TCPServer {

    private final static String fileToSend = "C:\\test1.pdf";

    public static void main(String args[]) {

        while (true) {
            ServerSocket welcomeSocket = null;
            Socket connectionSocket = null;
            BufferedOutputStream outToClient = null;

            try {
                welcomeSocket = new ServerSocket(3248);
                connectionSocket = welcomeSocket.accept();
                outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
            } catch (IOException ex) {
                // Do exception handling
            }

            if (outToClient != null) {
                File myFile = new File( fileToSend );
                byte[] mybytearray = new byte[(int) myFile.length()];

                FileInputStream fis = null;

                try {
                    fis = new FileInputStream(myFile);
                } catch (FileNotFoundException ex) {
                    // Do exception handling
                }
                BufferedInputStream bis = new BufferedInputStream(fis);

                try {
                    bis.read(mybytearray, 0, mybytearray.length);
                    outToClient.write(mybytearray, 0, mybytearray.length);
                    outToClient.flush();
                    outToClient.close();
                    connectionSocket.close();

                    // File sent, exit the main method
                    return;
                } catch (IOException ex) {
                    // Do exception handling
                }
            }
        }
    }
}

package filesendtest;

import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;

class TCPClient {

    private final static String serverIP = "127.0.0.1";
    private final static int serverPort = 3248;
    private final static String fileOutput = "C:\\testout.pdf";

    public static void main(String args[]) {
        byte[] aByte = new byte[1];
        int bytesRead;

        Socket clientSocket = null;
        InputStream is = null;

        try {
            clientSocket = new Socket( serverIP , serverPort );
            is = clientSocket.getInputStream();
        } catch (IOException ex) {
            // Do exception handling
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        if (is != null) {

            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            try {
                fos = new FileOutputStream( fileOutput );
                bos = new BufferedOutputStream(fos);
                bytesRead = is.read(aByte, 0, aByte.length);

                do {
                        baos.write(aByte);
                        bytesRead = is.read(aByte);
                } while (bytesRead != -1);

                bos.write(baos.toByteArray());
                bos.flush();
                bos.close();
                clientSocket.close();
            } catch (IOException ex) {
                // Do exception handling
            }
        }
    }
}

Related

Byte array of unknown length in java

Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):

public static String md5String(File file) {
    try {
        InputStream fin = new FileInputStream(file);
        java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[1024];
        int read;
        do {
            read = fin.read(buffer);
            if (read > 0) {
                md5er.update(buffer, 0, read);
            }
        } while (read != -1);
        fin.close();
        byte[] digest = md5er.digest();
        if (digest == null) {
            return null;
        }
        String strDigest = "0x";
        for (int i = 0; i < digest.length; i++) {
            strDigest += Integer.toString((digest[i] & 0xff)
                    + 0x100, 16).substring(1).toUpperCase();
        }
        return strDigest;
    } catch (Exception e) {
        return null;
    }
}

What is the worst programming language you ever worked with?

I can't belive nobody has said this one:

LotusScript

I thinks is far worst than php at least.

Is not about the language itself which follows a syntax similar to Visual Basic, is the fact that it seem to have a lot of functions for extremely unuseful things that you will never (or one in a million times) use, but lack support for things you will use everyday.

I don't remember any concrete example but they were like:

"Ok, I have an event to check whether the mouse pointer is in the upper corner of the form and I don't have an double click event for the Form!!?? WTF??"

IOS - How to segue programmatically using swift

If your segue exists in the storyboard with a segue identifier between your two views, you can just call it programmatically using:

performSegue(withIdentifier: "mySegueID", sender: nil)

For older versions:

performSegueWithIdentifier("mySegueID", sender: nil)

You could also do:

presentViewController(nextViewController, animated: true, completion: nil)

Or if you are in a Navigation controller:

self.navigationController?.pushViewController(nextViewController, animated: true)

Query to get the names of all tables in SQL Server 2008 Database

another way, will also work on MySQL and PostgreSQL

select TABLE_NAME from INFORMATION_SCHEMA.TABLES
where TABLE_TYPE = 'BASE TABLE'

jQuery Datepicker onchange event issue

if you are using wdcalendar this going to help you

 $("#PatientBirthday").datepicker({ 
        picker: "<button class='calpick'></button>",
        onReturn:function(d){
          var today = new Date();
          var birthDate = d;
          var age = today.getFullYear() - birthDate.getFullYear();
          var m = today.getMonth() - birthDate.getMonth();
          if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
            age--;
          }

          $('#ageshow')[0].innerHTML="Age: "+age;
          $("#PatientBirthday").val((d.getMonth() + 1) + '/' + d.getDate() + '/' +  d.getFullYear());
        }
      }); 

the event onReturn works for me

hope this help

How to expand textarea width to 100% of parent (or how to expand any HTML element to 100% of parent width)?

The box model is something every web-developer should know about. working with percents for sizes and pixels for padding/margin just doesn't work. There always is a resolution at which it doesn't look good (e.g. giving a width of 90% and a padding/margin of 10px in a div with a width of under 100px).

Check this out (using micro.pravi's code): http://jsbin.com/umeduh/2

<div id="container">
    <div class="left">
        <div class="content">
            left
        </div>
    </div>
    <div class="right">
        <div class="content">
            right
            <textarea>Check me out!</textarea>
        </div>
    </div>
</div>

The <div class="content"> are there so you can use padding and margin without screwing up the floats.

this is the most important part of the CSS:

textarea {
    display: block;
    width: 100%;
    -webkit-box-sizing: border-box;
       -moz-box-sizing: border-box;
            box-sizing: border-box;
}

How to format numbers as currency string?

You can use Intl natively like this:

// value: 11.07

Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(value)

// result: R$ 11,07

documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl

hope this helps! ;)

Complexities of binary tree traversals

O(n),I would say . I am doing for a balanced tree,applicable for all the trees. Assuming that you use recursion,

T(n) = 2*T(n/2) + 1 ----------> (1)

T(n/2) for left sub-tree and T(n/2) for right sub-tree and '1' for verifying the base case.

On Simplifying (1) you can prove that the traversal(either inorder or preorder or post order) is of order O(n).

How to check whether dynamically attached event listener exists or not?

Here's a script I used to check for the existence of a dynamically attached event listener. I used jQuery to attach an event handler to an element, then trigger that event (in this case the 'click' event). This way I can retrieve and capture event properties that will only exist if the event handler is attached.

var eventHandlerType;

$('#contentDiv').on('click', clickEventHandler).triggerHandler('click');

function clickEventHandler(e) {
    eventHandlerType = e.type;
}

if (eventHandlerType === 'click') {
    console.log('EventHandler "click" has been applied');
}

Is there a stopwatch in Java?

Use System.currentTimeMillis() to get the start time and the end time and calculate the difference.

class TimeTest1 {
  public static void main(String[] args) {

    long startTime = System.currentTimeMillis();

    long total = 0;
    for (int i = 0; i < 10000000; i++) {
      total += i;
    }

    long stopTime = System.currentTimeMillis();
    long elapsedTime = stopTime - startTime;
    System.out.println(elapsedTime);
  }
} 

More info at this tutorial

Creating multiple log files of different content with log4j

Perhaps something like this?

<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
 <!-- general application log -->
 <appender name="MainLogFile" class="org.apache.log4j.FileAppender">
  <param name="File" value="server.log" />
  <param name="Threshold" value="INFO" />
  <layout class="org.apache.log4j.PatternLayout">
   <param name="ConversionPattern" value="%-5p %t [%-40.40c] %x - %m%n"/>
  </layout>
 </appender> 
 <!-- additional fooSystem logging -->
 <appender name="FooLogFile" class="org.apache.log4j.FileAppender">
  <param name="File" value="foo.log" />
  <layout class="org.apache.log4j.PatternLayout">
   <param name="ConversionPattern" value="%-5p %t [%-40.40c] %x - %m%n"/>
  </layout>
 </appender>
 <!-- foo logging -->
 <logger name="com.example.foo">
  <level value="DEBUG"/>
  <appender-ref ref="FooLogFile"/>
 </logger>
 <!-- default logging -->
 <root>
  <level value="INFO"/>
  <appender-ref ref="MainLogFile"/>
 </root>
</log4j:configuration>

Thus, all info messages are written to server.log; by contrast, foo.log contains only com.example.foo messages, including debug-level messages.

What use is find_package() if you need to specify CMAKE_MODULE_PATH anyway?

If you are running cmake to generate SomeLib yourself (say as part of a superbuild), consider using the User Package Registry. This requires no hard-coded paths and is cross-platform. On Windows (including mingw64) it works via the registry. If you examine how the list of installation prefixes is constructed by the CONFIG mode of the find_packages() command, you'll see that the User Package Registry is one of elements.

Brief how-to

Associate the targets of SomeLib that you need outside of that external project by adding them to an export set in the CMakeLists.txt files where they are created:

add_library(thingInSomeLib ...)
install(TARGETS thingInSomeLib Export SomeLib-export DESTINATION lib)

Create a XXXConfig.cmake file for SomeLib in its ${CMAKE_CURRENT_BUILD_DIR} and store this location in the User Package Registry by adding two calls to export() to the CMakeLists.txt associated with SomeLib:

export(EXPORT SomeLib-export NAMESPACE SomeLib:: FILE SomeLibConfig.cmake) # Create SomeLibConfig.cmake
export(PACKAGE SomeLib)                                                    # Store location of SomeLibConfig.cmake

Issue your find_package(SomeLib REQUIRED) commmand in the CMakeLists.txt file of the project that depends on SomeLib without the "non-cross-platform hard coded paths" tinkering with the CMAKE_MODULE_PATH.

When it might be the right approach

This approach is probably best suited for situations where you'll never use your software downstream of the build directory (e.g., you're cross-compiling and never install anything on your machine, or you're building the software just to run tests in the build directory), since it creates a link to a .cmake file in your "build" output, which may be temporary.

But if you're never actually installing SomeLib in your workflow, calling EXPORT(PACKAGE <name>) allows you to avoid the hard-coded path. And, of course, if you are installing SomeLib, you probably know your platform, CMAKE_MODULE_PATH, etc, so @user2288008's excellent answer will have you covered.

MySQL LEFT JOIN 3 tables

Select 
    p.Name,
    p.SS,
    f.fear
From
    Persons p
left join
        Person_Fear pf
    inner join
        Fears f
    on
        pf.fearID = f.fearID
 on
    p.personID = pf.PersonID

Setting default permissions for newly created files and sub-directories under a directory in Linux?

in your shell script (or .bashrc) you may use somthing like:

umask 022

umask is a command that determines the settings of a mask that controls how file permissions are set for newly created files.

LPCSTR, LPCTSTR and LPTSTR

To answer the first part of your question:

LPCSTR is a pointer to a const string (LP means Long Pointer)

LPCTSTR is a pointer to a const TCHAR string, (TCHAR being either a wide char or char depending on whether UNICODE is defined in your project)

LPTSTR is a pointer to a (non-const) TCHAR string

In practice when talking about these in the past, we've left out the "pointer to a" phrase for simplicity, but as mentioned by lightness-races-in-orbit they are all pointers.

This is a great codeproject article describing C++ strings (see 2/3 the way down for a chart comparing the different types)

GetType used in PowerShell, difference between variables

Select-Object creates a new psobject and copies the properties you requested to it. You can verify this with GetType():

PS > $a.GetType().fullname
System.DayOfWeek

PS > $b.GetType().fullname
System.Management.Automation.PSCustomObject

how to delete all cookies of my website in php

The provided Answers did not solve my problem,

It did not:

  1. Remove parent domain cookies (from a.b.c; remove b.c; cookies),
  2. Remove cookies from a higher path other then root.

My script does, see.

<?php function unset_cookie($name)
{
    $host = $_SERVER['HTTP_HOST'];
    $domain = explode(':', $host)[0];

    $uri = $_SERVER['REQUEST_URI'];
    $uri = rtrim(explode('?', $uri)[0], '/');

    if ($uri && !filter_var('file://' . $uri, FILTER_VALIDATE_URL)) {
        throw new Exception('invalid uri: ' . $uri);
    }

    $parts = explode('/', $uri);

    $cookiePath = '';
    foreach ($parts as $part) {
        $cookiePath = '/'.ltrim($cookiePath.'/'.$part, '//');

        setcookie($name, '', 1, $cookiePath);

        $_domain = $domain;
        do {
            setcookie($name, '', 1, $cookiePath, $_domain);
        } while (strpos($_domain, '.') !== false && $_domain = substr($_domain, 1 + strpos($_domain, '.')));
    }
}

It is not the most pretty/safe/optimal solution, so use this only if you do not known the cookie-path and/or cookie-domain's. Or use the idea in order to create your version.

Handling InterruptedException in Java

The correct default choice is add InterruptedException to your throws list. An Interrupt indicates that another thread wishes your thread to end. The reason for this request is not made evident and is entirely contextual, so if you don't have any additional knowledge you should assume it's just a friendly shutdown, and anything that avoids that shutdown is a non-friendly response.

Java will not randomly throw InterruptedException's, all advice will not affect your application but I have run into a case where developer's following the "swallow" strategy became very inconvenient. A team had developed a large set of tests and used Thread.Sleep a lot. Now we started to run the tests in our CI server, and sometimes due to defects in the code would get stuck into permanent waits. To make the situation worse, when attempting to cancel the CI job it never closed because the Thread.Interrupt that was intended to abort the test did not abort the job. We had to login to the box and manually kill the processes.

So long story short, if you simply throw the InterruptedException you are matching the default intent that your thread should end. If you can't add InterruptedException to your throw list, I'd wrap it in a RuntimeException.

There is a very rational argument to be made that InterruptedException should be a RuntimeException itself, since that would encourage a better "default" handling. It's not a RuntimeException only because the designers stuck to a categorical rule that a RuntimeException should represent an error in your code. Since an InterruptedException does not arise directly from an error in your code, it's not. But the reality is that often an InterruptedException arises because there is an error in your code, (i.e. endless loop, dead-lock), and the Interrupt is some other thread's method for dealing with that error.

If you know there is rational cleanup to be done, then do it. If you know a deeper cause for the Interrupt, you can take on more comprehensive handling.

So in summary your choices for handling should follow this list:

  1. By default, add to throws.
  2. If not allowed to add to throws, throw RuntimeException(e). (Best choice of multiple bad options)
  3. Only when you know an explicit cause of the Interrupt, handle as desired. If your handling is local to your method, then reset interrupted by a call to Thread.currentThread().interrupt().

Set a default font for whole iOS app?

I created my own conversion of typography for Swift 4 after reviewing a few posts, it covers most of the cases, such as:

1st Add fonts to project estructure and to .plist file (with the same name):

<key>UIAppFonts</key>
<array>
    <string>Typo-Light.ttf</string>
    <string>Typo-Regular.ttf</string>
    <string>Typo-Semibold.ttf</string>
    <string>Typo-LightItalic.ttf</string>
</array>

Then

struct Resources {

    struct Fonts {
        //struct is extended in Fonts
    }
}

extension Resources.Fonts {

    enum Weight: String {
        case light = "Typo-Light"
        case regular = "Typo-Regular"
        case semibold = "Typo-Semibold"
        case italic = "Typo-LightItalic"
    }
}

extension UIFontDescriptor.AttributeName {
    static let nsctFontUIUsage = UIFontDescriptor.AttributeName(rawValue: "NSCTFontUIUsageAttribute")
}

extension UIFont {

    @objc class func mySystemFont(ofSize: CGFloat, weight: UIFont.Weight) -> UIFont {
        switch weight {
        case .semibold, .bold, .heavy, .black:
            return UIFont(name: Resources.Fonts.Weight.semibold.rawValue, size: ofSize)!

        case .medium, .regular:
            return UIFont(name: Resources.Fonts.Weight.regular.rawValue, size: ofSize)!

        default:
            return UIFont(name: Resources.Fonts.Weight.light.rawValue, size: ofSize)!
        }
    }

    @objc class func mySystemFont(ofSize size: CGFloat) -> UIFont {
        return UIFont(name: Resources.Fonts.Weight.light.rawValue, size: size)!
    }

    @objc class func myBoldSystemFont(ofSize size: CGFloat) -> UIFont {
        return UIFont(name: Resources.Fonts.Weight.semibold.rawValue, size: size)!
    }

    @objc class func myItalicSystemFont(ofSize size: CGFloat) -> UIFont {
        return UIFont(name: Resources.Fonts.Weight.italic.rawValue, size: size)!
    }

    @objc convenience init(myCoder aDecoder: NSCoder) {
        guard
            let fontDescriptor = aDecoder.decodeObject(forKey: "UIFontDescriptor") as? UIFontDescriptor,
            let fontAttribute = fontDescriptor.fontAttributes[.nsctFontUIUsage] as? String else {
                self.init(myCoder: aDecoder)
                return
        }
        var fontName = ""
        switch fontAttribute {
        case "CTFontRegularUsage", "CTFontMediumUsage":
            fontName = Resources.Fonts.Weight.regular.rawValue
        case "CTFontEmphasizedUsage", "CTFontBoldUsage", "CTFontSemiboldUsage","CTFontHeavyUsage", "CTFontBlackUsage":
            fontName = Resources.Fonts.Weight.semibold.rawValue
        case "CTFontObliqueUsage":
            fontName = Resources.Fonts.Weight.italic.rawValue
        default:
            fontName = Resources.Fonts.Weight.light.rawValue
        }
        self.init(name: fontName, size: fontDescriptor.pointSize)!
    }

    class func overrideDefaultTypography() {
        guard self == UIFont.self else { return }

        if let systemFontMethodWithWeight = class_getClassMethod(self, #selector(systemFont(ofSize: weight:))),
            let mySystemFontMethodWithWeight = class_getClassMethod(self, #selector(mySystemFont(ofSize: weight:))) {
            method_exchangeImplementations(systemFontMethodWithWeight, mySystemFontMethodWithWeight)
        }

        if let systemFontMethod = class_getClassMethod(self, #selector(systemFont(ofSize:))),
            let mySystemFontMethod = class_getClassMethod(self, #selector(mySystemFont(ofSize:))) {
            method_exchangeImplementations(systemFontMethod, mySystemFontMethod)
        }

        if let boldSystemFontMethod = class_getClassMethod(self, #selector(boldSystemFont(ofSize:))),
            let myBoldSystemFontMethod = class_getClassMethod(self, #selector(myBoldSystemFont(ofSize:))) {
            method_exchangeImplementations(boldSystemFontMethod, myBoldSystemFontMethod)
        }

        if let italicSystemFontMethod = class_getClassMethod(self, #selector(italicSystemFont(ofSize:))),
            let myItalicSystemFontMethod = class_getClassMethod(self, #selector(myItalicSystemFont(ofSize:))) {
            method_exchangeImplementations(italicSystemFontMethod, myItalicSystemFontMethod)
        }

        if let initCoderMethod = class_getInstanceMethod(self, #selector(UIFontDescriptor.init(coder:))),
            let myInitCoderMethod = class_getInstanceMethod(self, #selector(UIFont.init(myCoder:))) {
            method_exchangeImplementations(initCoderMethod, myInitCoderMethod)
        }
    }
}

Finally call to created method at Appdelegate like next:

class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {

        UIFont.overrideDefaultTypography()
        return true
    }
}

Select data from "show tables" MySQL query

To count:

SELECT COUNT(*) as total FROM (SELECT TABLE_NAME as tab, TABLES.* FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='database_name' GROUP BY tab) tables;

To list:

SELECT TABLE_NAME as table, TABLES.* FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='database_name' GROUP BY table;

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

These lines in your makefile,

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

and this line in your .cpp file,

#include "StdCUtil/split.h"

are in conflict.

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

Another option:

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

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

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

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

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

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

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


all: $(OBJS)

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

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

Submit form with Enter key without submit button?

$("input").keypress(function(event) {
    if (event.which == 13) {
        event.preventDefault();
        $("form").submit();
    }
});

Center HTML Input Text Field Placeholder

You can try like this :

input[placeholder] {
   text-align: center;
}

numpy array TypeError: only integer scalar arrays can be converted to a scalar index

You can use numpy.ravel to return a flattened array from n-dimensional array:

>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> a.ravel()
array([0, 1, 2, 3, 4, 5, 6, 7, 8])

How do you easily create empty matrices javascript?

var matrix = [];
for(var i=0; i<9; i++) {
    matrix[i] = new Array(9);
}

... or:

var matrix = [];
for(var i=0; i<9; i++) {
    matrix[i] = [];
    for(var j=0; j<9; j++) {
        matrix[i][j] = undefined;
    }
}

:touch CSS pseudo-class or something similar?

Since mobile doesn't give hover feedback, I want, as a user, to see instant feedback when a link is tapped. I noticed that -webkit-tap-highlight-color is the fastest to respond (subjective).

Add the following to your body and your links will have a tap effect.

body {
    -webkit-tap-highlight-color: #ccc;
}

Changing the action of a form with JavaScript/jQuery

just to add a detail to what Tamlyn wrote, instead of
$('form').get(0).setAttribute('action', 'baz'); //this works

$('form')[0].setAttribute('action', 'baz');
works equally well

ASP.NET MVC: No parameterless constructor defined for this object

By default, MVC Controllers require a default constructor with no parameters. The simplest would be to make a default constructor that calls the one with parameters:

public MyController() : this(new Helper()) {
}

public MyController(IHelper helper) {
  this.helper = helper;
}

However, you can override this functionality by rolling your own ControllerFactory. This way you can tell MVC that when you are creating a MyController give it an instance of Helper.

This allows you to use Dependency Injection frameworks with MVC, and really decouple everything. A good example of this is over at the StructureMap website. The whole quickstart is good, and he gets specific to MVC towards the bottom at "Auto Wiring".

How can I load webpage content into a div on page load?

With jQuery, it is possible, however not using ajax.

function LoadPage(){
  $.get('http://a_site.com/a_page.html', function(data) {
    $('#siteloader').html(data);
  });
}

And then place onload="LoadPage()" in the body tag.

Although if you follow this route, a php version might be better:

echo htmlspecialchars(file_get_contents("some URL"));

Syntax error due to using a reserved word as a table or column name in MySQL

The Problem

In MySQL, certain words like SELECT, INSERT, DELETE etc. are reserved words. Since they have a special meaning, MySQL treats it as a syntax error whenever you use them as a table name, column name, or other kind of identifier - unless you surround the identifier with backticks.

As noted in the official docs, in section 10.2 Schema Object Names (emphasis added):

Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.

...

If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.

...

The identifier quote character is the backtick ("`"):

A complete list of keywords and reserved words can be found in section 10.3 Keywords and Reserved Words. In that page, words followed by "(R)" are reserved words. Some reserved words are listed below, including many that tend to cause this issue.

  • ADD
  • AND
  • BEFORE
  • BY
  • CALL
  • CASE
  • CONDITION
  • DELETE
  • DESC
  • DESCRIBE
  • FROM
  • GROUP
  • IN
  • INDEX
  • INSERT
  • INTERVAL
  • IS
  • KEY
  • LIKE
  • LIMIT
  • LONG
  • MATCH
  • NOT
  • OPTION
  • OR
  • ORDER
  • PARTITION
  • RANK
  • REFERENCES
  • SELECT
  • TABLE
  • TO
  • UPDATE
  • WHERE

The Solution

You have two options.

1. Don't use reserved words as identifiers

The simplest solution is simply to avoid using reserved words as identifiers. You can probably find another reasonable name for your column that is not a reserved word.

Doing this has a couple of advantages:

  • It eliminates the possibility that you or another developer using your database will accidentally write a syntax error due to forgetting - or not knowing - that a particular identifier is a reserved word. There are many reserved words in MySQL and most developers are unlikely to know all of them. By not using these words in the first place, you avoid leaving traps for yourself or future developers.

  • The means of quoting identifiers differs between SQL dialects. While MySQL uses backticks for quoting identifiers by default, ANSI-compliant SQL (and indeed MySQL in ANSI SQL mode, as noted here) uses double quotes for quoting identifiers. As such, queries that quote identifiers with backticks are less easily portable to other SQL dialects.

Purely for the sake of reducing the risk of future mistakes, this is usually a wiser course of action than backtick-quoting the identifier.

2. Use backticks

If renaming the table or column isn't possible, wrap the offending identifier in backticks (`) as described in the earlier quote from 10.2 Schema Object Names.

An example to demonstrate the usage (taken from 10.3 Keywords and Reserved Words):

mysql> CREATE TABLE interval (begin INT, end INT);
ERROR 1064 (42000): You have an error in your SQL syntax.
near 'interval (begin INT, end INT)'

mysql> CREATE TABLE `interval` (begin INT, end INT); Query OK, 0 rows affected (0.01 sec)

Similarly, the query from the question can be fixed by wrapping the keyword key in backticks, as shown below:

INSERT INTO user_details (username, location, `key`)
VALUES ('Tim', 'Florida', 42)";               ^   ^

How to connect Bitbucket to Jenkins properly

I had this problem and it turned out the issue was that I had named my repository with CamelCase. Bitbucket automatically changes the URL of your repository to be all lower case and that gets sent to Jenkins in the webhook. Jenkins then searches for projects with a matching repository. If you, like me, have CamelCase in your repository URL in your project configuration you will be able to check out code, but the pattern matching on the webhook request will fail.

Just change your repo URL to be all lower case instead of CamelCase and the pattern match should find your project.

Invoke(Delegate)

If you want to modify a control it must be done in the thread in which the control was created. This Invoke method allows you to execute methods in the associated thread (the thread that owns the control's underlying window handle).

In below sample thread1 throws an exception because SetText1 is trying to modify textBox1.Text from another thread. But in thread2, Action in SetText2 is executed in the thread in which the TextBox was created

private void btn_Click(object sender, EvenetArgs e)
{
    var thread1 = new Thread(SetText1);
    var thread2 = new Thread(SetText2);
    thread1.Start();
    thread2.Start();
}

private void SetText1() 
{
    textBox1.Text = "Test";
}

private void SetText2() 
{
    textBox1.Invoke(new Action(() => textBox1.Text = "Test"));
}

How to copy and paste code without rich text formatting?

I have Far.exe as the first item in the start menu.

Richtext in the clipboard ->

ctrl-escape,arrdown,enter,shift-f4,$,enter
shift-insert,ctrl-insert,alt-backspace,
f10,enter

-> plaintext in the clipboard

Pros: no mouse, just blind typing, ends exactly where i was before

Cons: ANSI encoding - international symbols are lost

Luckily, I do not have to do that too often :)

A simple explanation of Naive Bayes Classification

I realize that this is an old question, with an established answer. The reason I'm posting is that is the accepted answer has many elements of k-NN (k-nearest neighbors), a different algorithm.

Both k-NN and NaiveBayes are classification algorithms. Conceptually, k-NN uses the idea of "nearness" to classify new entities. In k-NN 'nearness' is modeled with ideas such as Euclidean Distance or Cosine Distance. By contrast, in NaiveBayes, the concept of 'probability' is used to classify new entities.

Since the question is about Naive Bayes, here's how I'd describe the ideas and steps to someone. I'll try to do it with as few equations and in plain English as much as possible.

First, Conditional Probability & Bayes' Rule

Before someone can understand and appreciate the nuances of Naive Bayes', they need to know a couple of related concepts first, namely, the idea of Conditional Probability, and Bayes' Rule. (If you are familiar with these concepts, skip to the section titled Getting to Naive Bayes')

Conditional Probability in plain English: What is the probability that something will happen, given that something else has already happened.

Let's say that there is some Outcome O. And some Evidence E. From the way these probabilities are defined: The Probability of having both the Outcome O and Evidence E is: (Probability of O occurring) multiplied by the (Prob of E given that O happened)

One Example to understand Conditional Probability:

Let say we have a collection of US Senators. Senators could be Democrats or Republicans. They are also either male or female.

If we select one senator completely randomly, what is the probability that this person is a female Democrat? Conditional Probability can help us answer that.

Probability of (Democrat and Female Senator)= Prob(Senator is Democrat) multiplied by Conditional Probability of Being Female given that they are a Democrat.

  P(Democrat & Female) = P(Democrat) * P(Female | Democrat) 

We could compute the exact same thing, the reverse way:

  P(Democrat & Female) = P(Female) * P(Democrat | Female) 

Understanding Bayes Rule

Conceptually, this is a way to go from P(Evidence| Known Outcome) to P(Outcome|Known Evidence). Often, we know how frequently some particular evidence is observed, given a known outcome. We have to use this known fact to compute the reverse, to compute the chance of that outcome happening, given the evidence.

P(Outcome given that we know some Evidence) = P(Evidence given that we know the Outcome) times Prob(Outcome), scaled by the P(Evidence)

The classic example to understand Bayes' Rule:

Probability of Disease D given Test-positive = 

               P(Test is positive|Disease) * P(Disease)
     _______________________________________________________________
     (scaled by) P(Testing Positive, with or without the disease)

Now, all this was just preamble, to get to Naive Bayes.

Getting to Naive Bayes'

So far, we have talked only about one piece of evidence. In reality, we have to predict an outcome given multiple evidence. In that case, the math gets very complicated. To get around that complication, one approach is to 'uncouple' multiple pieces of evidence, and to treat each of piece of evidence as independent. This approach is why this is called naive Bayes.

P(Outcome|Multiple Evidence) = 
P(Evidence1|Outcome) * P(Evidence2|outcome) * ... * P(EvidenceN|outcome) * P(Outcome)
scaled by P(Multiple Evidence)

Many people choose to remember this as:

                      P(Likelihood of Evidence) * Prior prob of outcome
P(outcome|evidence) = _________________________________________________
                                         P(Evidence)

Notice a few things about this equation:

  • If the Prob(evidence|outcome) is 1, then we are just multiplying by 1.
  • If the Prob(some particular evidence|outcome) is 0, then the whole prob. becomes 0. If you see contradicting evidence, we can rule out that outcome.
  • Since we divide everything by P(Evidence), we can even get away without calculating it.
  • The intuition behind multiplying by the prior is so that we give high probability to more common outcomes, and low probabilities to unlikely outcomes. These are also called base rates and they are a way to scale our predicted probabilities.

How to Apply NaiveBayes to Predict an Outcome?

Just run the formula above for each possible outcome. Since we are trying to classify, each outcome is called a class and it has a class label. Our job is to look at the evidence, to consider how likely it is to be this class or that class, and assign a label to each entity. Again, we take a very simple approach: The class that has the highest probability is declared the "winner" and that class label gets assigned to that combination of evidences.

Fruit Example

Let's try it out on an example to increase our understanding: The OP asked for a 'fruit' identification example.

Let's say that we have data on 1000 pieces of fruit. They happen to be Banana, Orange or some Other Fruit. We know 3 characteristics about each fruit:

  1. Whether it is Long
  2. Whether it is Sweet and
  3. If its color is Yellow.

This is our 'training set.' We will use this to predict the type of any new fruit we encounter.

Type           Long | Not Long || Sweet | Not Sweet || Yellow |Not Yellow|Total
             ___________________________________________________________________
Banana      |  400  |    100   || 350   |    150    ||  450   |  50      |  500
Orange      |    0  |    300   || 150   |    150    ||  300   |   0      |  300
Other Fruit |  100  |    100   || 150   |     50    ||   50   | 150      |  200
            ____________________________________________________________________
Total       |  500  |    500   || 650   |    350    ||  800   | 200      | 1000
             ___________________________________________________________________

We can pre-compute a lot of things about our fruit collection.

The so-called "Prior" probabilities. (If we didn't know any of the fruit attributes, this would be our guess.) These are our base rates.

 P(Banana)      = 0.5 (500/1000)
 P(Orange)      = 0.3
 P(Other Fruit) = 0.2

Probability of "Evidence"

p(Long)   = 0.5
P(Sweet)  = 0.65
P(Yellow) = 0.8

Probability of "Likelihood"

P(Long|Banana) = 0.8
P(Long|Orange) = 0  [Oranges are never long in all the fruit we have seen.]
 ....

P(Yellow|Other Fruit)     =  50/200 = 0.25
P(Not Yellow|Other Fruit) = 0.75

Given a Fruit, how to classify it?

Let's say that we are given the properties of an unknown fruit, and asked to classify it. We are told that the fruit is Long, Sweet and Yellow. Is it a Banana? Is it an Orange? Or Is it some Other Fruit?

We can simply run the numbers for each of the 3 outcomes, one by one. Then we choose the highest probability and 'classify' our unknown fruit as belonging to the class that had the highest probability based on our prior evidence (our 1000 fruit training set):

P(Banana|Long, Sweet and Yellow) 
      P(Long|Banana) * P(Sweet|Banana) * P(Yellow|Banana) * P(banana)
    = _______________________________________________________________
                      P(Long) * P(Sweet) * P(Yellow)
                      
    = 0.8 * 0.7 * 0.9 * 0.5 / P(evidence)

    = 0.252 / P(evidence)


P(Orange|Long, Sweet and Yellow) = 0


P(Other Fruit|Long, Sweet and Yellow)
      P(Long|Other fruit) * P(Sweet|Other fruit) * P(Yellow|Other fruit) * P(Other Fruit)
    = ____________________________________________________________________________________
                                          P(evidence)

    = (100/200 * 150/200 * 50/200 * 200/1000) / P(evidence)

    = 0.01875 / P(evidence)

By an overwhelming margin (0.252 >> 0.01875), we classify this Sweet/Long/Yellow fruit as likely to be a Banana.

Why is Bayes Classifier so popular?

Look at what it eventually comes down to. Just some counting and multiplication. We can pre-compute all these terms, and so classifying becomes easy, quick and efficient.

Let z = 1 / P(evidence). Now we quickly compute the following three quantities.

P(Banana|evidence) = z * Prob(Banana) * Prob(Evidence1|Banana) * Prob(Evidence2|Banana) ...
P(Orange|Evidence) = z * Prob(Orange) * Prob(Evidence1|Orange) * Prob(Evidence2|Orange) ...
P(Other|Evidence)  = z * Prob(Other)  * Prob(Evidence1|Other)  * Prob(Evidence2|Other)  ...

Assign the class label of whichever is the highest number, and you are done.

Despite the name, Naive Bayes turns out to be excellent in certain applications. Text classification is one area where it really shines.

Hope that helps in understanding the concepts behind the Naive Bayes algorithm.

Getting request payload from POST request in Java servlet

Simple answer:
Use getReader() to read the body of the request

More info:
There are two methods for reading the data in the body:

  1. getReader() returns a BufferedReader that will allow you to read the body of the request.

  2. getInputStream() returns a ServletInputStream if you need to read binary data.

Note from the docs: "[Either method] may be called to read the body, not both."

How to change value of object which is inside an array using JavaScript or jQuery?

you can use .find so in your example

   var projects = [
            {
                value: "jquery",
                label: "jQuery",
                desc: "the write less, do more, JavaScript library",
                icon: "jquery_32x32.png"
            },
            {
                value: "jquery-ui",
                label: "jQuery UI",
                desc: "the official user interface library for jQuery",
                icon: "jqueryui_32x32.png"
            },
            {
                value: "sizzlejs",
                label: "Sizzle JS",
                desc: "a pure-JavaScript CSS selector engine",
                icon: "sizzlejs_32x32.png"
            }
        ];

let project = projects.find((p) => {
    return p.value === 'jquery-ui';
});

project.desc = 'your value'

Setting log level of message at runtime in slf4j

The method I use is to import the ch.qos.logback modules and then type-cast the slf4j Logger instance to a ch.qos.logback.classic.Logger. This instance includes a setLevel() method.

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;

Logger levelSet = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);

// Now you can set the desired logging-level
levelSet.setLevel( Level.OFF );

To find out the possible Logging-levels, you can explode the ch.qos.logback class to see all the possible values for Level:

prompt$ javap -cp logback-classic-1.2.3.jar ch.qos.logback.classic.Level

The results are the following:

{
   // ...skipping
   public static final ch.qos.logback.classic.Level OFF;
   public static final ch.qos.logback.classic.Level ERROR;
   public static final ch.qos.logback.classic.Level WARN;
   public static final ch.qos.logback.classic.Level INFO;
   public static final ch.qos.logback.classic.Level DEBUG;
   public static final ch.qos.logback.classic.Level TRACE;
   public static final ch.qos.logback.classic.Level ALL;
}

URL.Action() including route values

outgoing url in mvc generated based on the current routing schema.

because your Information action method require id parameter, and your route collection has id of your current requested url(/Admin/Information/5), id parameter automatically gotten from existing route collection values.

to solve this problem you should use UrlParameter.Optional:

 <a href="@Url.Action("Information", "Admin", new { id = UrlParameter.Optional })">Add an Admin</a>

Stretch background image css?

You can't stretch a background image (until CSS 3).

You would have to use absolute positioning, so that you can put an image tag inside the cell and stretch it to cover the entire cell, then put the content on top of the image.

_x000D_
_x000D_
table {_x000D_
  width: 230px;_x000D_
}_x000D_
_x000D_
.style1 {_x000D_
  text-align: center;_x000D_
  height: 35px;_x000D_
}_x000D_
_x000D_
.bg {_x000D_
  position: relative;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.bg img {_x000D_
  display: block;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.bg .linkcontainer {_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
  overflow: hidden;_x000D_
  width: 100%;_x000D_
}
_x000D_
<table cellpadding="0" cellspacing="0" border="10">_x000D_
  <tr>_x000D_
    <td class="style1">_x000D_
      <div class="bg">_x000D_
        <img src="http://placekitten.com/20/20" alt="" />_x000D_
        <div class="linkcontainer">_x000D_
          <a class="link" href="#">_x000D_
            <span>Answer</span>_x000D_
          </a>_x000D_
        </div>_x000D_
      </div>_x000D_
    </td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Transparent background on winforms?

I tried almost all of this. but still couldn't work. Finally I found it was because of 24bitmap problems. If you tried some bitmap which less than 24bit. Most of those above methods should work.

How to set a JavaScript breakpoint from code in Chrome?

There are many ways to debug JavaScript code. Following two approaches are widely used to debug JavaScript via code

  1. Using console.log() to print out the values in the browser console. (This will help you understand the values at certain points of your code)

  2. Debugger keyword. Add debugger; to the locations you want to debug, and open the browser's developer console and navigate to the sources tab.

For more tools and ways in which you debug JavaScript Code, are given in this link by W3School.

Creating a constant Dictionary in C#

Why not:

public class MyClass
{
    private Dictionary<string, int> _myCollection = new Dictionary<string, int>() { { "A", 1 }, { "B", 2 }, { "C", 3 } };

    public IEnumerable<KeyValuePair<string,int>> MyCollection
    {
        get { return _myCollection.AsEnumerable<KeyValuePair<string, int>>(); }
    }
}

cannot call member function without object

You need to instantiate an object in order to call its member functions. The member functions need an object to operate on; they can't just be used on their own. The main() function could, for example, look like this:

int main()
{
   Name_pairs np;
   cout << "Enter names and ages. Use 0 to cancel.\n";
   while(np.test())
   {
      np.read_names();
      np.read_ages();
   }
   np.print();
   keep_window_open();
}

When should I use Memcache instead of Memcached?

This is 2013. Forget about the 2009 comments. Likewise, if you are running serious traffic loads, do not even contemplate how to make-do with a windows based memcache. When dealing with a very large scale (500+ front end web servers) and 20+ back end database servers and replicants (mysql & mssql mix), a farm of memcached servers (12 servers in group) supports multiple high volume OLTP applications answering 25K ~ 40K mc->get calls per-second. These calls are those that do NOT have to reach a database.

IMHO, this use of memcached provided SERIOUS $$$,$$$savings on CAPEX for new DB servers & licences as well as on support contracts for large commercial designs.

jQuery UI 1.10: dialog and zIndex option

Add zIndex property to dialog object:

$(elm).dialog(
 zIndex: 10000
);

Restore a postgres backup file using the command line?

I didnt see here mentions about dump file extension (*.dump).

This solution worked for me:

I got a dump file and needed to recover it.

First I tried to do this with pg_restore and got:

pg_restore: error: input file appears to be a text format dump. Please use psql.

I did it with psql and worked well:

psql -U myUser-d myDataBase < path_to_the_file/file.dump

Git: Installing Git in PATH with GitHub client for Windows

I would like to add one more thing to what the other answers have said. It is not compulsory that path will be:

C:\Users\<user>\AppData\Local\GitHub\PortableGit_<guid>\bin\git.exe

In my computer I did not found Git there.

BUT git and cmd are located in

git.exe

C:\Program Files\Git\bin\git.exe

cmd

C:\Program Files\Git\cmd

To add into PATH:

  • Right-Click on My Computer
  • Click on Advanced System Settings
  • Click on Environment Variables
  • Then, under System Variables, look for the path variable and click edit
  • Add the path to git’s bin and cmd at the end of the string like this:

    ;C:\Program Files\Git\bin\git.exe;C:\Program Files\Git\cmd

OR

;C:\Users\<user>\AppData\Local\GitHub\PortableGit_<guid>\bin;C:\Users\<user>\AppData\Local\GitHub\PortableGit_<guid>\cmd

To verify, restart cmd and type git --version in cmd

How to obtain Signing certificate fingerprint (SHA1) for OAuth 2.0 on Android?

I know this question has been answered but this is how I found my signature for the default keystore. In Eclipse, if you go to Windows -> Preferences -> Android -> Build

enter image description here

How to access a dictionary key value present inside a list?

Index the list then the dict.

print L[1]['d']

Is it possible to have a HTML SELECT/OPTION value as NULL using PHP?

All you need is a check on the post side of things.

if(empty($_REQUEST['type_id']) && $_REQUEST['type_id'] != 0)
    $_REQUEST['type_id'] = null;

How to get the sign, mantissa and exponent of a floating point number

On Linux package glibc-headers provides header #include <ieee754.h> with floating point types definitions, e.g.:

union ieee754_double
  {
    double d;

    /* This is the IEEE 754 double-precision format.  */
    struct
      {
#if __BYTE_ORDER == __BIG_ENDIAN
    unsigned int negative:1;
    unsigned int exponent:11;
    /* Together these comprise the mantissa.  */
    unsigned int mantissa0:20;
    unsigned int mantissa1:32;
#endif              /* Big endian.  */
#if __BYTE_ORDER == __LITTLE_ENDIAN
# if    __FLOAT_WORD_ORDER == __BIG_ENDIAN
    unsigned int mantissa0:20;
    unsigned int exponent:11;
    unsigned int negative:1;
    unsigned int mantissa1:32;
# else
    /* Together these comprise the mantissa.  */
    unsigned int mantissa1:32;
    unsigned int mantissa0:20;
    unsigned int exponent:11;
    unsigned int negative:1;
# endif
#endif              /* Little endian.  */
      } ieee;

    /* This format makes it easier to see if a NaN is a signalling NaN.  */
    struct
      {
#if __BYTE_ORDER == __BIG_ENDIAN
    unsigned int negative:1;
    unsigned int exponent:11;
    unsigned int quiet_nan:1;
    /* Together these comprise the mantissa.  */
    unsigned int mantissa0:19;
    unsigned int mantissa1:32;
#else
# if    __FLOAT_WORD_ORDER == __BIG_ENDIAN
    unsigned int mantissa0:19;
    unsigned int quiet_nan:1;
    unsigned int exponent:11;
    unsigned int negative:1;
    unsigned int mantissa1:32;
# else
    /* Together these comprise the mantissa.  */
    unsigned int mantissa1:32;
    unsigned int mantissa0:19;
    unsigned int quiet_nan:1;
    unsigned int exponent:11;
    unsigned int negative:1;
# endif
#endif
      } ieee_nan;
  };

#define IEEE754_DOUBLE_BIAS 0x3ff /* Added to exponent.  */

curl: (6) Could not resolve host: application

In my case, I copied the curl command from Confluence to TextEdit. After spending almost an hour, and trying to paste the command in different text editors in order to sanitize, finally, PyCharm helped me (IntelliJ should help too)

After pasting it in PyCharm I got to see the error

Non-breaking spaces

After removing these "NBSP" (non-breaking spaces), the command started running fine.

How to close the command line window after running a batch file?

%Started Program or Command% | taskkill /F /IM cmd.exe

Example:

notepad.exe | taskkill /F /IM cmd.exe

I can't install python-ldap

To correct the error due to dependencies to install the python-ldap : Windows 7/10

download the whl file

http://www.lfd.uci.edu/~gohlke/pythonlibs/#python-ldap.

python 3.6 suit with

python_ldap-3.2.0-cp36-cp36m-win_amd64.whl

Deploy the file in :

c:\python36\Scripts\

install it with

python -m pip install python_ldap-3.2.0-cp36-cp36m-win_amd64.whl

WinForms DataGridView font size

1st Step: Go to the form where datagridview is added

2nd step: click on the datagridview at the top right side there will be displayed a small button of like play icon or arrow to edit the datagridview.

3rd step: click on that button and select edit columns now click the attributes you want to increase font size.

4th step: on the right side of the property menu the first on the list column named defaultcellstyle click on its property a new window will open to change the font and font size.

Git removing upstream from local repository

git remote manpage is pretty straightforward:

Use

Older (backwards-compatible) syntax:
$ git remote rm upstream
Newer syntax for newer git versions: (* see below)
$ git remote remove upstream

Then do:    
$ git remote add upstream https://github.com/Foo/repos.git

or just update the URL directly:

$ git remote set-url upstream https://github.com/Foo/repos.git

or if you are comfortable with it, just update the .git/config directly - you can probably figure out what you need to change (left as exercise for the reader).

...
[remote "upstream"]
    fetch = +refs/heads/*:refs/remotes/upstream/*
    url = https://github.com/foo/repos.git
...

===

* Regarding 'git remote rm' vs 'git remote remove' - this changed around git 1.7.10.3 / 1.7.12 2 - see

https://code.google.com/p/git-core/source/detail?spec=svne17dba8fe15028425acd6a4ebebf1b8e9377d3c6&r=e17dba8fe15028425acd6a4ebebf1b8e9377d3c6

Log message

remote: prefer subcommand name 'remove' to 'rm'

All remote subcommands are spelled out words except 'rm'. 'rm', being a
popular UNIX command name, may mislead users that there are also 'ls' or
'mv'. Use 'remove' to fit with the rest of subcommands.

'rm' is still supported and used in the test suite. It's just not
widely advertised.

What is the best way to compare floats for almost-equality in Python?

I liked @Sesquipedal 's suggestion but with modification (a special use case when both values are 0 returns False). In my case I was on Python 2.7 and just used a simple function:

if f1 ==0 and f2 == 0:
    return True
else:
    return abs(f1-f2) < tol*max(abs(f1),abs(f2))

How to unnest a nested list

itertools provides the chain function for that:

From http://docs.python.org/library/itertools.html#recipes:

def flatten(listOfLists):
    "Flatten one level of nesting"
    return chain.from_iterable(listOfLists)

Note that the result is an iterable, so you may need list(flatten(...)).

Why do we need to use flatMap?

['a','b','c'].flatMap(function(e) {
    return [e, e+ 'x', e+ 'y',  e+ 'z'  ];
});
//['a', 'ax', 'ay', 'az', 'b', 'bx', 'by', 'bz', 'c', 'cx', 'cy', 'cz']


['a','b','c'].map(function(e) {
    return [e, e+ 'x', e+ 'y',  e+ 'z'  ];
});
//[Array[4], Array[4], Array[4]]

You use flatMap when you have an Observable whose results are more Observables.

If you have an observable which is produced by an another observable you can not filter, reduce, or map it directly because you have an Observable not the data. If you produce an observable choose flatMap over map; then you are okay.

As in second snippet, if you are doing async operation you need to use flatMap.

_x000D_
_x000D_
var source = Rx.Observable.interval(100).take(10).map(function(num){_x000D_
    return num+1_x000D_
});_x000D_
source.subscribe(function(e){_x000D_
    console.log(e)_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.1/Rx.min.js"></script>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
var source = Rx.Observable.interval(100).take(10).flatMap(function(num){_x000D_
    return Rx.Observable.timer(100).map(() => num)_x000D_
});_x000D_
source.subscribe(function(e){_x000D_
    console.log(e)_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.1/Rx.min.js"></script>
_x000D_
_x000D_
_x000D_

How to get the real and total length of char * (char array)?

You can find the length of a char* string like this:

char* mystring = "Hello World";
int length = sprintf(mystring, "%s", mystring);

sprintf() prints mystring onto itself, and returns the number of characters printed.

Adding JPanel to JFrame

Test2 test = new Test2();
...
frame.add(test, BorderLayout.CENTER);

Are you sure of this? test is NOT a component! To do what you're trying to do you should let Test2 extend JPanel !

What is the color code for transparency in CSS?

jus add two zeroes (00) before your color code you will get the transparent of that color

javascript variable reference/alias

edit to my previous answer: if you want to count a function's invocations, you might want to try:

var countMe = ( function() {
  var c = 0;

  return function() {
    c++;
    return c;
  }
})();

alert(countMe()); // Alerts "1"
alert(countMe()); // Alerts "2"

Here, c serves as the counter, and you do not have to use arguments.callee.

Best database field type for a URL

VARCHAR(512) (or similar) should be sufficient. However, since you don't really know the maximum length of the URLs in question, I might just go direct to TEXT. The danger with this is of course loss of efficiency due to CLOBs being far slower than a simple string datatype like VARCHAR.

Call a function from another file?

If your file is in the different package structure and you want to call it from a different package, then you can call it in that fashion:

Let's say you have following package structure in your python project:

Python package and file structure

in - com.my.func.DifferentFunction python file you have some function, like:

def add(arg1, arg2):
    return arg1 + arg2

def sub(arg1, arg2) :
    return arg1 - arg2

def mul(arg1, arg2) :
    return arg1 * arg2

And you want to call different functions from Example3.py, then following way you can do it:

Define import statement in Example3.py - file for import all function

from com.my.func.DifferentFunction import *

or define each function name which you want to import

from com.my.func.DifferentFunction import add, sub, mul

Then in Example3.py you can call function for execute:

num1 = 20
num2 = 10

print("\n add : ", add(num1,num2))
print("\n sub : ", sub(num1,num2))
print("\n mul : ", mul(num1,num2))

Output:

 add :  30

 sub :  10

 mul :  200

How do I format a String in an email so Outlook will print the line breaks?

I have used html line break instead of "\n" . It worked fine.

Plotting 4 curves in a single plot, with 3 y-axes

Multi-scale plots are rare to find beyond two axes... Luckily in Matlab it is possible, but you have to fully overlap axes and play with tickmarks so as not to hide info.

Below is a nice working sample. I hope this is what you are looking for (although colors could be much nicer)!

close all
clear all 

display('Generating data');

x = 0:10;
y1 = rand(1,11);
y2 = 10.*rand(1,11);
y3 = 100.*rand(1,11);
y4 = 100.*rand(1,11);

display('Plotting');

figure;
ax1 = gca;
get(ax1,'Position')
set(ax1,'XColor','k',...
    'YColor','b',...
    'YLim',[0,1],...
    'YTick',[0, 0.2, 0.4, 0.6, 0.8, 1.0]);
line(x, y1, 'Color', 'b', 'LineStyle', '-', 'Marker', '.', 'Parent', ax1)

ax2 = axes('Position',get(ax1,'Position'),...
           'XAxisLocation','bottom',...
           'YAxisLocation','left',...
           'Color','none',...
           'XColor','k',...
           'YColor','r',...
           'YLim',[0,10],...
           'YTick',[1, 3, 5, 7, 9],...
           'XTick',[],'XTickLabel',[]);
line(x, y2, 'Color', 'r', 'LineStyle', '-', 'Marker', '.', 'Parent', ax2)

ax3 = axes('Position',get(ax1,'Position'),...
           'XAxisLocation','bottom',...
           'YAxisLocation','right',...
           'Color','none',...
           'XColor','k',...
           'YColor','g',...
           'YLim',[0,100],...
           'YTick',[0, 20, 40, 60, 80, 100],...
           'XTick',[],'XTickLabel',[]);
line(x, y3, 'Color', 'g', 'LineStyle', '-', 'Marker', '.', 'Parent', ax3)

ax4 = axes('Position',get(ax1,'Position'),...
           'XAxisLocation','bottom',...
           'YAxisLocation','right',...
           'Color','none',...
           'XColor','k',...
           'YColor','c',...
           'YLim',[0,100],...
           'YTick',[10, 30, 50, 70, 90],...
           'XTick',[],'XTickLabel',[]);
line(x, y4, 'Color', 'c', 'LineStyle', '-', 'Marker', '.', 'Parent', ax4)

alt text
(source: pablorodriguez.info)

Bootstrap 3 Gutter Size

You can keep the default behaviour (with gutter) and add a class to your CSS stylesheet for tasks like yours:

.no-gutter > [class*='col-'] {
    padding-right:0;
    padding-left:0;
}

And here’s how you can use it in your HTML:

<div class="row no-gutter">
    <div class="col-md-4">
        ...
    </div>
    <div class="col-md-4">
        ...
    </div>
    <div class="col-md-4">
        ...
    </div>
</div>

How to remove all callbacks from a Handler?

If you don't have the Runnable references, on the first callback, get the obj of the message, and use removeCallbacksAndMessages() to remove all related callbacks.

How do you convert a DataTable into a generic list?

Converting DataTable to Generic Dictionary

public static Dictionary<object,IList<dynamic>> DataTable2Dictionary(DataTable dt)
{
    Dictionary<object, IList<dynamic>> dict = new Dictionary<dynamic, IList<dynamic>>();

    foreach(DataColumn column in dt.Columns)
    {
        IList<dynamic> ts = dt.AsEnumerable()
                              .Select(r => r.Field<dynamic>(column.ToString()))
                              .ToList();
        dict.Add(column, ts);
    }
    return dict;
}

Apply a function to every row of a matrix or a data frame

Another approach if you want to use a varying portion of the dataset instead of a single value is to use rollapply(data, width, FUN, ...). Using a vector of widths allows you to apply a function on a varying window of the dataset. I've used this to build an adaptive filtering routine, though it isn't very efficient.

Create Test Class in IntelliJ

*IntelliJ 13 * (its paid for) We found you have to have the cursor in the actual class before ctrl+Shift+T worked.

Which seems a bit restrictive if its the only way to generate a test class. Although in retrospect it would force developers to create a test class when they write a functional class.

How can I get client information such as OS and browser

Here's my code that works, as of today, with some of the latest browsers.

Naturally, it will break as User-Agent's evolve, but it's simple, and easy to fix.

    String userAgent = "Unknown";
    String osType = "Unknown";
    String osVersion = "Unknown";
    String browserType = "Unknown";
    String browserVersion = "Unknown";
    String deviceType = "Unknown";

    try {
        userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36 OPR/60.0.3255.165";
        //userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0";
        //userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36";
        //userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134";
        //userAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 12_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.1 Mobile/15E148 Safari/604.1";
        boolean exceptionTest = false;
        if(exceptionTest) throw new Exception("EXCEPTION TEST");

        if (userAgent.indexOf("Windows NT") >= 0) {
            osType = "Windows";
            osVersion = userAgent.substring(userAgent.indexOf("Windows NT ")+11, userAgent.indexOf(";"));

        } else if (userAgent.indexOf("Mac OS") >= 0) {
            osType = "Mac";
            osVersion = userAgent.substring(userAgent.indexOf("Mac OS ")+7, userAgent.indexOf(")"));

            if(userAgent.indexOf("iPhone") >= 0) {
                deviceType = "iPhone";
            } else if(userAgent.indexOf("iPad") >= 0) {
                deviceType = "iPad";
            }

        } else if (userAgent.indexOf("X11") >= 0) {
            osType = "Unix";
            osVersion = "Unknown";

        } else if (userAgent.indexOf("android") >= 0) {
            osType = "Android";
            osVersion = "Unknown";
        }
        logger.trace("end of os section");

        if (userAgent.contains("Edge/")) {
            browserType = "Edge";
            browserVersion = userAgent.substring(userAgent.indexOf("Edge")).split("/")[1];

        } else if (userAgent.contains("Safari/") && userAgent.contains("Version/")) {
            browserType = "Safari";
            browserVersion = userAgent.substring(userAgent.indexOf("Version/")+8).split(" ")[0];

        } else if (userAgent.contains("OPR/") || userAgent.contains("Opera/")) {
            browserType = "Opera";
            browserVersion = userAgent.substring(userAgent.indexOf("OPR")).split("/")[1];

        } else if (userAgent.contains("Chrome/")) {
            browserType = "Chrome"; 
            browserVersion = userAgent.substring(userAgent.indexOf("Chrome")).split("/")[1];
            browserVersion = browserVersion.split(" ")[0];

        } else if (userAgent.contains("Firefox/")) {
            browserType = "Firefox"; 
            browserVersion = userAgent.substring(userAgent.indexOf("Firefox")).split("/")[1];
        }            
        logger.trace("end of browser section");

    } catch (Exception ex) {
        logger.error("ERROR: " +ex);            
    }

    logger.debug(
              "\n userAgent: " + userAgent
            + "\n osType: " + osType
            + "\n osVersion: " + osVersion
            + "\n browserType: " + browserType
            + "\n browserVersion: " + browserVersion
            + "\n deviceType: " + deviceType
            );

Logger Output:

 userAgent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36 OPR/60.0.3255.165
 osType: Windows
 osVersion: 10.0
 browserType: Opera
 browserVersion: 60.0.3255.165
 deviceType: Unknown

UTF-8 all the way through

I recently discovered that using strtolower() can cause issues where the data is truncated after a special character.

The solution was to use

mb_strtolower($string, 'UTF-8');

mb_ uses MultiByte. It supports more characters but in general is a little slower.

Can someone explain __all__ in Python?

This is defined in PEP8 here:

Global Variable Names

(Let's hope that these variables are meant for use inside one module only.) The conventions are about the same as those for functions.

Modules that are designed for use via from M import * should use the __all__ mechanism to prevent exporting globals, or use the older convention of prefixing such globals with an underscore (which you might want to do to indicate these globals are "module non-public").

PEP8 provides coding conventions for the Python code comprising the standard library in the main Python distribution. The more you follow this, closer you are to the original intent.

How to get the return value from a thread in python?

Taking into consideration @iman comment on @JakeBiesinger answer I have recomposed it to have various number of threads:

from multiprocessing.pool import ThreadPool

def foo(bar, baz):
    print 'hello {0}'.format(bar)
    return 'foo' + baz

numOfThreads = 3 
results = []

pool = ThreadPool(numOfThreads)

for i in range(0, numOfThreads):
    results.append(pool.apply_async(foo, ('world', 'foo'))) # tuple of args for foo)

# do some other stuff in the main process
# ...
# ...

results = [r.get() for r in results]
print results

pool.close()
pool.join()

Cheers,

Guy.

SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed

Remove or comment out the line-

$mail->IsSMTP();

And it will work for you.

I have checked and experimented many answers from different sites but haven't got any solution except the above solution.

How can strings be concatenated?

Use + for string concatenation as:

section = 'C_type'
new_section = 'Sec_' + section

How to print in C

try this:

printf("%d", addNumber(a,b))

Here's the documentation for printf.

How can I get relative path of the folders in my android project?

Generally we want to add images, txt, doc and etc files inside our Java project and specific folder such as /images. I found in search that in JAVA, we can get path from Root to folder which we specify as,

String myStorageFolder= "/images"; // this is folder name in where I want to store files.

String getImageFolderPath= request.getServletContext().getRealPath(myStorageFolder);

Here, request is object of HttpServletRequest. It will get the whole path from Root to /images folder. You will get output like,

C:\Users\STARK\Workspaces\MyEclipse.metadata.me_tcat7\webapps\JavaProject\images

Serializing PHP object to JSON

In the simplest cases type hinting should work:

$json = json_encode( (array)$object );

Command /Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 1

This happened to me and it took me an hour to find it. In my case I had typed too fast and did:

[seld method];

instead of:

[self method];

Seriously! I don't know why it didn't catch this in a more recognizable way. But it was of course looking for a class called "seld".

How to delete the first row of a dataframe in R?

You can use negative indexing to remove rows, e.g.:

dat <- dat[-1, ]

Here is an example:

> dat <- data.frame(A = 1:3, B = 1:3)
> dat[-1, ]
  A B
2 2 2
3 3 3
> dat2 <- dat[-1, ]
> dat2
  A B
2 2 2
3 3 3

That said, you may have more problems than just removing the labels that ended up on row 1. It is more then likely that R has interpreted the data as text and thence converted to factors. Check what str(foo), where foo is your data object, says about the data types.

It sounds like you just need header = TRUE in your call to read in the data (assuming you read it in via read.table() or one of it's wrappers.)

ComboBox: Adding Text and Value to an Item (no Binding Source)

You can use Dictionary Object instead of creating a custom class for adding text and value in a Combobox.

Add keys and values in a Dictionary Object:

Dictionary<string, string> comboSource = new Dictionary<string, string>();
comboSource.Add("1", "Sunday");
comboSource.Add("2", "Monday");

Bind the source Dictionary object to Combobox:

comboBox1.DataSource = new BindingSource(comboSource, null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";

Retrieve Key and value:

string key = ((KeyValuePair<string,string>)comboBox1.SelectedItem).Key;
string value = ((KeyValuePair<string,string>)comboBox1.SelectedItem).Value;

Full Source : Combobox Text nd Value

How to Resize a Bitmap in Android?

profileImage.setImageBitmap(
    Bitmap.createScaledBitmap(
        BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length), 
        80, 80, false
    )
);

Playing Sound In Hidden Tag

I hope people would allow them to turn things such as music off, as for button clicks, Sometimes, those are pretty cool. Use the

<audio controls autoplay hidden="hidden"> <source src="*file here*" type="*file extension (.mp3 .ogg etc.)*"> <!--This displays an error to users that don't have it supported--> Your browser does not support the audio element. </audio>

As you can see, I don't like to repeat myself much, But I decided with the hidden tag.

Hope this helps.

Maven and adding JARs to system scope

You will need to add the jar to your local maven repository. Alternatively (better option) specify the proper repository (if one exists) so it can be automatically downloaded by maven

In either case, remove the <systemPath> tag from the dependency

In Python, how do I read the exif data for an image?

I have found that using ._getexif doesn't work in higher python versions, moreover, it is a protected class and one should avoid using it if possible. After digging around the debugger this is what I found to be the best way to get the EXIF data for an image:

from PIL import Image

def get_exif(path):
    return Image.open(path).info['parsed_exif']

This returns a dictionary of all the EXIF data of an image.

Note: For Python3.x use Pillow instead of PIL

Using Google maps API v3 how do I get LatLng with a given address?

There is a pretty good example on https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple

To shorten it up a little:

geocoder = new google.maps.Geocoder();

function codeAddress() {

    //In this case it gets the address from an element on the page, but obviously you  could just pass it to the method instead
    var address = document.getElementById( 'address' ).value;

    geocoder.geocode( { 'address' : address }, function( results, status ) {
        if( status == google.maps.GeocoderStatus.OK ) {

            //In this case it creates a marker, but you can get the lat and lng from the location.LatLng
            map.setCenter( results[0].geometry.location );
            var marker = new google.maps.Marker( {
                map     : map,
                position: results[0].geometry.location
            } );
        } else {
            alert( 'Geocode was not successful for the following reason: ' + status );
        }
    } );
}

Xcode/Simulator: How to run older iOS version?

I was searching for how to do this on a much newer version of xcode than the original question and while the answers here got me where I needed to go, they aren't quite accurate for location anymore. Xcode 11.3.1, you need to go into Preferences -> Components, then select the desired Simulators. You can also select tvOS and watchOS similators from the same window.

Components preference window from Xcode 11.3.1

Leave only two decimal places after the dot

double doublVal = 123.45678;

There are two ways.

  1. for display in string:

    String.Format("{0:0.00}", doublVal );
    
  2. for geting again Double

    doublVal = Convert.ToDouble(String.Format("{0:0.00}", doublVal ));
    

Disable webkit's spin buttons on input type="number"?

You can also hide spinner with following trick :

input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
  opacity:0;
  pointer-events:none;
}

How to replace multiple strings in a file using PowerShell

A third option, for a pipelined one-liner is to nest the -replaces:

PS> ("ABC" -replace "B","C") -replace "C","D"
ADD

And:

PS> ("ABC" -replace "C","D") -replace "B","C"
ACD

This preserves execution order, is easy to read, and fits neatly into a pipeline. I prefer to use parentheses for explicit control, self-documentation, etc. It works without them, but how far do you trust that?

-Replace is a Comparison Operator, which accepts an object and returns a presumably modified object. This is why you can stack or nest them as shown above.

Please see:

help about_operators

SQL: ... WHERE X IN (SELECT Y FROM ...)

SELECT Customers.* 
  FROM Customers 
 WHERE NOT EXISTS (
       SELECT *
         FROM SUBSCRIBERS AS s
         JOIN s.Cust_ID = Customers.Customer_ID) 

When using “NOT IN”, the query performs nested full table scans, whereas for “NOT EXISTS”, the query can use an index within the sub-query.

How to make circular background using css?

Keep it simple:

.circle
  {
    border-radius: 50%;
    width: 200px;
    height: 200px; 
  }

Width and height can be anything, as long as they're equal

ASP.NET MVC - Extract parameter of an URL

Update

RouteData.Values["id"] + Request.Url.Query

Will match all your examples


It is not entirely clear what you are trying to achieve. MVC passes URL parameters for you through model binding.

public class CustomerController : Controller {

  public ActionResult Edit(int id) {

    int customerId = id //the id in the URL

    return View();
  }

}


public class ProductController : Controller {

  public ActionResult Edit(int id, bool allowed) { 

    int productId = id; // the id in the URL
    bool isAllowed = allowed  // the ?allowed=true in the URL

    return View();
  }

}

Adding a route mapping to your global.asax.cs file before the default will handle the /administration/ part. Or you might want to look into MVC Areas.

routes.MapRoute(
  "Admin", // Route name
  "Administration/{controller}/{action}/{id}", // URL with parameters
  new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults

If it's the raw URL data you are after then you can use one of the various URL and Request properties available in your controller action

string url = Request.RawUrl;
string query= Request.Url.Query;
string isAllowed= Request.QueryString["allowed"];

It sounds like Request.Url.PathAndQuery could be what you want.

If you want access to the raw posted data you can use

string isAllowed = Request.Params["allowed"];
string id = RouteData.Values["id"];

Delete dynamically-generated table row using jQuery

I know this is old but I've used a function similar to this...

deleteRow: function (ctrl) {

    //remove the row from the table
    $(ctrl).closest('tr').remove();

}

... with markup like this ...

<tr>
<td><span id="spDeleteRow" onclick="deleteRow(this)">X</td>
<td> blah blah </td>
</tr>

...and it works fine

Replace whole line containing a string using Sed

cat find_replace | while read pattern replacement ; do
sed -i "/${pattern}/c ${replacement}" file    
done 

find_replace file contains 2 columns, c1 with pattern to match, c2 with replacement, the sed loop replaces each line conatining one of the pattern of variable 1

How to make image hover in css?

It will not work like this, put both images as background images:

.bg-img {
    background:url(images/yourImg.jpg) no-repeat 0 0;
}

.bg-img:hover {
    background:url(images/yourImg-1.jpg) no-repeat 0 0;
}

How to start/stop/restart a thread in Java?

Once a thread stops you cannot restart it. However, there is nothing stopping you from creating and starting a new thread.

Option 1: Create a new thread rather than trying to restart.

Option 2: Instead of letting the thread stop, have it wait and then when it receives notification you can allow it to do work again. This way the thread never stops and will never need to be restarted.

Edit based on comment:

To "kill" the thread you can do something like the following.

yourThread.setIsTerminating(true); // tell the thread to stop
yourThread.join(); // wait for the thread to stop

How can I get input radio elements to horizontally align?

In your case, you just need to remove the line breaks (<br> tags) between the elements - input elements are inline-block by default (in Chrome at least). (updated example).

<input type="radio" name="editList" value="always">Always
<input type="radio" name="editList" value="never">Never
<input type="radio" name="editList" value="costChange">Cost Change

I'd suggest using <label> elements, though. In doing so, clicking on the label will check the element too. Either associate the <label>'s for attribute with the <input>'s id: (example)

<input type="radio" name="editList" id="always" value="always"/>
<label for="always">Always</label>

<input type="radio" name="editList" id="never" value="never"/>
<label for="never">Never</label>

<input type="radio" name="editList" id="change" value="costChange"/>
<label for="change">Cost Change</label>

..or wrap the <label> elements around the <input> elements directly: (example)

<label>
    <input type="radio" name="editList" value="always"/>Always
</label>
<label>
    <input type="radio" name="editList" value="never"/>Never
</label>
<label>
    <input type="radio" name="editList" value="costChange"/>Cost Change
</label>

You can also get fancy and use the :checked pseudo class.

How to link 2 cell of excel sheet?

The simplest solution is to select the second cell, and press =. This will begin the fomula creation process. Now either type in the 1st cell reference (eg, A1) or click on the first cell and press enter. This should make the second cell reference the value of the first cell.

To read up more on different options for referencing see - This Article.

Find which rows have different values for a given column in Teradata SQL

You can do this using a group by:

select id, addressCode
from t
group by id, addressCode
having min(address) <> max(address)

Another way of writing this may seem clearer, but does not perform as well:

select id, addressCode
from t
group by id, addressCode
having count(distinct address) > 1

How to change color in markdown cells ipython/jupyter notebook?

The text color can be changed using,

<span style='color:green'> message/text </span>

MySQLi prepared statements error reporting

Completeness

You need to check both $mysqli and $statement. If they are false, you need to output $mysqli->error or $statement->error respectively.

Efficiency

For simple scripts that may terminate, I use simple one-liners that trigger a PHP error with the message. For a more complex application, an error warning system should be activated instead, for example by throwing an exception.

Usage example 1: Simple script

# This is in a simple command line script
$mysqli = new mysqli('localhost', 'buzUser', 'buzPassword');
$q = "UPDATE foo SET bar=1";
($statement = $mysqli->prepare($q)) or trigger_error($mysqli->error, E_USER_ERROR);
$statement->execute() or trigger_error($statement->error, E_USER_ERROR);

Usage example 2: Application

# This is part of an application
class FuzDatabaseException extends Exception {
}

class Foo {
  public $mysqli;
  public function __construct(mysqli $mysqli) {
    $this->mysqli = $mysqli;
  }
  public function updateBar() {
    $q = "UPDATE foo SET bar=1";
    $statement = $this->mysqli->prepare($q);
    if (!$statement) {
      throw new FuzDatabaseException($mysqli->error);
    }

    if (!$statement->execute()) {
      throw new FuzDatabaseException($statement->error);
    }
  }
}

$foo = new Foo(new mysqli('localhost','buzUser','buzPassword'));
try {
  $foo->updateBar();
} catch (FuzDatabaseException $e)
  $msg = $e->getMessage();
  // Now send warning emails, write log
}

Postgres manually alter sequence

This syntax isn't valid in any version of PostgreSQL:

ALTER SEQUENCE payments_id_seq LASTVALUE 22

This would work:

ALTER SEQUENCE payments_id_seq RESTART WITH 22;

And is equivalent to:

SELECT setval('payments_id_seq', 22, FALSE);

More in the current manual for ALTER SEQUENCE and sequence functions.

Note that setval() expects either (regclass, bigint) or (regclass, bigint, boolean). In the above example I am providing untyped literals. That works too. But if you feed typed variables to the function you may need explicit type casts to satisfy function type resolution. Like:

SELECT setval(my_text_variable::regclass, my_other_variable::bigint, FALSE);

For repeated operations you might be interested in:

ALTER SEQUENCE payments_id_seq START WITH 22; -- set default
ALTER SEQUENCE payments_id_seq RESTART;       -- without value

START [WITH] stores a default RESTART number, which is used for subsequent RESTART calls without value. You need Postgres 8.4 or later for the last part.

Python Pip install Error: Unable to find vcvarsall.bat. Tried all solutions

After doing a lot of things, I upgraded pip, setuptools and virtualenv.

  1. python -m pip install -U pip
  2. pip install -U setuptools
  3. pip install -U virtualenv

I did steps 1, 2 in my virtual environment as well as globally. Next, I installed the package through pip and it worked.

Laravel 5 Class 'form' not found

I have tried everything, but only this helped:

php artisan route:clear
php artisan cache:clear

Work on a remote project with Eclipse via SSH

This answer currently only applies to using two Linux computers [or maybe works on Mac too?--untested on Mac] (syncing from one to the other) because I wrote this synchronization script in bash. It is simply a wrapper around git, however, so feel free to take it and convert it into a cross-platform Python solution or something if you wish


This doesn't directly answer the OP's question, but it is so close I guarantee it will answer many other peoples' question who land on this page (mine included, actually, as I came here first before writing my own solution), so I'm posting it here anyway.

I want to:

  1. develop code using a powerful IDE like Eclipse on a light-weight Linux computer, then
  2. build that code via ssh on a different, more powerful Linux computer (from the command-line, NOT from inside Eclipse)

Let's call the first computer where I write the code "PC1" (Personal Computer 1), and the 2nd computer where I build the code "PC2". I need a tool to easily synchronize from PC1 to PC2. I tried rsync, but it was insanely slow for large repos and took tons of bandwidth and data.

So, how do I do it? What workflow should I use? If you have this question too, here's the workflow that I decided upon. I wrote a bash script to automate the process by using git to automatically push changes from PC1 to PC2 via a remote repository, such as github. So far it works very well and I'm very pleased with it. It is far far far faster than rsync, more trustworthy in my opinion because each PC maintains a functional git repo, and uses far less bandwidth to do the whole sync, so it's easily doable over a cell phone hot spot without using tons of your data.

Setup:

  1. Install the script on PC1 (this solution assumes ~/bin is in your $PATH):

    git clone https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles.git
    cd eRCaGuy_dotfiles/useful_scripts
    mkdir -p ~/bin
    ln -s "${PWD}/sync_git_repo_from_pc1_to_pc2.sh" ~/bin/sync_git_repo_from_pc1_to_pc2
    cd ..
    cp -i .sync_git_repo ~/.sync_git_repo
    
  2. Now edit the "~/.sync_git_repo" file you just copied above, and update its parameters to fit your case. Here are the parameters it contains:

    # The git repo root directory on PC2 where you are syncing your files TO; this dir must *already exist* 
    # and you must have *already `git clone`d* a copy of your git repo into it!
    # - Do NOT use variables such as `$HOME`. Be explicit instead. This is because the variable expansion will 
    #   happen on the local machine when what we need is the variable expansion from the remote machine. Being 
    #   explicit instead just avoids this problem.
    PC2_GIT_REPO_TARGET_DIR="/home/gabriel/dev/eRCaGuy_dotfiles" # explicitly type this out; don't use variables
    
    PC2_SSH_USERNAME="my_username" # explicitly type this out; don't use variables
    PC2_SSH_HOST="my_hostname"     # explicitly type this out; don't use variables
    
  3. Git clone your repo you want to sync on both PC1 and PC2.

  4. Ensure your ssh keys are all set up to be able to push and pull to the remote repo from both PC1 and PC2. Here's some helpful links:
    1. https://help.github.com/en/github/authenticating-to-github/connecting-to-github-with-ssh
    2. https://help.github.com/en/github/authenticating-to-github/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent
  5. Ensure your ssh keys are all set up to ssh from PC1 to PC2.
  6. Now cd into any directory within the git repo on PC1, and run:

    sync_git_repo_from_pc1_to_pc2
    
  7. That's it! About 30 seconds later everything will be magically synced from PC1 to PC2, and it will be printing output the whole time to tell you what it's doing and where it's doing it on your disk and on which computer. It's safe too, because it doesn't overwrite or delete anything that is uncommitted. It backs it up first instead! Read more below for how that works.

Here's the process this script uses (ie: what it's actually doing)

  1. From PC1: It checks to see if any uncommitted changes are on PC1. If so, it commits them to a temporary commit on the current branch. It then force pushes them to a remote SYNC branch. Then it uncommits its temporary commit it just did on the local branch, then it puts the local git repo back to exactly how it was by staging any files that were previously staged at the time you called the script. Next, it rsyncs a copy of the script over to PC2, and does an ssh call to tell PC2 to run the script with a special option to just do PC2 stuff.
  2. Here's what PC2 does: it cds into the repo, and checks to see if any local uncommitted changes exist. If so, it creates a new backup branch forked off of the current branch (sample name: my_branch_SYNC_BAK_20200220-0028hrs-15sec <-- notice that's YYYYMMDD-HHMMhrs--SSsec), and commits any uncommitted changes to that branch with a commit message such as DO BACKUP OF ALL UNCOMMITTED CHANGES ON PC2 (TARGET PC/BUILD MACHINE). Now, it checks out the SYNC branch, pulling it from the remote repository if it is not already on the local machine. Then, it fetches the latest changes on the remote repository, and does a hard reset to force the local SYNC repository to match the remote SYNC repository. You might call this a "hard pull". It is safe, however, because we already backed up any uncommitted changes we had locally on PC2, so nothing is lost!
  3. That's it! You now have produced a perfect copy from PC1 to PC2 without even having to ensure clean working directories, as the script handled all of the automatic committing and stuff for you! It is fast and works very well on huge repositories. Now you have an easy mechanism to use any IDE of your choice on one machine while building or testing on another machine, easily, over a wifi hot spot from your cell phone if needed, even if the repository is dozens of gigabytes and you are time and resource-constrained.

Resources:

  1. The whole project: https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles
    1. See tons more links and references in the source code itself within this project.
  2. How to do a "hard pull", as I call it: How do I force "git pull" to overwrite local files?

Related:

  1. git repository sync between computers, when moving around?

How to create separate AngularJS controller files?

For brevity, here's an ES2015 sample that doesn't rely on global variables

// controllers/example-controller.js

export const ExampleControllerName = "ExampleController"
export const ExampleController = ($scope) => {
  // something... 
}

// controllers/another-controller.js

export const AnotherControllerName = "AnotherController"
export const AnotherController = ($scope) => {
  // functionality... 
}

// app.js

import angular from "angular";

import {
  ExampleControllerName,
  ExampleController
} = "./controllers/example-controller";

import {
  AnotherControllerName,
  AnotherController
} = "./controllers/another-controller";

angular.module("myApp", [/* deps */])
  .controller(ExampleControllerName, ExampleController)
  .controller(AnotherControllerName, AnotherController)

bash shell nested for loop

One one line (semi-colons necessary):

for i in 0 1 2 3 4 5 6 7 8 9; do for j in 0 1 2 3 4 5 6 7 8 9; do echo "$i$j"; done; done

Formatted for legibility (no semi-colons needed):

for i in 0 1 2 3 4 5 6 7 8 9
do
    for j in 0 1 2 3 4 5 6 7 8 9
    do 
        echo "$i$j"
    done
done

There are different views on how the shell code should be laid out over multiple lines; that's about what I normally use, unless I put the next operation on the same line as the do (saving two lines here).

How to post data in PHP using file_get_contents?

$sUrl = 'http://www.linktopage.com/login/';
$params = array('http' => array(
    'method'  => 'POST',
    'content' => 'username=admin195&password=d123456789'
));

$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if(!$fp) {
    throw new Exception("Problem with $sUrl, $php_errormsg");
}

$response = @stream_get_contents($fp);
if($response === false) {
    throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}

How to obtain the chat_id of a private Telegram channel?

I use Telegram.Bot and got the ID the following way:

  1. Add the bot to the channel
  2. Run the bot
  3. Write something into the channel (eg: /authenticate or foo)

Telegram.Bot:

private static async Task Main()
{
    var botClient = new TelegramBotClient("key");
    botClient.OnUpdate += BotClientOnOnUpdate;
    Console.ReadKey();
}

private static async void BotClientOnOnUpdate(object? sender, UpdateEventArgs e)
{
    var id = e.Update.ChannelPost.Chat.Id;
    await botClient.SendTextMessageAsync(new ChatId(id), $"Hello World! Channel ID is {id}");
}

Plain API:

This translates to the getUpdates method in the plain API, which has an array of Update which then contains channel_post.chat.id

Pretty-print an entire Pandas Series / DataFrame

datascroller was created in part to solve this problem.

pip install datascroller

It loads the dataframe into a terminal view you can "scroll" with your mouse or arrow keys, kind of like an Excel workbook at the terminal that supports querying, highlighting, etc.

import pandas as pd
from datascroller import scroll

# Call `scroll` with a Pandas DataFrame as the sole argument:
my_df = pd.read_csv('<path to your csv>')
scroll(my_df)

Google Recaptcha v3 example demo

if you are newly implementing recaptcha on your site, I would suggest adding api.js and let google collect behavioral data of your users 1-2 days. It is much fail-safe this way, especially before starting to use score.

MySQL: #1075 - Incorrect table definition; autoincrement vs another key?

Identified this solution while reading this thread. Figured id post this for the next guy possibly.

When dealing with Laravel migration file from a package, I Ran into this issue.

My old value was

$table->increments('id');

My new

$table->integer('id')->autoIncrement();

What is the "double tilde" (~~) operator in JavaScript?

It hides the intention of the code.

It's two single tilde operators, so it does a bitwise complement (bitwise not) twice. The operations take out each other, so the only remaining effect is the conversion that is done before the first operator is applied, i.e. converting the value to an integer number.

Some use it as a faster alternative to Math.floor, but the speed difference is not that dramatic, and in most cases it's just micro optimisation. Unless you have a piece of code that really needs to be optimised, you should use code that descibes what it does instead of code that uses a side effect of a non-operation.

Update 2011-08:

With optimisation of the JavaScript engine in browsers, the performance for operators and functions change. With current browsers, using ~~ instead of Math.floor is somewhat faster in some browsers, and not faster at all in some browsers. If you really need that extra bit of performance, you would need to write different optimised code for each browser.

See: tilde vs floor

Detect current device with UI_USER_INTERFACE_IDIOM() in Swift

You should use this GBDeviceInfo framework or ...

Apple defines this:

public enum UIUserInterfaceIdiom : Int {

    case unspecified

    case phone // iPhone and iPod touch style UI

    case pad // iPad style UI

    @available(iOS 9.0, *)
    case tv // Apple TV style UI

    @available(iOS 9.0, *)
    case carPlay // CarPlay style UI
}

so for the strict definition of the device can be used this code

struct ScreenSize
{
    static let SCREEN_WIDTH         = UIScreen.main.bounds.size.width
    static let SCREEN_HEIGHT        = UIScreen.main.bounds.size.height
    static let SCREEN_MAX_LENGTH    = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
    static let SCREEN_MIN_LENGTH    = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
}

struct DeviceType
{
    static let IS_IPHONE_4_OR_LESS  = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH < 568.0
    static let IS_IPHONE_5          = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 568.0
    static let IS_IPHONE_6_7          = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 667.0
    static let IS_IPHONE_6P_7P         = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 736.0
    static let IS_IPAD              = UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1024.0
    static let IS_IPAD_PRO          = UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1366.0
}

how to use

if DeviceType.IS_IPHONE_6P_7P {
    print("IS_IPHONE_6P_7P")
}

to detect iOS version

struct Version{
    static let SYS_VERSION_FLOAT = (UIDevice.current.systemVersion as NSString).floatValue
    static let iOS7 = (Version.SYS_VERSION_FLOAT < 8.0 && Version.SYS_VERSION_FLOAT >= 7.0)
    static let iOS8 = (Version.SYS_VERSION_FLOAT >= 8.0 && Version.SYS_VERSION_FLOAT < 9.0)
    static let iOS9 = (Version.SYS_VERSION_FLOAT >= 9.0 && Version.SYS_VERSION_FLOAT < 10.0)
}

how to use

if Version.iOS8 {
    print("iOS8")
}

How do I use TensorFlow GPU?

Strangely, even though the tensorflow website 1 mentions that CUDA 10.1 is compatible with tensorflow-gpu-1.13.1, it doesn't work so far. tensorflow-gpu gets installed properly though but it throws out weird errors when running.

So far, the best configuration to run tensorflow with GPU is CUDA 9.0 with tensorflow_gpu-1.12.0 under python3.6.

Following this configuration with the steps mentioned in https://stackoverflow.com/a/51307381/2562870 (the answer above), worked for me :)

How to convert TimeStamp to Date in Java?

Just make a new Date object with the stamp's getTime() value as a parameter.

Here's an example (I use an example timestamp of the current time):

Timestamp stamp = new Timestamp(System.currentTimeMillis());
Date date = new Date(stamp.getTime());
System.out.println(date);

Responsive bootstrap 3 timepicker?

Kendo UI provides the best and ultimate collection of JavaScript UI components with libraries for jQuery, Angular, React, and Vue. You can quickly build eye-catching, high-performance, responsive web applications regardless of your JavaScript framework choice. Here is a timepicker UI component from them:

Also below is an alternate and a simple solution

<!--Css-->
<link href="css/timepicker.css" type="text/css" rel="stylesheet" />

<!--Html-->
<div class="row">
    <div class="col">
        <label class="label-in">Time</label>
        <input class="timepicker" id="event-time" type="text" value="" required="">
    </div>
</div>

<!--Script-->
<script src="Scripts/ClockPicker.js"></script>
<script>
   $('.timepicker').timepicker({
     });
</script>

Here is yet another popular framework Bootstrap Time Picker from mdbootstrap

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

In certain cases, it might be necessary to restrict the display of a webpage to a document mode supported by an earlier version of Internet Explorer. You can do this by serving the page with an x-ua-compatible header. For more info, see Specifying legacy document modes.
- https://msdn.microsoft.com/library/cc288325

Thus this tag is used to future proof the webpage, such that the older / compatible engine is used to render it the same way as intended by the creator.

Make sure that you have checked it to work properly with the IE version you specify.

String was not recognized as a valid DateTime " format dd/MM/yyyy"

You might need to specify the culture for that specific date format as in:

    Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); //dd/MM/yyyy

    this.Text="22/11/2009";

    DateTime date = DateTime.Parse(this.Text);

For more details go here:

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

Form submit with AJAX passing form data to PHP without page refresh

JS Code

    $("#submit").click(function() { 
    //get input field values
    var name            = $('#name').val(); 
    var email           = $('#email').val();
    var message         = $('#comment').val();
    var flag = true;
    /********validate all our form fields***********/
    /* Name field validation  */
    if(name==""){ 
        $('#name').css('border-color','red'); 
        flag = false;
    }
    /* email field validation  */
    if(email==""){ 
        $('#email').css('border-color','red'); 
        flag = false;
    } 
    /* message field validation */
    if(message=="") {  
       $('#comment').css('border-color','red'); 
        flag = false;
    }
    /********Validation end here ****/
    /* If all are ok then we send ajax request to email_send.php *******/
    if(flag) 
    {
        $.ajax({
            type: 'post',
            url: "email_send.php", 
            dataType: 'json',
            data: 'username='+name+'&useremail='+email+'&message='+message,
            beforeSend: function() {
                $('#submit').attr('disabled', true);
                $('#submit').after('<span class="wait">&nbsp;<img src="image/loading.gif" alt="" /></span>');
            },
            complete: function() {
                $('#submit').attr('disabled', false);
                $('.wait').remove();
            },  
            success: function(data)
            {
                if(data.type == 'error')
                {
                    output = '<div class="error">'+data.text+'</div>';
                }else{
                    output = '<div class="success">'+data.text+'</div>';
                    $('input[type=text]').val(''); 
                    $('#contactform textarea').val(''); 
                }

                $("#result").hide().html(output).slideDown();           
                }
        });
    }
});
//reset previously set border colors and hide all message on .keyup()
$("#contactform input, #contactform textarea").keyup(function() { 
    $("#contactform input, #contactform textarea").css('border-color',''); 
    $("#result").slideUp();
});

HTML Form

<div  class="cover">
<div id="result"></div>
<div id="contactform">
    <p class="contact"><label for="name">Name</label></p>
    <input id="name" name="name" placeholder="Yourname" type="text">

    <p class="contact"><label for="email">Email</label></p>
    <input id="email" name="email" placeholder="[email protected]" type="text">

    <p class="contact"><label for="comment">Your Message</label></p>
    <textarea name="comment" id="comment" tabindex="4"></textarea> <br>
    <input name="submit" id="submit" tabindex="5" value="Send Mail" type="submit" style="width:200px;">
</div>

PHP Code

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

//check if its an ajax request, exit if not
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {

    //exit script outputting json data
    $output = json_encode(
            array(
                'type' => 'error',
                'text' => 'Request must come from Ajax'
    ));

    die($output);
}

//check $_POST vars are set, exit if any missing
if (!isset($_POST["username"]) || !isset($_POST["useremail"]) || !isset($_POST["message"])) {
    $output = json_encode(array('type' => 'error', 'text' => 'Input fields are empty!'));
    die($output);
}

//Sanitize input data using PHP filter_var().
$username = filter_var(trim($_POST["username"]), FILTER_SANITIZE_STRING);
$useremail = filter_var(trim($_POST["useremail"]), FILTER_SANITIZE_EMAIL);
$message = filter_var(trim($_POST["message"]), FILTER_SANITIZE_STRING);

//additional php validation
if (strlen($username) < 4) { // If length is less than 4 it will throw an HTTP error.
    $output = json_encode(array('type' => 'error', 'text' => 'Name is too short!'));
    die($output);
}
if (!filter_var($useremail, FILTER_VALIDATE_EMAIL)) { //email validation
    $output = json_encode(array('type' => 'error', 'text' => 'Please enter a valid email!'));
    die($output);
}
if (strlen($message) < 5) { //check emtpy message
    $output = json_encode(array('type' => 'error', 'text' => 'Too short message!'));
    die($output);
}

$to = "[email protected]"; //Replace with recipient email address
//proceed with PHP email.
$headers = 'From: ' . $useremail . '' . "\r\n" .
        'Reply-To: ' . $useremail . '' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

$sentMail = @mail($to, $subject, $message . '  -' . $username, $headers);
//$sentMail = true;
if (!$sentMail) {
    $output = json_encode(array('type' => 'error', 'text' => 'Could not send mail! Please contact administrator.'));
    die($output);
} else {
    $output = json_encode(array('type' => 'message', 'text' => 'Hi ' . $username . ' Thank you for your email'));
    die($output);
}

This page has a simpler example http://wearecoders.net/submit-form-without-page-refresh-with-php-and-ajax/

How can I add NSAppTransportSecurity to my info.plist file?

In mac shell command line , use the following command:

plutil -insert NSAppTransportSecurity -xml "<array><string> hidden </string></array>" [location of your xcode project]/Info.plist 

The command will add all the necessary values into your plist file.

file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request?

Your second question is easy, GET has a size limitation of 1-2 kilobytes on both the server and browser side, so any kind of larger amounts of data you'd have to send through POST.

Is it possible to pass a flag to Gulp to have it run tasks in different ways?

Gulp doesn't offer any kind of util for that, but you can use one of the many command args parsers. I like yargs. Should be:

var argv = require('yargs').argv;

gulp.task('my-task', function() {
    return gulp.src(argv.a == 1 ? options.SCSS_SOURCE : options.OTHER_SOURCE)
        .pipe(sass({style:'nested'}))
        .pipe(autoprefixer('last 10 version'))
        .pipe(concat('style.css'))
        .pipe(gulp.dest(options.SCSS_DEST));
});

You can also combine it with gulp-if to conditionally pipe the stream, very useful for dev vs. prod building:

var argv = require('yargs').argv,
    gulpif = require('gulp-if'),
    rename = require('gulp-rename'),
    uglify = require('gulp-uglify');

gulp.task('my-js-task', function() {
  gulp.src('src/**/*.js')
    .pipe(concat('out.js'))
    .pipe(gulpif(argv.production, uglify()))
    .pipe(gulpif(argv.production, rename({suffix: '.min'})))
    .pipe(gulp.dest('dist/'));
});

And call with gulp my-js-task or gulp my-js-task --production.

How to get the URL of the current page in C#

Try this :

string url = HttpContext.Current.Request.Url.AbsoluteUri;
// http://localhost:1302/TESTERS/Default6.aspx

string path = HttpContext.Current.Request.Url.AbsolutePath;
// /TESTERS/Default6.aspx

string host = HttpContext.Current.Request.Url.Host;
// localhost

Func vs. Action vs. Predicate

Action is a delegate (pointer) to a method, that takes zero, one or more input parameters, but does not return anything.

Func is a delegate (pointer) to a method, that takes zero, one or more input parameters, and returns a value (or reference).

Predicate is a special kind of Func often used for comparisons.

Though widely used with Linq, Action and Func are concepts logically independent of Linq. C++ already contained the basic concept in form of typed function pointers.

Here is a small example for Action and Func without using Linq:

class Program
{
    static void Main(string[] args)
    {
        Action<int> myAction = new Action<int>(DoSomething);
        myAction(123);           // Prints out "123"
                                 // can be also called as myAction.Invoke(123);

        Func<int, double> myFunc = new Func<int, double>(CalculateSomething);
        Console.WriteLine(myFunc(5));   // Prints out "2.5"
    }

    static void DoSomething(int i)
    {
        Console.WriteLine(i);
    }

    static double CalculateSomething(int i)
    {
        return (double)i/2;
    }
}

set up device for development (???????????? no permissions)

  1. Follow the instructions at http://developer.android.com/guide/developing/device.html(Archived link)
  2. Replace the vendor id of 0bb4 with 18d1 in /etc/udev/rules.d/51-android.rules

    Or add another line that reads:

    SUBSYSTEM=="usb", SYSFS{idVendor}=="18d1", MODE="0666"
    
  3. Restart computer or just restart udev service.

Filename timestamp in Windows CMD batch script getting truncated

In the past, I've used a .cmd script I found on the Internet. I hate the way localization normally messes with dates. Anytime you have dates in filenames (or anywhere else, if I may be so bold) I figure you want them in ISO 8601 format:

2015-02-19T14:54:51Z

or something else that has Y M D H M in that order, such as

2015-02-19 14:54

because it fixes the MDY / DMY ambiguity and because it's sortable as text.

I don't know where I got that .cmd script, but it may have been http://ss64.com/nt/syntax-getdate.html, which works beautifully on my YYYY-MM-DD Windows 8.1 and on a M/D/YYYY vanilla install of Windows 7. Both give the same format:

2015-02-09 04:43

Store images in a MongoDB database

"You should always use GridFS for storing files larger than 16MB" - When should I use GridFS?

MongoDB BSON documents are capped at 16 MB. So if the total size of your array of files is less than that, you may store them directly in your document using the BinData data type.

Videos, images, PDFs, spreadsheets, etc. - it doesn't matter, they are all treated the same. It's up to your application to return an appropriate content type header to display them.

Check out the GridFS documentation for more details.

How to change the cursor into a hand when a user hovers over a list item?

Use for li:

li:hover {
    cursor: pointer;
}

See more cursor properties with examples after running snippet option:

An animation showing a cursor hovering over a div of each class

_x000D_
_x000D_
.auto          { cursor: auto; }_x000D_
.default       { cursor: default; }_x000D_
.none          { cursor: none; }_x000D_
.context-menu  { cursor: context-menu; }_x000D_
.help          { cursor: help; }_x000D_
.pointer       { cursor: pointer; }_x000D_
.progress      { cursor: progress; }_x000D_
.wait          { cursor: wait; }_x000D_
.cell          { cursor: cell; }_x000D_
.crosshair     { cursor: crosshair; }_x000D_
.text          { cursor: text; }_x000D_
.vertical-text { cursor: vertical-text; }_x000D_
.alias         { cursor: alias; }_x000D_
.copy          { cursor: copy; }_x000D_
.move          { cursor: move; }_x000D_
.no-drop       { cursor: no-drop; }_x000D_
.not-allowed   { cursor: not-allowed; }_x000D_
.all-scroll    { cursor: all-scroll; }_x000D_
.col-resize    { cursor: col-resize; }_x000D_
.row-resize    { cursor: row-resize; }_x000D_
.n-resize      { cursor: n-resize; }_x000D_
.e-resize      { cursor: e-resize; }_x000D_
.s-resize      { cursor: s-resize; }_x000D_
.w-resize      { cursor: w-resize; }_x000D_
.ns-resize     { cursor: ns-resize; }_x000D_
.ew-resize     { cursor: ew-resize; }_x000D_
.ne-resize     { cursor: ne-resize; }_x000D_
.nw-resize     { cursor: nw-resize; }_x000D_
.se-resize     { cursor: se-resize; }_x000D_
.sw-resize     { cursor: sw-resize; }_x000D_
.nesw-resize   { cursor: nesw-resize; }_x000D_
.nwse-resize   { cursor: nwse-resize; }_x000D_
_x000D_
.cursors > div {_x000D_
    float: left;_x000D_
    box-sizing: border-box;_x000D_
    background: #f2f2f2;_x000D_
    border:1px solid #ccc;_x000D_
    width: 20%;_x000D_
    padding: 10px 2px;_x000D_
    text-align: center;_x000D_
    white-space: nowrap;_x000D_
    &:nth-child(even) {_x000D_
       background: #eee;_x000D_
    }_x000D_
    &:hover {_x000D_
       opacity: 0.25_x000D_
    }_x000D_
}
_x000D_
<h1>Example of cursor</h1>_x000D_
_x000D_
<div class="cursors">_x000D_
    <div class="auto">auto</div>_x000D_
    <div class="default">default</div>_x000D_
    <div class="none">none</div>_x000D_
    <div class="context-menu">context-menu</div>_x000D_
    <div class="help">help</div>_x000D_
    <div class="pointer">pointer</div>_x000D_
    <div class="progress">progress</div>_x000D_
    <div class="wait">wait</div>_x000D_
    <div class="cell">cell</div>_x000D_
    <div class="crosshair">crosshair</div>_x000D_
    <div class="text">text</div>_x000D_
    <div class="vertical-text">vertical-text</div>_x000D_
    <div class="alias">alias</div>_x000D_
    <div class="copy">copy</div>_x000D_
    <div class="move">move</div>_x000D_
    <div class="no-drop">no-drop</div>_x000D_
    <div class="not-allowed">not-allowed</div>_x000D_
    <div class="all-scroll">all-scroll</div>_x000D_
    <div class="col-resize">col-resize</div>_x000D_
    <div class="row-resize">row-resize</div>_x000D_
    <div class="n-resize">n-resize</div>_x000D_
    <div class="s-resize">s-resize</div>_x000D_
    <div class="e-resize">e-resize</div>_x000D_
    <div class="w-resize">w-resize</div>_x000D_
    <div class="ns-resize">ns-resize</div>_x000D_
    <div class="ew-resize">ew-resize</div>_x000D_
    <div class="ne-resize">ne-resize</div>_x000D_
    <div class="nw-resize">nw-resize</div>_x000D_
    <div class="se-resize">se-resize</div>_x000D_
    <div class="sw-resize">sw-resize</div>_x000D_
    <div class="nesw-resize">nesw-resize</div>_x000D_
    <div class="nwse-resize">nwse-resize</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

string comparison in batch file

While @ajv-jsy's answer works most of the time, I had the same problem as @MarioVilas. If one of the strings to be compared contains a double quote ("), the variable expansion throws an error.

Example:

@echo off
SetLocal

set Lhs="
set Rhs="

if "%Lhs%" == "%Rhs%" echo Equal

Error:

echo was unexpected at this time.

Solution:

Enable delayed expansion and use ! instead of %.

@echo off
SetLocal EnableDelayedExpansion

set Lhs="
set Rhs="

if !Lhs! == !Rhs! echo Equal

:: Surrounding with double quotes also works but appears (is?) unnecessary.
if "!Lhs!" == "!Rhs!" echo Equal

I have not been able to break it so far using this technique. It works with empty strings and all the symbols I threw at it.

Test:

@echo off
SetLocal EnableDelayedExpansion

:: Test empty string
set Lhs=
set Rhs=
echo Lhs: !Lhs! & echo Rhs: !Rhs!
if !Lhs! == !Rhs! (echo Equal) else (echo Not Equal)
echo.

:: Test symbols
set Lhs= \ / : * ? " ' < > | %% ^^ ` ~ @ # $ [ ] & ( ) + - _ =
set Rhs= \ / : * ? " ' < > | %% ^^ ` ~ @ # $ [ ] & ( ) + - _ =
echo Lhs: !Lhs! & echo Rhs: !Rhs!
if !Lhs! == !Rhs! (echo Equal) else (echo Not Equal)
echo.

Appending values to dictionary in Python

If you want to append to the lists of each key inside a dictionary, you can append new values to them using + operator (tested in Python 3.7):

mydict = {'a':[], 'b':[]}
print(mydict)
mydict['a'] += [1,3]
mydict['b'] += [4,6]
print(mydict)
mydict['a'] += [2,8]
print(mydict)

and the output:

{'a': [], 'b': []}
{'a': [1, 3], 'b': [4, 6]}
{'a': [1, 3, 2, 8], 'b': [4, 6]}

mydict['a'].extend([1,3]) will do the job same as + without creating a new list (efficient way).

Disabled UIButton not faded or grey

Create an extension in Swift > 3.0 rather than each button by itself

extension UIButton {
    override open var isEnabled : Bool {
        willSet{
            if newValue == false {
                self.setTitleColor(UIColor.gray, for: UIControlState.disabled)
            }
        }
    }
}

Show popup after page load

If you don't want to use jquery, use this:

<script>
 // without jquery
document.addEventListener("DOMContentLoaded", function() {
 setTimeout(function() {
  // run your open popup function after 5 sec = 5000
  PopUp();
 }, 5000)
});
</script>

OR With jquery

<script>
  $(document).ready(function(){
   setTimeout(function(){
   // open popup after 5 seconds
   PopUp();
  },5000);  
 });
</script>

using wildcards in LDAP search filters/queries

Your best bet would be to anticipate prefixes, so:

"(|(displayName=SEARCHKEY*)(displayName=ITSM - SEARCHKEY*)(displayName=alt prefix - SEARCHKEY*))"

Clunky, but I'm doing a similar thing within my organization.