Programs & Examples On #Serp

Serp refers to Search Engine Results Page. This page displays the results of search query. General questions about SEO are off topic here unless directly related to programming.

DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server

var userPasswordString = new Buffer(baseAuth, 'base64').toString('ascii');

Change this line from your code to this -

var userPasswordString = Buffer.from(baseAuth, 'base64').toString('ascii');

or in my case, I gave the encoding in reverse order

var userPasswordString = Buffer.from(baseAuth, 'utf-8').toString('base64');

Nested routes with react router v4 / v5

A complete answer for React Router v5.


const Router = () => {
  return (
    <Switch>
      <Route path={"/"} component={LandingPage} exact />
      <Route path={"/games"} component={Games} />
      <Route path={"/game-details/:id"} component={GameDetails} />
      <Route
        path={"/dashboard"}
        render={({ match: { path } }) => (
          <Dashboard>
            <Switch>
              <Route
                exact
                path={path + "/"}
                component={DashboardDefaultContent}
              />
              <Route path={`${path}/inbox`} component={Inbox} />
              <Route
                path={`${path}/settings-and-privacy`}
                component={SettingsAndPrivacy}
              />
              <Redirect exact from={path + "/*"} to={path} />
            </Switch>
          </Dashboard>
        )}
      />
      <Route path="/not-found" component={NotFound} />
      <Redirect exact from={"*"} to={"/not-found"} />
    </Switch>
  );
};

export default Router;
const Dashboard = ({ children }) => {
  return (
    <Grid
      container
      direction="row"
      justify="flex-start"
      alignItems="flex-start"
    >
      <DashboardSidebarNavigation />
      {children}
    </Grid>
  );
};

export default Dashboard;

Github repo is here. https://github.com/webmasterdevlin/react-router-5-demo

How to determine previous page URL in Angular?

Angular 8 & rxjs 6 in 2019 version

I would like to share the solution based on others great solutions.

First make a service to listen for routes changes and save the last previous route in a Behavior Subject, then provide this service in the main app.component in constructor then use this service to get the previous route you want when ever you want.

use case: you want to redirect the user to an advertise page then auto redirect him/her to where he did came from so you need the last previous route to do so.

// service : route-events.service.ts

import { Injectable } from '@angular/core';
import { Router, RoutesRecognized } from '@angular/router';
import { BehaviorSubject } from 'rxjs';
import { filter, pairwise } from 'rxjs/operators';
import { Location } from '@angular/common';

@Injectable()
export class RouteEventsService {

    // save the previous route
  public previousRoutePath = new BehaviorSubject<string>('');

  constructor(
    private router: Router,
    private location: Location
  ) {

    // ..initial prvious route will be the current path for now
    this.previousRoutePath.next(this.location.path());


    // on every route change take the two events of two routes changed(using pairwise)
    // and save the old one in a behavious subject to access it in another component
    // we can use if another component like intro-advertise need the previous route
    // because he need to redirect the user to where he did came from.
    this.router.events.pipe(
      filter(e => e instanceof RoutesRecognized),
      pairwise(),
        )
    .subscribe((event: any[]) => {
        this.previousRoutePath.next(event[0].urlAfterRedirects);
    });

  }
}

provide the service in app.module

  providers: [
    ....
    RouteEventsService,
    ....
  ]

Inject it in app.component

  constructor(
    private routeEventsService: RouteEventsService
  )

finally use the saved previous route in the component you want

  onSkipHandler(){
    // navigate the user to where he did came from
    this.router.navigate([this.routeEventsService.previousRoutePath.value]);
  }

org.springframework.web.client.HttpClientErrorException: 400 Bad Request

This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.

MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
        headers);
JSONObject jsonObject = null;

try {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> responseEntity = restTemplate.exchange(
            "https://url", HttpMethod.POST, entity,
            String.class);

    if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
        try {
            jsonObject = new JSONObject(responseEntity.getBody());
        } catch (JSONException e) {
            throw new RuntimeException("JSONException occurred");
        }
    }
  } catch (final HttpClientErrorException httpClientErrorException) {
        throw new ExternalCallBadRequestException();
  } catch (HttpServerErrorException httpServerErrorException) {
        throw new ExternalCallServerErrorException(httpServerErrorException);
  } catch (Exception exception) {
        throw new ExternalCallServerErrorException(exception);
    } 

ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.

Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.

Angular 2 TypeScript how to find element in Array

You need to use method Array.filter:

this.persons =  this.personService.getPersons().filter(x => x.id == this.personId)[0];

or Array.find

this.persons =  this.personService.getPersons().find(x => x.id == this.personId);

<img>: Unsafe value used in a resource URL context

Pipe

// Angular
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';

/**
 * Sanitize HTML
 */
@Pipe({
  name: 'safe'
})
export class SafePipe implements PipeTransform {
  /**
   * Pipe Constructor
   *
   * @param _sanitizer: DomSanitezer
   */
  // tslint:disable-next-line
  constructor(protected _sanitizer: DomSanitizer) {
  }

  /**
   * Transform
   *
   * @param value: string
   * @param type: string
   */
  transform(value: string, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
    switch (type) {
      case 'html':
        return this._sanitizer.bypassSecurityTrustHtml(value);
      case 'style':
        return this._sanitizer.bypassSecurityTrustStyle(value);
      case 'script':
        return this._sanitizer.bypassSecurityTrustScript(value);
      case 'url':
        return this._sanitizer.bypassSecurityTrustUrl(value);
      case 'resourceUrl':
        return this._sanitizer.bypassSecurityTrustResourceUrl(value);
      default:
        return this._sanitizer.bypassSecurityTrustHtml(value);
    }
  }
}

Template

{{ data.url | safe:'url' }}

That's it!

Note: You shouldn't need it but here is the component use of the pipe
  // Public properties
  itsSafe: SafeHtml;

  // Private properties
  private safePipe: SafePipe = new SafePipe(this.domSanitizer);

  /**
   * Component constructor
   *
   * @param safePipe: SafeHtml
   * @param domSanitizer: DomSanitizer
   */
  constructor(private safePipe: SafePipe, private domSanitizer: DomSanitizer) {
  }

  /**
   * On init
   */
  ngOnInit(): void {
    this.itsSafe = this.safePipe.transform('<h1>Hi</h1>', 'html');
  }

Angular2 Routing with Hashtag to page anchor

I just got this working on my own website, so I figured it would be worth posting my solution here.

<a [routerLink]="baseUrlGoesHere" fragment="nameOfYourAnchorGoesHere">Link Text!</a>

<a name="nameOfYourAnchorGoesHere"></a>
<div>They're trying to anchor to me!</div>

And then in your component, make sure you include this:

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

 constructor(private route: ActivatedRoute) { 
     this.route.fragment.subscribe ( f => {
         const element = document.querySelector ( "#" + f )
         if ( element ) element.scrollIntoView ( element )
     });
 }

Powershell: A positional parameter cannot be found that accepts argument "xxx"

In my case I had tried to make code more readable by putting:

"LONGTEXTSTRING " +
"LONGTEXTSTRING" +
"LONGTEXTSTRING"

Once I changed it to

LONGTEXTSTRING LONGTEXTSTRING LONGTEXTSTRING 

Then it worked

How to edit default dark theme for Visual Studio Code?

In VS code 'User Settings', you can edit visible colours using the following tags(this is a sample and there are much more tags),

"workbench.colorCustomizations": {
    "list.inactiveSelectionBackground": "#C5DEF0",
    "sideBar.background": "#F8F6F6",
    "sideBar.foreground": "#000000",
    "editor.background": "#FFFFFF",
    "editor.foreground": "#000000",
    "sideBarSectionHeader.background": "#CAC9C9",
    "sideBarSectionHeader.foreground": "#000000",
    "activityBar.border": "#FFFFFF",
    "statusBar.background": "#102F97",
    "scrollbarSlider.activeBackground": "#77D4CB",
    "scrollbarSlider.hoverBackground": "#8CE6DA",
    "badge.background": "#81CA91"}

If you want to edit some C++ color tokens, use the following tag,

"editor.tokenColorCustomizations": {
    "numbers": "#2247EB",
    "comments": "#6D929C",
    "functions": "#0D7C28"
}

android : Error converting byte to dex

I've noticed this can happen (sometimes) when editing java files while Android Studio is building.

I solved this by manually deleting the build folder and running agin.

How to submit a form using Enter key in react.js?

Change <button type="button" to <button type="submit". Remove the onClick. Instead do <form className="commentForm" onSubmit={this.onFormSubmit}>. This should catch clicking the button and pressing the return key.

onFormSubmit = e => {
  e.preventDefault();
  const { name, email } = this.state;
  // send to server with e.g. `window.fetch`
}

...

<form onSubmit={this.onFormSubmit}>
  ...
  <button type="submit">Submit</button>
</form>

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

In my case I've had more then 5000 items in the list. My problem was that when scrolling the recycler view, sometimes the "onBindViewHolder" get called while "myCustomAddItems" method is altering the list.

My solution was to add "synchronized (syncObject){}" to all the methods that alter the data list. This way at any point at time only one method can read this list.

How to loop through an array of objects in swift

Unwrap and downcast the objects to the right type, safely, with if let, before doing the iteration with a simple for in loop.

if let currentUser = currentUser, 
    let photos = currentUser.photos as? [ModelAttachment] 
{
    for object in photos {
        let url = object.url
    }
}

There's also guard let else instead of if let if you prefer having the result available in scope:

guard let currentUser = currentUser, 
    let photos = currentUser.photos as? [ModelAttachment] else 
{
    // break or return
}
// now 'photos' is available outside the guard
for object in photos {
    let url = object.url
}

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

i had the same problem and it seems like i didn't initiate the button used with click listener, in other words id didn't te

How to get the SHA-1 fingerprint certificate in Android Studio for debug mode?

Easiest ways ever:

Update added for Android Studio V 2.2 in last step

There are two ways to do this.

1. Faster way:

  1. Open Android Studio
  2. Open your Project
  3. Click on Gradle (From Right Side Panel, you will see Gradle Bar)
  4. Click on Refresh (Click on Refresh from Gradle Bar, you will see List Gradle scripts of your Project)
  5. Click on Your Project (Your Project Name form List (root))
  6. Click on Tasks
  7. Click on Android
  8. Double Click on signingReport (You will get SHA1 and MD5 in Run Bar(Sometimes it will be in Gradle Console))
  9. Select app module from module selection dropdown to run or debug your application

Check the screenshot below:

enter image description here

2. Work with Google Maps Activity:

  1. Open Android Studio
  2. Open Your Project
  3. Click on File menu -> Select New -> Click on Google -> Select Google Maps Activity
  4. A dialog would appear -> Click on Finish
  5. Android Studio would automatically generate an XML file named with google_maps_api.xml
  6. You would get debug SHA1 key here (at line number 10 of the XML file)

Check Screenshot below:

Enter image description here

Android Studio V 2.2 Update

There is an issue with Execution.

Solution:

  • Click on Toggle tasks execution/text mode from Run bar

Check Screenshot below:

enter image description here

Done.

How can I verify if an AD account is locked?

This ScriptingGuy guest post links to a script by a Microsoft Powershell Expert can help you find this information, but to fully audit why it was locked and which machine triggered the lock you probably need to turn on additional levels of auditing via GPO.

https://gallery.technet.microsoft.com/scriptcenter/Get-LockedOutLocation-b2fd0cab#content

The view didn't return an HttpResponse object. It returned None instead

Python is very sensitive to indentation, with the code below I got the same error:

    except IntegrityError as e:
        if 'unique constraint' in e.args:
            return render(request, "calender.html")

The correct indentation is:

    except IntegrityError as e:
        if 'unique constraint' in e.args:
        return render(request, "calender.html")

You are trying to add a non-nullable field 'new_field' to userprofile without a default

If you are in early development cycle and don't care about your current database data you can just remove it and then migrate. But first you need to clean migrations dir and remove its rows from table (django_migrations)

rm  your_app/migrations/*

rm db.sqlite3
python manage.py makemigrations
python manage.py migrate

git returns http error 407 from proxy after CONNECT

Had the 407 error from Android Studio. Tried adding the proxy, but nothing happened. Found out that it was related to company certificate, so I exported the one from my browser and added it to Git.

Export From Web Browser

Internet Options > Content > Certificates > Export (Follow wizard, I chose format "Base 64 encoded X.509(.CER))

In Git Bash

git config --global http.sslCAInfo c:\Utilities\Certificates\my_certificate

The following page was useful https://blogs.msdn.microsoft.com/phkelley/2014/01/20/adding-a-corporate-or-self-signed-certificate-authority-to-git-exes-store/

To add the proxy, like the other threads I used

git config --global http.proxy proxy.company.net:8080
git config --global https.proxy proxy.company.net:8080

How to handle authentication popup with Selenium WebDriver using Java

Try following solution and let me know in case of any issues:

driver.get('https://example.com/')
driver.switchTo().alert().sendKeys("username" + Keys.TAB + "password");
driver.switchTo().alert().accept();

This is working fine for me

"if not exist" command in batch file

if not exist "%USERPROFILE%\.qgis-custom\" (
    mkdir "%USERPROFILE%\.qgis-custom" 2>nul
    if not errorlevel 1 (
        xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
    )
)

You have it almost done. The logic is correct, just some little changes.

This code checks for the existence of the folder (see the ending backslash, just to differentiate a folder from a file with the same name).

If it does not exist then it is created and creation status is checked. If a file with the same name exists or you have no rights to create the folder, it will fail.

If everyting is ok, files are copied.

All paths are quoted to avoid problems with spaces.

It can be simplified (just less code, it does not mean it is better). Another option is to always try to create the folder. If there are no errors, then copy the files

mkdir "%USERPROFILE%\.qgis-custom" 2>nul 
if not errorlevel 1 (
    xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
)

In both code samples, files are not copied if the folder is not being created during the script execution.

EDITED - As dbenham comments, the same code can be written as a single line

md "%USERPROFILE%\.qgis-custom" 2>nul && xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e

The code after the && will only be executed if the previous command does not set errorlevel. If mkdir fails, xcopy is not executed.

Unable to launch the IIS Express Web server, Failed to register URL, Access is denied

In VS2017. I had to edit my .sln file and had to update the VWDPort = "5010" setting. None of the other solutions posted here worked.

lambda expression join multiple tables with select and where clause

I was looking for something and I found this post. I post this code that managed many-to-many relationships in case someone needs it.

    var UserInRole = db.UsersInRoles.Include(u => u.UserProfile).Include(u => u.Roles)
    .Select (m => new 
    {
        UserName = u.UserProfile.UserName,
        RoleName = u.Roles.RoleName
    });

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

The code below resolved the issue

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls Or SecurityProtocolType.Ssl3

ORA-12516, TNS:listener could not find available handler

You opened a lot of connections and that's the issue. I think in your code, you did not close the opened connection.

A database bounce could temporarily solve, but will re-appear when you do consecutive execution. Also, it should be verified the number of concurrent connections to the database. If maximum DB processes parameter has been reached this is a common symptom.

Courtesy of this thread: https://community.oracle.com/thread/362226?tstart=-1

C# Enum - How to Compare Value

use this

if (userProfile.AccountType == AccountType.Retailer)
{
     ...
}

If you want to get int from your AccountType enum and compare it (don't know why) do this:

if((int)userProfile.AccountType == 1)
{ 
     ...
}

Objet reference not set to an instance of an object exception is because your userProfile is null and you are getting property of null. Check in debug why it's not set.

EDIT (thanks to @Rik and @KonradMorawski) :

Maybe you can do some check before:

if(userProfile!=null)
{
}

or

if(userProfile==null)
{
   throw new ArgumentNullException(nameof(userProfile)); // or any other exception
}

TypeError: Cannot read property "0" from undefined

The while increments the i. So you get:

data[1][0]
data[2][0]
data[3][0]
...

It looks like name doesn't match any of the the elements of data. So, the while still increments and you reach the end of the array. I'll suggest to use for loop.

How can I find out what FOREIGN KEY constraint references a table in SQL Server?

You can also return all the information about the Foreign Keys by adapating @LittleSweetSeas answer:

SELECT 
   OBJECT_NAME(f.parent_object_id) ConsTable,
   OBJECT_NAME (f.referenced_object_id) refTable,
   COL_NAME(fc.parent_object_id,fc.parent_column_id) ColName
FROM 
   sys.foreign_keys AS f
INNER JOIN 
   sys.foreign_key_columns AS fc 
      ON f.OBJECT_ID = fc.constraint_object_id
INNER JOIN 
   sys.tables t 
      ON t.OBJECT_ID = fc.referenced_object_id
order by
ConsTable

How to get info on sent PHP curl request

The request is printed in a request.txt with details

$ch = curl_init();
$f = fopen('request.txt', 'w');
curl_setopt_array($ch, array(
CURLOPT_URL            => $url, 
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_VERBOSE        => 1,
CURLOPT_STDERR         => $f,
));
$response = curl_exec($ch);
fclose($f);
curl_close($ch);

You can also use curl_getinfo() function.

Select multiple records based on list of Id's with linq

Nice answers abowe, but don't forget one IMPORTANT thing - they provide different results!

  var idList = new int[1, 2, 2, 2, 2]; // same user is selected 4 times
  var userProfiles = _dataContext.UserProfile.Where(e => idList.Contains(e)).ToList();

This will return 2 rows from DB (and this could be correct, if you just want a distinct sorted list of users)

BUT in many cases, you could want an unsorted list of results. You always have to think about it like about a SQL query. Please see the example with eshop shopping cart to illustrate what's going on:

  var priceListIDs = new int[1, 2, 2, 2, 2]; // user has bought 4 times item ID 2
  var shoppingCart = _dataContext.ShoppingCart
                     .Join(priceListIDs, sc => sc.PriceListID, pli => pli, (sc, pli) => sc)
                     .ToList();

This will return 5 results from DB. Using 'contains' would be wrong in this case.

Does Python have a toString() equivalent, and can I convert a db.Model element to String?

You should define the __unicode__ method on your model, and the template will call it automatically when you reference the instance.

Android Studio with Google Play Services

Follow this article -> http://developer.android.com/google/play-services/setup.html

You should to choose Using Android Studio

enter image description here

Example Gradle file:

Note: Open the build.gradle file inside your application module directory.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 20
    buildToolsVersion "20.0.0"

    defaultConfig {
        applicationId "{applicationId}"
        minSdkVersion 14
        targetSdkVersion 20
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:20.+'
    compile 'com.google.android.gms:play-services:6.1.+'
}

You can find latest version of Google Play Services here: https://developer.android.com/google/play-services/index.html

Nested or Inner Class in PHP

You cannot do this in PHP. However, there are functional ways to accomplish this.

For more details please check this post: How to do a PHP nested class or nested methods?

This way of implementation is called fluent interface: http://en.wikipedia.org/wiki/Fluent_interface

Spring,Request method 'POST' not supported

Try this

@RequestMapping(value = "proffessional", method = RequestMethod.POST)
    public @ResponseBody
    String forgotPassword(@ModelAttribute("PROFESSIONAL") UserProfessionalForm professionalForm,
            BindingResult result, Model model) {

        UserProfileVO userProfileVO = new UserProfileVO();
        userProfileVO.setUser(sessionData.getUser());
        userService.saveUserProfile(userProfileVO);
        model.addAttribute("professional", professionalForm);
        return "Your Professional Details Updated";
    }

ldap_bind: Invalid Credentials (49)

I don't see an obvious problem with the above.

It's possible your ldap.conf is being overridden, but the command-line options will take precedence, ldapsearch will ignore BINDDN in the main ldap.conf, so the only parameter that could be wrong is the URI. (The order is ETCDIR/ldap.conf then ~/ldaprc or ~/.ldaprc and then ldaprc in the current directory, though there environment variables which can influence this too, see man ldapconf.)

Try an explicit URI:

ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost

or prevent defaults with:

LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd binary for these):

  • make sure your slapd.conf is being used and is correct (as root)

    slapd -T test -f slapd.conf -d 65535

    You may have a left-over or default slapd.d configuration directory which takes preference over your slapd.conf (unless you specify your config explicitly with -f, slapd.conf is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.

  • stop OpenLDAP, then manually start slapd in a separate terminal/console with debug enabled (as root, ^C to quit)

    slapd -h ldap://localhost -d 481

    then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd without the -u/-g options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap )

  • if debug is enabled, then try also

    ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

How can I drop a table if there is a foreign key constraint in SQL Server?

You must drop the constraint before you can drop the table.Other wise its rule violation. How to get foreign key relationships see this old question. SQL DROP TABLE foreign key constraint

Change UITableView height dynamically

Lots of the answers here don't honor changes of the table or are way too complicated. Using a subclass of UITableView that will properly set intrinsicContentSize is a far easier solution when using autolayout. No height constraints etc. needed.

class UIDynamicTableView: UITableView
{
    override var intrinsicContentSize: CGSize {
        self.layoutIfNeeded()
        return CGSize(width: UIViewNoIntrinsicMetric, height: self.contentSize.height)
    }

    override func reloadData() {
        super.reloadData()
        self.invalidateIntrinsicContentSize()
    }
} 

Set the class of your TableView to UIDynamicTableView in the interface builder and watch the magic as this TableView will change it's size after a call to reloadData().

Cannot enqueue Handshake after invoking quit

If you using the node-mysql module, just remove the .connect and .end. Just solved the problem myself. Apparently they pushed in unnecessary code in their last iteration that is also bugged. You don't need to connect if you have already ran the createConnection call

Initialize empty vector in structure - c++

How about

user r = {"",{}};

or

user r = {"",{'\0'}};

or

user r = {"",std::vector<unsigned char>()};

or

user r;

How to get the Display Name Attribute of an Enum member via MVC Razor code?

You could use Type.GetMember Method, then get the attribute info using reflection:

// display attribute of "currentPromotion"

var type = typeof(UserPromotion);
var memberInfo = type.GetMember(currentPromotion.ToString());
var attributes = memberInfo[0].GetCustomAttributes(typeof(DisplayAttribute), false);
var description = ((DisplayAttribute)attributes[0]).Name;

There were a few similar posts here:

Getting attributes of Enum's value

How to make MVC3 DisplayFor show the value of an Enum's Display-Attribute?

LDAP Authentication using Java

You will have to provide the entire user dn in SECURITY_PRINCIPAL

like this

env.put(Context.SECURITY_PRINCIPAL, "cn=username,ou=testOu,o=test"); 

How to find the serial port number on Mac OS X?

I was able to screen using the device's name anyway so that wasn't the issue. I was actually just trying to find the port number, i.e. 5331, 5332 etc. I managed to find this by a trial and error process using an app called TCP2Serial from the app store on Mac OS X. It isn't free but that's fine as long as I know it works!

Worth the 99c :) http://itunes.apple.com/us/app/tcp2serial/id506186902?mt=12

Insert using LEFT JOIN and INNER JOIN

You have to be specific about the columns you are selecting. If your user table had four columns id, name, username, opted_in you must select exactly those four columns from the query. The syntax looks like:

INSERT INTO user (id, name, username, opted_in)
  SELECT id, name, username, opted_in 
  FROM user LEFT JOIN user_permission AS userPerm ON user.id = userPerm.user_id

However, there does not appear to be any reason to join against user_permission here, since none of the columns from that table would be inserted into user. In fact, this INSERT seems bound to fail with primary key uniqueness violations.

MySQL does not support inserts into multiple tables at the same time. You either need to perform two INSERT statements in your code, using the last insert id from the first query, or create an AFTER INSERT trigger on the primary table.

INSERT INTO user (name, username, email, opted_in) VALUES ('a','b','c',0);
/* Gets the id of the new row and inserts into the other table */
INSERT INTO user_permission (user_id, permission_id) VALUES (LAST_INSERT_ID(), 4)

Or using a trigger:

CREATE TRIGGER creat_perms AFTER INSERT ON `user`
FOR EACH ROW
BEGIN
  INSERT INTO user_permission (user_id, permission_id) VALUES (NEW.id, 4)
END

How to "log in" to a website using Python's Requests module?

The requests.Session() solution assisted with logging into a form with CSRF Protection (as used in Flask-WTF forms). Check if a csrf_token is required as a hidden field and add it to the payload with the username and password:

import requests
from bs4 import BeautifulSoup

payload = {
    'email': '[email protected]',
    'password': 'passw0rd'
}     

with requests.Session() as sess:
    res = sess.get(server_name + '/signin')
    signin = BeautifulSoup(res._content, 'html.parser')
    payload['csrf_token'] = signin.find('input', id='csrf_token')['value']
    res = sess.post(server_name + '/auth/login', data=payload)

Find all files in a folder

First off; best practice would be to get the users Desktop folder with

string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

Then you can find all the files with something like

string[] files = Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories);

Note that with the above line you will find all files with a .txt extension in the Desktop folder of the logged in user AND all subfolders.

Then you could copy or move the files by enumerating the above collection like

// For copying...
foreach (string s in files)
{
   File.Copy(s, "C:\newFolder\newFilename.txt");
}

// ... Or for moving
foreach (string s in files)
{
   File.Move(s, "C:\newFolder\newFilename.txt");
}

Please note that you will have to include the filename in your Copy() (or Move()) operation. So you would have to find a way to determine the filename of at least the extension you are dealing with and not name all the files the same like what would happen in the above example.

With that in mind you could also check out the DirectoryInfo and FileInfo classes. These work in similair ways, but you can get information about your path-/filenames, extensions, etc. more easily

Check out these for more info:

http://msdn.microsoft.com/en-us/library/system.io.directory.aspx

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

http://msdn.microsoft.com/en-us/library/system.io.file.aspx

Chrome javascript debugger breakpoints don't do anything?

Make sure the script with the "debugger;" statement in it is not blackboxed by Chrome. You can go to the Sources tab to check and turn off blackboxing if so.

EDIT: Added screenshot.

How to turn off blackboxing.

Creating a thumbnail from an uploaded image

<?php 
error_reporting(0);

$change="";
$abc="";


 define ("MAX_SIZE","4000");
 function getExtension($str) {
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
 }

 $errors=0;

 if($_SERVER["REQUEST_METHOD"] == "POST")
 {
    $image =$_FILES["file"]["name"];
    $uploadedfile = $_FILES['file']['tmp_name'];


    if ($image) 
    {

        $filename = stripslashes($_FILES['file']['name']);

        $extension = getExtension($filename);
        $extension = strtolower($extension);


 if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
        {

            $change='<div class="msgdiv">Unknown Image extension </div> ';
            $errors=1;
        }
        else
        {

 $size=filesize($_FILES['file']['tmp_name']);


if ($size > MAX_SIZE*1024)
{
    $change='<div class="msgdiv">You have exceeded the size limit!</div> ';
    $errors=1;
}


if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);

}
else if($extension=="png")
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);

}
else 
{
$src = imagecreatefromgif($uploadedfile);
}

echo $scr;

list($width,$height)=getimagesize($uploadedfile);


$newwidth=45;
$newheight=45;
$tmp=imagecreatetruecolor($newwidth,$newheight);


$newwidth1=90;
$newheight1=90;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);

$tmp2=imagecreatetruecolor($width,$height);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);

imagecopyresampled($tmp2,$src,0,0,0,0,$width,$height,$width,$height);

$filename = "images/1-". $_FILES['file']['name']=time();

$filename1 = "images/2-". $_FILES['file']['name']=time();

$filename2 = "images/3-". $_FILES['file']['name']=time();

imagejpeg($tmp,$filename,100);

imagejpeg($tmp1,$filename1,100);

imagejpeg($tmp2,$filename2,100);

imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}}

}
 if(isset($_POST['Submit']) && !$errors) 
 {

   // mysql_query("update {$prefix}users set img='$big',img_small='$small' where user_id='$user'");
    $change=' <div class="msgdiv">Image Uploaded Successfully!</div>';
 }

?>
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en"><head>
    <title>picture demo</title>

   <link href=".css" media="screen, projection" rel="stylesheet" type="text/css">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery_002.js"></script>
<script type="text/javascript" src="js/displaymsg.js"></script>
<script type="text/javascript" src="js/ajaxdelete.js"></script>


  <style type="text/css">
  .help
{
font-size:11px; color:#006600;
}
body {
     color: #000000;
 background-color:#999999 ;
    background:#999999 url(<?php echo $user_row['img_src']; ?>) fixed repeat top left;


    font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif; 

    }
        .msgdiv{
    width:759px;
padding-top:8px;
padding-bottom:8px;
background-color: #fff;
font-weight:bold;
font-size:18px;-moz-border-radius: 6px;-webkit-border-radius: 6px;
}
#container{width:763px;margin:0 auto;padding:3px 0;text-align:left;position:relative; -moz-border-radius: 6px;-webkit-border-radius: 6px; background-color:#FFFFFF }
</style>

  </head><body>
     <div align="center" id="err">
<?php echo $change; ?>  </div>
   <div id="space"></div>





  <div id="container" >

   <div id="con">



        <table width="502" cellpadding="0" cellspacing="0" id="main">
          <tbody>
            <tr>
              <td width="500" height="238" valign="top" id="main_right">

              <div id="posts">
              &nbsp;&nbsp;&nbsp;&nbsp;<img src="<?php// echo $filename; ?>" />  &nbsp;&nbsp;&nbsp;&nbsp;<img src="<?php// echo $filename1; ?>"  />
                <form method="post" action="" enctype="multipart/form-data" name="form1">
                <table width="500" border="0" align="center" cellpadding="0" cellspacing="0">
               <tr><Td style="height:25px">&nbsp;</Td></tr>
        <tr>
          <td width="150"><div align="right" class="titles">Picture 
            : </div></td>
          <td width="350" align="left">
            <div align="left">
              <input size="25" name="file" type="file" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10pt" class="box"/>

              </div></td>

        </tr>
        <tr><Td></Td>
        <Td valign="top" height="35px" class="help">Image maximum size <b>4000 </b>kb</span></Td>
        </tr>
        <tr><Td></Td><Td valign="top" height="35px"><input type="submit" id="mybut" value="       Upload        " name="Submit"/></Td></tr>
        <tr>
          <td width="200">&nbsp;</td>
          <td width="200"><table width="200" border="0" cellspacing="0" cellpadding="0">
              <tr>
                <td width="200" align="center"><div align="left"></div></td>
                <td width="100">&nbsp;</td>
              </tr>
          </table></td>
        </tr>
      </table>
    </form>
 </div>
            </td>

        </tr>
          </tbody>
     </table>
   </div>

  </div>



</body></html>

How to create a user in Django?

Have you confirmed that you are passing actual values and not None?

from django.shortcuts import render

def createUser(request):
    userName = request.REQUEST.get('username', None)
    userPass = request.REQUEST.get('password', None)
    userMail = request.REQUEST.get('email', None)

    # TODO: check if already existed
    if userName and userPass and userMail:
       u,created = User.objects.get_or_create(userName, userMail)
       if created:
          # user was created
          # set the password here
       else:
          # user was retrieved
    else:
       # request was empty

    return render(request,'home.html')

ALTER TABLE add constraint

ALTER TABLE `User`
ADD CONSTRAINT `user_properties_foreign`
FOREIGN KEY (`properties`)
REFERENCES `Properties` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;

How to do a less than or equal to filter in Django queryset?

Less than or equal:

User.objects.filter(userprofile__level__lte=0)

Greater than or equal:

User.objects.filter(userprofile__level__gte=0)

Likewise, lt for less than and gt for greater than. You can find them all in the documentation.

What's the proper way to compare a String to an enum value?

You should declare toString() and valueOf() method in enum.

 import java.io.Serializable;

public enum Gesture implements Serializable {
    ROCK,PAPER,SCISSORS;

    public String toString(){
        switch(this){
        case ROCK :
            return "Rock";
        case PAPER :
            return "Paper";
        case SCISSORS :
            return "Scissors";
        }
        return null;
    }

    public static Gesture valueOf(Class<Gesture> enumType, String value){
        if(value.equalsIgnoreCase(ROCK.toString()))
            return Gesture.ROCK;
        else if(value.equalsIgnoreCase(PAPER.toString()))
            return Gesture.PAPER;
        else if(value.equalsIgnoreCase(SCISSORS.toString()))
            return Gesture.SCISSORS;
        else
            return null;
    }
}

Why is my locally-created script not allowed to run under the RemoteSigned execution policy?

When you run a .ps1 PowerShell script you might get the message saying “.ps1 is not digitally signed. The script will not execute on the system.” To fix it you have to run the command below to run Set-ExecutionPolicy and change the Execution Policy setting.

Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing

In my case setting the referenced object to NULL in my object before the merge o save method solve the problem, in my case the referenced object was catalog, that doesn't need to be saved, because in some cases I don't have it even.

    fisEntryEB.setCatStatesEB(null);

    (fisEntryEB) getSession().merge(fisEntryEB);

How to run batch file from network share without "UNC path are not supported" message?

This is the RegKey I used:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor]
"DisableUNCCheck"=dword:00000001

Getting input values from text box

Remove the id="pass" off the td element. Right now the js will get the td element instead of the input hence the value is undefined.

How can I find out if an .EXE has Command-Line Options?

Invoke it from the shell, with an argument like /? or --help. Those are the usual help switches.

drag drop files into standard html file input

This is the "DTHML" HTML5 way to do it. Normal form input (which IS read only as Ricardo Tomasi pointed out). Then if a file is dragged in, it is attached to the form. This WILL require modification to the action page to accept the file uploaded this way.

_x000D_
_x000D_
function readfiles(files) {_x000D_
  for (var i = 0; i < files.length; i++) {_x000D_
    document.getElementById('fileDragName').value = files[i].name_x000D_
    document.getElementById('fileDragSize').value = files[i].size_x000D_
    document.getElementById('fileDragType').value = files[i].type_x000D_
    reader = new FileReader();_x000D_
    reader.onload = function(event) {_x000D_
      document.getElementById('fileDragData').value = event.target.result;}_x000D_
    reader.readAsDataURL(files[i]);_x000D_
  }_x000D_
}_x000D_
var holder = document.getElementById('holder');_x000D_
holder.ondragover = function () { this.className = 'hover'; return false; };_x000D_
holder.ondragend = function () { this.className = ''; return false; };_x000D_
holder.ondrop = function (e) {_x000D_
  this.className = '';_x000D_
  e.preventDefault();_x000D_
  readfiles(e.dataTransfer.files);_x000D_
}
_x000D_
#holder.hover { border: 10px dashed #0c0 !important; }
_x000D_
<form method="post" action="http://example.com/">_x000D_
  <input type="file"><input id="fileDragName"><input id="fileDragSize"><input id="fileDragType"><input id="fileDragData">_x000D_
  <div id="holder" style="width:200px; height:200px; border: 10px dashed #ccc"></div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

It is even more boss if you can make the whole window a drop zone, see How do I detect a HTML5 drag event entering and leaving the window, like Gmail does?

WCF named pipe minimal example

Try this.

Here is the service part.

[ServiceContract]
public interface IService
{
    [OperationContract]
    void  HelloWorld();
}

public class Service : IService
{
    public void HelloWorld()
    {
        //Hello World
    }
}

Here is the Proxy

public class ServiceProxy : ClientBase<IService>
{
    public ServiceProxy()
        : base(new ServiceEndpoint(ContractDescription.GetContract(typeof(IService)),
            new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/MyAppNameThatNobodyElseWillUse/helloservice")))
    {

    }
    public void InvokeHelloWorld()
    {
        Channel.HelloWorld();
    }
}

And here is the service hosting part.

var serviceHost = new ServiceHost
        (typeof(Service), new Uri[] { new Uri("net.pipe://localhost/MyAppNameThatNobodyElseWillUse") });
    serviceHost.AddServiceEndpoint(typeof(IService), new NetNamedPipeBinding(), "helloservice");
    serviceHost.Open();

    Console.WriteLine("Service started. Available in following endpoints");
    foreach (var serviceEndpoint in serviceHost.Description.Endpoints)
    {
        Console.WriteLine(serviceEndpoint.ListenUri.AbsoluteUri);
    }

"A referral was returned from the server" exception when accessing AD from C#

A referral is sent by an AD server when it doesn't have the information requested itself, but know that another server have the info. It usually appears in trust environment where a DC can refer to a DC in trusted domain.

In your case you are only specifying a domain, relying on automatic lookup of what domain controller to use. I think that you should try to find out what domain controller is used for the query and look if that one really holds the requested information.

If you provide more information on your AD setup, including any trusts/subdomains, global catalogues and the DNS resource records for the domain controllers it will be easier to help you.

How to check if a column is empty or null using SQL query select statement?

An answer above got me 99% of the way there (thanks Denis Ivin!). For my PHP / MySQL implementation, I needed to change the syntax a little:

SELECT *
FROM UserProfile
WHERE PropertydefinitionID in (40, 53)
AND (LENGTH(IFNULL(PropertyValue,'')) = 0)

LEN becomes LENGTH and ISNULL becomes IFNULL.

Transparent background on winforms?

Here was my solution:

In the constructors add these two lines:

this.BackColor = Color.LimeGreen;
this.TransparencyKey = Color.LimeGreen;

In your form, add this method:

protected override void OnPaintBackground(PaintEventArgs e)
{
    e.Graphics.FillRectangle(Brushes.LimeGreen, e.ClipRectangle);
}

Be warned, not only is this form fully transparent inside the frame, but you can also click through it. However, it might be cool to draw an image onto it and make the form able to be dragged everywhere to create a custom shaped form.

Render partial view with dynamic model in Razor view engine and ASP.NET MVC 3

There's another reason that this can be thrown, even if you're not using dynamic/ExpandoObject. If you are doing a loop, like this:

@foreach (var folder in ViewBag.RootFolder.ChildFolders.ToList())
{
    @Html.Partial("ContentFolderTreeViewItems", folder)
}

In that case, the "var" instead of the type declaration will throw the same error, despite the fact that RootFolder is of type "Folder. By changing the var to the actual type, the problem goes away.

@foreach (ContentFolder folder in ViewBag.RootFolder.ChildFolders.ToList())
{
    @Html.Partial("ContentFolderTreeViewItems", folder)
}

Do I really need to encode '&' as '&amp;'?

The link has a fairly good example of when and why you may need to escape & to &amp;

https://jsfiddle.net/vh2h7usk/1/

Interestingly, I had to escape the character in order to represent it properly in my answer here. If I were to use the built-in code sample option (from the answer panel), I can just type in &amp; and it appears as it should. But if I were to manually use the <code></code> element, then I have to escape in order to represent it correctly :)

codeigniter model error: Undefined property

function user() { 

       parent::Model(); 

} 

=> class name is User, construct name is User.

function User() { 

       parent::Model(); 

} 

How to add two edit text fields in an alert dialog

Check this code in alert box have edit textview when click OK it displays on screen using toast.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final AlertDialog.Builder alert = new AlertDialog.Builder(this);
    final EditText input = new EditText(this);
    alert.setView(input);
    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            String value = input.getText().toString().trim();
            Toast.makeText(getApplicationContext(), value, 
                Toast.LENGTH_SHORT).show();
        }
    });

    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            dialog.cancel();
        }
    });
    alert.show();               
}

Set HTML dropdown selected option using JSTL

Real simple. You just need to have the string 'selected' added to the right option. In the following code, ${myBean.foo == val ? 'selected' : ' '} will add the string 'selected' if the option's value is the same as the bean value;

<select name="foo" id="foo" value="${myBean.foo}">
    <option value="">ALL</option>
    <c:forEach items="${fooList}" var="val"> 
        <option value="${val}" ${myBean.foo == val ? 'selected' : ' '}><c:out value="${val}" ></c:out></option>   
    </c:forEach>                     
</select>

Setting Curl's Timeout in PHP

Your code sets the timeout to 1000 seconds. For milliseconds, use CURLOPT_TIMEOUT_MS.

"Invalid JSON primitive" in Ajax processing

On the Server, to Serialize/Deserialize json to custom objects:

public static string Serialize<T>(T obj)
{
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    MemoryStream ms = new MemoryStream();
    serializer.WriteObject(ms, obj);
    string retVal = Encoding.UTF8.GetString(ms.ToArray());
    return retVal;
}

public static T Deserialize<T>(string json)
{
    T obj = Activator.CreateInstance<T>();
    MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    obj = (T)serializer.ReadObject(ms);
    ms.Close();
    return obj;
}

How do a LDAP search/authenticate against this LDAP in Java

try {
    LdapContext ctx = new InitialLdapContext(env, null);
    ctx.setRequestControls(null);
    NamingEnumeration<?> namingEnum = ctx.search("ou=people,dc=example,dc=com", "(objectclass=user)", getSimpleSearchControls());
    while (namingEnum.hasMore ()) {
        SearchResult result = (SearchResult) namingEnum.next ();    
        Attributes attrs = result.getAttributes ();
        System.out.println(attrs.get("cn"));

    } 
    namingEnum.close();
} catch (Exception e) {
    e.printStackTrace();
}

private SearchControls getSimpleSearchControls() {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setTimeLimit(30000);
    //String[] attrIDs = {"objectGUID"};
    //searchControls.setReturningAttributes(attrIDs);
    return searchControls;
}

What's the environment variable for the path to the desktop?

TL;DR

%HOMEDRIVE%%HOMEPATH%\Desktop seems to be the safest way.

Discussion

Assumptions about which drive a thing is on are quite fragile in Windows as it lacks a unified directory tree where mounts would map to directories internally. Therefore the %HOMEDRIVE% variable is important to reference to make sure you're on the right one (it isn't always C:\!).

Non-English locales will usually have localized names for things like "Desktop" and "Pictures" and whatnot, but fortunately they are all aliases that point to Desktop, which seems to be the underlying canonical directory name regardless of locale (we use this safely here in Japan, Thailand, Israel and the US).

The big quirk comes with determining whether %UserProfile% points to the user's actual profile base dir, or their Desktop or somewhere completely different. I'm not really a Windows dev, but what I've found is the profile dir is for settings, but the %HOMEPATH% is for the user's own files, so this points to the directory root that leads to Desktop/Downloads/Pictures/etc. This tends to make %HOMEDRIVE%%HOMEPATH%\Desktop the safest way.

Send a file via HTTP POST with C#

I had got the same problem and this following code answered perfectly at this problem :

//Identificate separator
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
//Encoding
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

//Creation and specification of the request
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url); //sVal is id for the webService
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;

string sAuthorization = "login:password";//AUTHENTIFICATION BEGIN
byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(sAuthorization);
string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
wr.Headers.Add("Authorization: Basic " + returnValue); //AUTHENTIFICATION END
Stream rs = wr.GetRequestStream();


string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; //For the POST's format

//Writting of the file
rs.Write(boundarybytes, 0, boundarybytes.Length);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(Server.MapPath("questions.pdf"));
rs.Write(formitembytes, 0, formitembytes.Length);

rs.Write(boundarybytes, 0, boundarybytes.Length);

string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, "file", "questions.pdf", contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);

FileStream fileStream = new FileStream(Server.MapPath("questions.pdf"), FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
    rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();

byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
rs = null;

WebResponse wresp = null;
try
{
    //Get the response
    wresp = wr.GetResponse();
    Stream stream2 = wresp.GetResponseStream();
    StreamReader reader2 = new StreamReader(stream2);
    string responseData = reader2.ReadToEnd();
}
catch (Exception ex)
{
    string s = ex.Message;
}
finally
{
    if (wresp != null)
    {
        wresp.Close();
        wresp = null;
    }
    wr = null;
}

Get login username in java

I tested in linux centos

Map<String, String> env = System.getenv();   
for (String envName : env.keySet()) { 
 System.out.format("%s=%s%n", envName, env.get(envName)); 
}

System.out.println(env.get("USERNAME")); 

How to get the current user's Active Directory details in C#

Add reference to COM "Active DS Type Library"


            Int32 nameTypeNT4               = (int) ActiveDs.ADS_NAME_TYPE_ENUM.ADS_NAME_TYPE_NT4;
            Int32 nameTypeDN                = (int) ActiveDs.ADS_NAME_TYPE_ENUM.ADS_NAME_TYPE_1779;
            Int32 nameTypeUserPrincipalName = (int) ActiveDs.ADS_NAME_TYPE_ENUM.ADS_NAME_TYPE_USER_PRINCIPAL_NAME;

            ActiveDs.NameTranslate nameTranslate = new ActiveDs.NameTranslate();

            // Convert NT name DOMAIN\User into AD distinguished name 
            // "CN= User\\, Name,OU=IT,OU=All Users,DC=Company,DC=com"
            nameTranslate.Set(nameTypeNT4, ntUser);

            String distinguishedName = nameTranslate.Get(nameTypeDN);

            Console.WriteLine(distinguishedName);

            // Convert AD distinguished name "CN= User\\, Name,OU=IT,OU=All Users,DC=Company,DC=com" 
            // into NT name DOMAIN\User
            ntUser = String.Empty;
            nameTranslate.Set(nameTypeDN, distinguishedName);
            ntUser = nameTranslate.Get(nameTypeNT4);
            Console.WriteLine(ntUser);

            // Convert NT name DOMAIN\User into AD UserPrincipalName [email protected]
            nameTranslate.Set(nameTypeNT4, ntUser);
            String userPrincipalName = nameTranslate.Get(nameTypeUserPrincipalName);

            Console.WriteLine(userPrincipalName);

Cannot delete directory with Directory.Delete(path, true)

Recursive directory deletion that does not delete files is certainly unexpected. My fix for that:

public class IOUtils
{
    public static void DeleteDirectory(string directory)
    {
        Directory.GetFiles(directory, "*", SearchOption.AllDirectories).ForEach(File.Delete);
        Directory.Delete(directory, true);
    }
}

I experienced cases where this helped, but generally, Directory.Delete deletes files inside directories upon recursive deletion, as documented in msdn.

From time to time I encounter this irregular behavior also as a user of Windows Explorer: Sometimes I cannot delete a folder (it think the nonsensical message is "access denied") but when I drill down and delete lower items I can then delete the upper items as well. So I guess the code above deals with an OS anomaly - not with a base class library issue.

Parse usable Street Address, City, State, Zip from a string

using google API

$d=str_replace(" ", "+", $address_url);
$completeurl ="http://maps.googleapis.com/maps/api/geocode/xml?address=".$d."&sensor=true"; 
$phpobject = simplexml_load_file($completeurl);
print_r($phpobject);

deleting rows in numpy array

import numpy as np 
arr = np.array([[ 0.96488889, 0.73641667, 0.67521429, 0.592875, 0.53172222],[ 0.78008333, 0.5938125, 0.481, 0.39883333, 0.]])
print(arr[np.where(arr != 0.)])

Exception in thread "main" java.lang.Error: Unresolved compilation problems

Check Following : 1) Package names 2) Import Statements (import every required packages) 3) Proper set of braces ,i.e { } 4) Check Syntax too.. i.e semicolons,commas,etc.

Redirect to a page/URL after alert button is pressed

You're missing semi-colons after your javascript lines. Also, window.location should have .href or .replace etc to redirect - See this post for more information.

echo '<script type="text/javascript">'; 
echo 'alert("review your answer");'; 
echo 'window.location.href = "index.php";';
echo '</script>';

For clarity, try leaving PHP tags for this:

?>
<script type="text/javascript">
alert("review your answer");
window.location.href = "index.php";
</script>
<?php

NOTE: semi colons on seperate lines are optional, but encouraged - however as in the comments below, PHP won't break lines in the first example here but will in the second, so semi-colons are required in the first example.

Running Selenium WebDriver python bindings in chrome

You need to make sure the standalone ChromeDriver binary (which is different than the Chrome browser binary) is either in your path or available in the webdriver.chrome.driver environment variable.

see http://code.google.com/p/selenium/wiki/ChromeDriver for full information on how wire things up.

Edit:

Right, seems to be a bug in the Python bindings wrt reading the chromedriver binary from the path or the environment variable. Seems if chromedriver is not in your path you have to pass it in as an argument to the constructor.

import os
from selenium import webdriver

chromedriver = "/Users/adam/Downloads/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.Chrome(chromedriver)
driver.get("http://stackoverflow.com")
driver.quit()

Should C# or C++ be chosen for learning Games Programming (consoles)?

To tell the truth...you have to make the decision as to which is the better language. I know what I can do with C#. I know what can be done in C++. C# isn't made to do what C++ was made to do...write code at the most basic level and still be somewhat meaningful when read by human eyes.

We are developing a game engine with C#, DirectX...is it a challenge? hell yeah...but it's something we chose to do. We are looking at some performance levels that are very close to what C++ can give. So, I see no problems with this effort.

To cross-platform development, if it weren't for .Net, we might not have the Mono platform. The Mono platform has broadened our platform base.

Here is some support to my arguments...

getting the ng-object selected with ng-change

You can also directly get selected value using following code

 <select ng-options='t.name for t in templates'
                  ng-change='selectedTemplate(t.url)'></select>

script.js

 $scope.selectedTemplate = function(pTemplate) {
    //Your logic
    alert('Template Url is : '+pTemplate);
}

Get list of passed arguments in Windows batch script (.bat)

Here is a fairly simple way to get the args and set them as env vars. In this example I will just refer to them as Keys and Values.

Save the following code example as "args.bat". Then call the batch file you saved from a command line. example: arg.bat --x 90 --y 120

I have provided some echo commands to step you through the process. But the end result is that --x will have a value of 90 and --y will have a value of 120(that is if you run the example as specified above ;-) ).

You can then use the 'if defined' conditional statement to determine whether or not to run your code block. So lets say run: "arg.bat --x hello-world" I could then use the statement "IF DEFINED --x echo %--x%" and the results would be "hello-world". It should make more sense if you run the batch.

@setlocal enableextensions enabledelayedexpansion
@ECHO off
ECHO.
ECHO :::::::::::::::::::::::::: arg.bat example :::::::::::::::::::::::::::::::
ECHO :: By:      User2631477, 2013-07-29                                   ::
ECHO :: Version: 1.0                                                         ::
ECHO :: Purpose: Checks the args passed to the batch.                        ::
ECHO ::                                                                      ::
ECHO :: Start by gathering all the args with the %%* in a for loop.          ::
ECHO ::                                                                      ::
ECHO :: Now we use a 'for' loop to search for our keys which are identified  ::
ECHO :: by the text '--'. The function then sets the --arg ^= to the next    ::
ECHO :: arg. "CALL:Function_GetValue" ^<search for --^> ^<each arg^>         ::
ECHO ::                                                                      ::
ECHO ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

ECHO.

ECHO ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
ECHO :: From the command line you could pass... arg.bat --x 90 --y 220       ::
ECHO ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
ECHO.
ECHO.Checking Args:"%*"

FOR %%a IN (%*) do (
    CALL:Function_GetValue "--","%%a" 
)

ECHO.
ECHO ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
ECHO :: Now lets check which args were set to variables...                   ::
ECHO ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
ECHO.
ECHO ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
ECHO :: For this we are using the CALL:Function_Show_Defined "--x,--y,--z"   ::
ECHO ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
ECHO.
CALL:Function_Show_Defined "--x,--y,--z"
endlocal
goto done

:Function_GetValue

REM First we use find string to locate and search for the text.
echo.%~2 | findstr /C:"%~1" 1>nul

REM Next we check the errorlevel return to see if it contains a key or a value
REM and set the appropriate action.

if not errorlevel 1 (
  SET KEY=%~2
) ELSE (
  SET VALUE=%~2
)
IF DEFINED VALUE (
    SET %KEY%=%~2
    ECHO.
    ECHO ::::::::::::::::::::::::: %~0 ::::::::::::::::::::::::::::::
    ECHO :: The KEY:'%KEY%' is now set to the VALUE:'%VALUE%'                     ::
    ECHO :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    ECHO.
    ECHO %KEY%=%~2
    ECHO.
    REM It's important to clear the definitions for the key and value in order to
    REM search for the next key value set.
    SET KEY=
    SET VALUE=
)
GOTO:EOF

:Function_Show_Defined 
ECHO.
ECHO ::::::::::::::::::: %~0 ::::::::::::::::::::::::::::::::
ECHO :: Checks which args were defined i.e. %~2
ECHO :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
ECHO.
SET ARGS=%~1
for %%s in (%ARGS%) DO (
    ECHO.
    ECHO :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    ECHO :: For the ARG: '%%s'                         
    IF DEFINED %%s (
        ECHO :: Defined as: '%%s=!%%s!'                                             
    ) else (
        ECHO :: Not Defined '%%s' and thus has no value.
    )
    ECHO :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    ECHO.
)
goto:EOF

:done

How to change the color of an image on hover

Use the background-color property instead of the background property in your CSS. So your code will look like this:
.fb-icon:hover {
background: blue;
}

How can I check if a string only contains letters in Python?

The str.isalpha() function works. ie.

if my_string.isalpha():
    print('it is letters')

What's the best way to override a user agent CSS stylesheet rule that gives unordered-lists a 1em margin?

put this in your "head" of your index.html

 <style>
  html body{
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    margin: 0;
  }
  </style>

Check if a string is null or empty in XSLT

If there is a possibility that the element does not exist in the XML I would test both that the element is present and that the string-length is greater than zero:

<xsl:choose>
    <xsl:when test="categoryName and string-length(categoryName) &gt; 0">
        <xsl:value-of select="categoryName " />
    </xsl:when>
    <xsl:otherwise>
        <xsl:value-of select="other" />
    </xsl:otherwise>
</xsl:choose>

Entity Framework Provider type could not be loaded?

remove the entity framework from the project via nuget then add it back in.

Could not commit JPA transaction: Transaction marked as rollbackOnly

Save sub object first and then call final repository save method.

@PostMapping("/save")
    public String save(@ModelAttribute("shortcode") @Valid Shortcode shortcode, BindingResult result) {
        Shortcode existingShortcode = shortcodeService.findByShortcode(shortcode.getShortcode());
        if (existingShortcode != null) {
            result.rejectValue(shortcode.getShortcode(), "This shortode is already created.");
        }
        if (result.hasErrors()) {
            return "redirect:/shortcode/create";
        }
        **shortcode.setUser(userService.findByUsername(shortcode.getUser().getUsername()));**
        shortcodeService.save(shortcode);
        return "redirect:/shortcode/create?success";
    }

Split large string in n-size chunks in JavaScript

You can use reduce() without any regex:

(str, n) => {
  return str.split('').reduce(
    (acc, rec, index) => {
      return ((index % n) || !(index)) ? acc.concat(rec) : acc.concat(',', rec)
    },
    ''
  ).split(',')
}

jQuery: set selected value of dropdown list?

UPDATED ANSWER:

Old answer, correct method nowadays is to use jQuery's .prop(). IE, element.prop("selected", true)

OLD ANSWER:

Use this instead:

$("#routetype option[value='quietest']").attr("selected", "selected");

Fiddle'd: http://jsfiddle.net/x3UyB/4/

How to expire a cookie in 30 minutes using jQuery?

If you're using jQuery Cookie (https://plugins.jquery.com/cookie/), you can use decimal point or fractions.

As one day is 1, one minute would be 1 / 1440 (there's 1440 minutes in a day).

So 30 minutes is 30 / 1440 = 0.02083333.

Final code:

$.cookie("example", "foo", { expires: 30 / 1440, path: '/' });

I've added path: '/' so that you don't forget that the cookie is set on the current path. If you're on /my-directory/ the cookie is only set for this very directory.

How do you set, clear, and toggle a single bit?

Let suppose few things first
num = 55 Integer to perform bitwise operations (set, get, clear, toggle).
n = 4 0 based bit position to perform bitwise operations.

How to get a bit?

  1. To get the nth bit of num right shift num, n times. Then perform bitwise AND & with 1.
bit = (num >> n) & 1;

How it works?

       0011 0111 (55 in decimal)
    >>         4 (right shift 4 times)
-----------------
       0000 0011
     & 0000 0001 (1 in decimal)
-----------------
    => 0000 0001 (final result)

How to set a bit?

  1. To set a particular bit of number. Left shift 1 n times. Then perform bitwise OR | operation with num.
num |= (1 << n);    // Equivalent to; num = (1 << n) | num;

How it works?

       0000 0001 (1 in decimal)
    <<         4 (left shift 4 times)
-----------------
       0001 0000
     | 0011 0111 (55 in decimal)
-----------------
    => 0001 0000 (final result)

How to clear a bit?

  1. Left shift 1, n times i.e. 1 << n.
  2. Perform bitwise complement with the above result. So that the nth bit becomes unset and rest of bit becomes set i.e. ~ (1 << n).
  3. Finally, perform bitwise AND & operation with the above result and num. The above three steps together can be written as num & (~ (1 << n));

Steps to clear a bit

num &= (~(1 << n));    // Equivalent to; num = num & (~(1 << n));

How it works?

       0000 0001 (1 in decimal)
    <<         4 (left shift 4 times)
-----------------
     ~ 0001 0000
-----------------
       1110 1111
     & 0011 0111 (55 in decimal)
-----------------
    => 0010 0111 (final result)

How to toggle a bit?

To toggle a bit we use bitwise XOR ^ operator. Bitwise XOR operator evaluates to 1 if corresponding bit of both operands are different, otherwise evaluates to 0.

Which means to toggle a bit, we need to perform XOR operation with the bit you want to toggle and 1.

num ^= (1 << n);    // Equivalent to; num = num ^ (1 << n);

How it works?

  • If the bit to toggle is 0 then, 0 ^ 1 => 1.
  • If the bit to toggle is 1 then, 1 ^ 1 => 0.
       0000 0001 (1 in decimal)
    <<         4 (left shift 4 times)
-----------------
       0001 0000
     ^ 0011 0111 (55 in decimal)
-----------------
    => 0010 0111 (final result)

Recommended reading - Bitwise operator exercises

What is a monad?

Explaining "what is a monad" is a bit like saying "what is a number?" We use numbers all the time. But imagine you met someone who didn't know anything about numbers. How the heck would you explain what numbers are? And how would you even begin to describe why that might be useful?

What is a monad? The short answer: It's a specific way of chaining operations together.

In essence, you're writing execution steps and linking them together with the "bind function". (In Haskell, it's named >>=.) You can write the calls to the bind operator yourself, or you can use syntax sugar which makes the compiler insert those function calls for you. But either way, each step is separated by a call to this bind function.

So the bind function is like a semicolon; it separates the steps in a process. The bind function's job is to take the output from the previous step, and feed it into the next step.

That doesn't sound too hard, right? But there is more than one kind of monad. Why? How?

Well, the bind function can just take the result from one step, and feed it to the next step. But if that's "all" the monad does... that actually isn't very useful. And that's important to understand: Every useful monad does something else in addition to just being a monad. Every useful monad has a "special power", which makes it unique.

(A monad that does nothing special is called the "identity monad". Rather like the identity function, this sounds like an utterly pointless thing, yet turns out not to be... But that's another story™.)

Basically, each monad has its own implementation of the bind function. And you can write a bind function such that it does hoopy things between execution steps. For example:

  • If each step returns a success/failure indicator, you can have bind execute the next step only if the previous one succeeded. In this way, a failing step aborts the whole sequence "automatically", without any conditional testing from you. (The Failure Monad.)

  • Extending this idea, you can implement "exceptions". (The Error Monad or Exception Monad.) Because you're defining them yourself rather than it being a language feature, you can define how they work. (E.g., maybe you want to ignore the first two exceptions and only abort when a third exception is thrown.)

  • You can make each step return multiple results, and have the bind function loop over them, feeding each one into the next step for you. In this way, you don't have to keep writing loops all over the place when dealing with multiple results. The bind function "automatically" does all that for you. (The List Monad.)

  • As well as passing a "result" from one step to another, you can have the bind function pass extra data around as well. This data now doesn't show up in your source code, but you can still access it from anywhere, without having to manually pass it to every function. (The Reader Monad.)

  • You can make it so that the "extra data" can be replaced. This allows you to simulate destructive updates, without actually doing destructive updates. (The State Monad and its cousin the Writer Monad.)

  • Because you're only simulating destructive updates, you can trivially do things that would be impossible with real destructive updates. For example, you can undo the last update, or revert to an older version.

  • You can make a monad where calculations can be paused, so you can pause your program, go in and tinker with internal state data, and then resume it.

  • You can implement "continuations" as a monad. This allows you to break people's minds!

All of this and more is possible with monads. Of course, all of this is also perfectly possible without monads too. It's just drastically easier using monads.

How to navigate to to different directories in the terminal (mac)?

To check that the file you're trying to open actually exists, you can change directories in terminal using cd. To change to ~/Desktop/sass/css: cd ~/Desktop/sass/css. To see what files are in the directory: ls.

If you want information about either of those commands, use the man page: man cd or man ls, for example.

Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.

On Mac OS X, you can also use open to open a finder window: open . will open the current directory in finder. (open ~/Desktop/sass/css will open the ~/Desktop/sass/css).

VBA - how to conditionally skip a for loop iteration

Hi I am also facing this issue and I solve this using below example code

For j = 1 To MyTemplte.Sheets.Count

       If MyTemplte.Sheets(j).Visible = 0 Then
           GoTo DoNothing        
       End If 


'process for this for loop
DoNothing:

Next j 

How to define a relative path in java

Try something like this

String filePath = new File("").getAbsolutePath();
filePath.concat("path to the property file");

So your new file points to the path where it is created, usually your project home folder.

[EDIT]

As @cmc said,

    String basePath = new File("").getAbsolutePath();
    System.out.println(basePath);

    String path = new File("src/main/resources/conf.properties")
                                                           .getAbsolutePath();
    System.out.println(path);

Both give the same value.

CSS Calc Viewport Units Workaround?

Before I answer this, I'd like to point out that Chrome and IE 10+ actually supports calc with viewport units.

FIDDLE (In IE10+)

Solution (for other browsers): box-sizing

1) Start of by setting your height as 100vh.

2) With box-sizing set to border-box - add a padding-top of 75vw. This means that the padding will be part f the inner height.

3) Just offset the extra padding-top with a negative margin-top

FIDDLE

div
{
    /*height: calc(100vh - 75vw);*/
    height: 100vh;
    margin-top: -75vw;
    padding-top: 75vw;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    background: pink;
}

Location for session files in Apache/PHP

The only surefire option to find the current session.save_path value is always to check with phpinfo() in exactly the environment where you want to find out the session storage directory.

Reason: there can be all sorts of things that change session.save_path, either by overriding the php.ini value or by setting it at runtime with ini_set('session.save_path','/path/to/folder');. For example, web server management panels like ISPConfig, Plesk etc. often adapt this to give each website its own directory with session files.

babel-loader jsx SyntaxError: Unexpected token

You can find a really good boilerplate made by Henrik Joreteg (ampersandjs) here: https://github.com/HenrikJoreteg/hjs-webpack

Then in your webpack.config.js

var getConfig = require('hjs-webpack')

module.exports = getConfig({
  in: 'src/index.js',
  out: 'public',
  clearBeforeBuild: true,
  https: process.argv.indexOf('--https') !== -1
})

Convert int (number) to string with leading zeros? (4 digits)

Use the formatting options available to you, use the Decimal format string. It is far more flexible and requires little to no maintenance compared to direct string manipulation.

To get the string representation using at least 4 digits:

int length = 4;
int number = 50;
string asString = number.ToString("D" + length); //"0050"

Read contents of a local file into a variable in Rails

Answering my own question here... turns out it's a Windows only quirk that happens when reading binary files (in my case a JPEG) that requires an additional flag in the open or File.open function call. I revised it to open("/path/to/file", 'rb') {|io| a = a + io.read} and all was fine.

How do I get whole and fractional parts from double in JSP/Java?

http://www.java2s.com/Code/Java/Data-Type/Obtainingtheintegerandfractionalparts.htm

double num;
long iPart;
double fPart;

// Get user input
num = 2.3d;
iPart = (long) num;
fPart = num - iPart;
System.out.println("Integer part = " + iPart);
System.out.println("Fractional part = " + fPart);

Outputs:

Integer part = 2
Fractional part = 0.2999999999999998

check all socket opened in linux OS

Also you can use ss utility to dump sockets statistics.

To dump summary:

ss -s

Total: 91 (kernel 0)
TCP:   18 (estab 11, closed 0, orphaned 0, synrecv 0, timewait 0/0), ports 0

Transport Total     IP        IPv6
*         0         -         -        
RAW       0         0         0        
UDP       4         2         2        
TCP       18        16        2        
INET      22        18        4        
FRAG      0         0         0

To display all sockets:

ss -a

To display UDP sockets:

ss -u -a

To display TCP sockets:

ss -t -a

Here you can read ss man: ss

How do I resolve "Please make sure that the file is accessible and that it is a valid assembly or COM component"?

Make sure the required dlls are exported (or copied manually) to the bin folder when building your application.

How to connect to my http://localhost web server from Android Emulator

If you using Android Emulator :

You can connect to your Pc localhost by these IPs : 10.0.2.2:{port of your localhost} => if you set your machine port in xamp you must use that port . In my case 10.0.2.2:2080

enter image description here

enter image description here

Also you can use your network adapter IP .In CMD write ipconfig and find your adapter ip address :

enter image description here

enter image description here

If emulator can not connect to this IPs close the emulator an open it by cold boot from AVD Manager :

enter image description here

If you using Genymotion :

You can connect to machine localhost by this IP : 10.0.3.2:{port number} Or your adapter IP address as I explained above: in my case : 192.168.1.3:2080

ffmpeg usage to encode a video to H264 codec format

"C:\Program Files (x86)\ffmpegX86shared\bin\ffmpeg.exe" -y -i "C:\testfile.ts" -an -vcodec libx264 -g 75 -keyint_min 12 -vb 4000k -vprofile high -level 40 -s 1920x1080 -y -threads 0 -r 25 "C:\testfile.h264"

The above worked for me on a Windows machine using a FFmpeg Win32 shared build by Kyle Schwarz. The build was compiled on: Feb 22 2013, at: 01:09:53

Note that -an defines that audio should be skipped.

Prevent nginx 504 Gateway timeout using PHP set_time_limit()

You need to add extra nginx directive (for ngx_http_proxy_module) in nginx.conf, e.g.:

proxy_read_timeout 300;

Basically the nginx proxy_read_timeout directive changes the proxy timeout, the FcgidIOTimeout is for scripts that are quiet too long, and FcgidBusyTimeout is for scripts that take too long to execute.

Also if you're using FastCGI application, increase these options as well:

FcgidBusyTimeout 300
FcgidIOTimeout 250

Then reload nginx and PHP5-FPM.

Plesk

In Plesk, you can add it in Web Server Settings under Additional nginx directives.

For FastCGI check in Web Server Settings under Additional directives for HTTP.

See: How to fix FastCGI timeout issues in Plesk?

C# windows application Event: CLR20r3 on application start

.NET has two CLRs 2.0 and 4.0. CLR 2.0 works till .NET framework 3.5. CLR 4.0 works from .NET 4.0 onwards. Its possible that your solution is using a different CLR than your reference assemblies. In your local development environment, you might have both the CLRs and hence you did not faced any problem. However when you moved to deployment environments, they might have a single CLR only and you got this error.

How to determine if a String has non-alphanumeric characters?

If you can use the Apache Commons library, then Commons-Lang StringUtils has a method called isAlphanumeric() that does what you're looking for.

Changing Shell Text Color (Windows)

Been looking into this for a while and not got any satisfactory answers, however...

1) ANSI escape sequences do work in a terminal on Linux

2) if you can tolerate a limited set of colo(u)rs try this:

print("hello", end=''); print("error", end='', file=sys.stderr); print("goodbye")

In idle "hello" and "goodbye" are in blue and "error" is in red.

Not fantastic, but good enough for now, and easy!

Double precision floating values in Python?

Python's built-in float type has double precision (it's a C double in CPython, a Java double in Jython). If you need more precision, get NumPy and use its numpy.float128.

How can I find the first occurrence of a sub-string in a python string?

Quick Overview: index and find

Next to the find method there is as well index. find and index both yield the same result: returning the position of the first occurrence, but if nothing is found index will raise a ValueError whereas find returns -1. Speedwise, both have the same benchmark results.

s.find(t)    #returns: -1, or index where t starts in s
s.index(t)   #returns: Same as find, but raises ValueError if t is not in s

Additional knowledge: rfind and rindex:

In general, find and index return the smallest index where the passed-in string starts, and rfind and rindex return the largest index where it starts Most of the string searching algorithms search from left to right, so functions starting with r indicate that the search happens from right to left.

So in case that the likelihood of the element you are searching is close to the end than to the start of the list, rfind or rindex would be faster.

s.rfind(t)   #returns: Same as find, but searched right to left
s.rindex(t)  #returns: Same as index, but searches right to left

Source: Python: Visual QuickStart Guide, Toby Donaldson

Given two directory trees, how can I find out which files differ by content?

You can also use Rsync and find. For find:

find $FOLDER -type f | cut -d/ -f2- | sort > /tmp/file_list_$FOLDER

But files with the same names and in the same subfolders, but with different content, will not be shown in the lists.

If you are a fan of GUI, you may check Meld that @Alexander mentioned. It works fine in both windows and linux.

How can I use interface as a C# generic type constraint?

Solution A: This combination of constraints should guarantee that TInterface is an interface:

class example<TInterface, TStruct>
    where TStruct : struct, TInterface
    where TInterface : class
{ }

It requires a single struct TStruct as a Witness to proof that TInterface is a struct.

You can use single struct as a witness for all your non-generic types:

struct InterfaceWitness : IA, IB, IC 
{
    public int DoA() => throw new InvalidOperationException();
    //...
}

Solution B: If you don't want to make structs as witnesses you can create an interface

interface ISInterface<T>
    where T : ISInterface<T>
{ }

and use a constraint:

class example<TInterface>
    where TInterface : ISInterface<TInterface>
{ }

Implementation for interfaces:

interface IA :ISInterface<IA>{ }

This solves some of the problems, but requires trust that noone implements ISInterface<T> for non-interface types, but that is pretty hard to do accidentally.

MySQL CREATE FUNCTION Syntax

MySQL create function syntax:

DELIMITER //

CREATE FUNCTION GETFULLNAME(fname CHAR(250),lname CHAR(250))
    RETURNS CHAR(250)
    BEGIN
        DECLARE fullname CHAR(250);
        SET fullname=CONCAT(fname,' ',lname);
        RETURN fullname;
    END //

DELIMITER ;

Use This Function In Your Query

SELECT a.*,GETFULLNAME(a.fname,a.lname) FROM namedbtbl as a


SELECT GETFULLNAME("Biswarup","Adhikari") as myname;

Watch this Video how to create mysql function and how to use in your query

Create Mysql Function Video Tutorial

Delete specified file from document directory

You can double protect your file removal with NSFileManager.defaultManager().isDeletableFileAtPath(PathName) As of now you MUST use do{}catch{} as the old error methods no longer work. isDeletableFileAtPath() is not a "throws" (i.e. "public func removeItemAtPath(path: String) throws") so it does not need the do...catch

let killFile = NSFileManager.defaultManager()

            if (killFile.isDeletableFileAtPath(PathName)){


                do {
                  try killFile.removeItemAtPath(arrayDictionaryFilePath)
                }
                catch let error as NSError {
                    error.description
                }
            }

PostgreSQL: Drop PostgreSQL database through command line

When it says users are connected, what does the query "select * from pg_stat_activity;" say? Are the other users besides yourself now connected? If so, you might have to edit your pg_hba.conf file to reject connections from other users, or shut down whatever app is accessing the pg database to be able to drop it. I have this problem on occasion in production. Set pg_hba.conf to have a two lines like this:

local   all         all                               ident
host    all         all         127.0.0.1/32          reject

and tell pgsql to reload or restart (i.e. either sudo /etc/init.d/postgresql reload or pg_ctl reload) and now the only way to connect to your machine is via local sockets. I'm assuming you're on linux. If not this may need to be tweaked to something other than local / ident on that first line, to something like host ... yourusername.

Now you should be able to do:

psql postgres
drop database mydatabase;

Error 1022 - Can't write; duplicate key in table

I had this problem when creating a new table. It turns out the Foreign Key name I gave was already in use. Renaming the key fixed it.

Guzzle 6: no more json() method for responses

$response is instance of PSR-7 ResponseInterface. For more details see https://www.php-fig.org/psr/psr-7/#3-interfaces

getBody() returns StreamInterface:

/**
 * Gets the body of the message.
 *
 * @return StreamInterface Returns the body as a stream.
 */
public function getBody();

StreamInterface implements __toString() which does

Reads all data from the stream into a string, from the beginning to end.

Therefore, to read body as string, you have to cast it to string:

$stringBody = (string) $response->getBody()


Gotchas

  1. json_decode($response->getBody() is not the best solution as it magically casts stream into string for you. json_decode() requires string as 1st argument.
  2. Don't use $response->getBody()->getContents() unless you know what you're doing. If you read documentation for getContents(), it says: Returns the remaining contents in a string. Therefore, calling getContents() reads the rest of the stream and calling it again returns nothing because stream is already at the end. You'd have to rewind the stream between those calls.

How to resume Fragment from BackStack if exists

I think this method my solve your problem:

public static void attachFragment ( int fragmentHolderLayoutId, Fragment fragment, Context context, String tag ) {


    FragmentManager manager = ( (AppCompatActivity) context ).getSupportFragmentManager ();
    FragmentTransaction ft = manager.beginTransaction ();

    if (manager.findFragmentByTag ( tag ) == null) { // No fragment in backStack with same tag..
        ft.add ( fragmentHolderLayoutId, fragment, tag );
        ft.addToBackStack ( tag );
        ft.commit ();
    }
    else {
        ft.show ( manager.findFragmentByTag ( tag ) ).commit ();
    }
}

which was originally posted in This Question

Vertically centering a div inside another div

Instead of tying myself in a knot with hard-to-write and hard-to-maintain CSS (that also needs careful cross-browser validation!) I find it far better to give up on CSS and use instead wonderfully simple HTML 1.0:

<table id="outerDiv" cellpadding="0" cellspacing="0" border="0">
    <tr>
        <td valign="middle" id="innerDiv">
        </td>
    </tr>
</table>

This accomplishes everything the original poster wanted, and is robust and maintainable.

Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies

I encounter this issue recently and I tried many things mentioned in this thread and others. I added package reference for "System.Runtime" by nuget package manager, fixed the binding redicts in app.config, and make sure that app.config and package.config have the same version for the assembly. However, the problem persisted.

Finally, I removed the <dependentAssembly> tag for the assembly and the problem dissappeared. So, try removing the following in your app.config.

<dependentAssembly>
    <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.1.0" />
</dependentAssembly>

Edit: After I update .NET framework to 4.7.2, the problem resurfaced. I tried the above trick but it didn't work. After wasting many hours, I realized the problem is occurring because of an old System.Linq reference in app.config. Therefore, either remove or update all Linq references also to get rid of this problem.

urllib and "SSL: CERTIFICATE_VERIFY_FAILED" Error

import requests
requests.packages.urllib3.disable_warnings()

import ssl

try:
    _create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
    # Legacy Python that doesn't verify HTTPS certificates by default
    pass
else:
    # Handle target environment that doesn't support HTTPS verification
    ssl._create_default_https_context = _create_unverified_https_context

Taken from here https://gist.github.com/michaelrice/a6794a017e349fc65d01

How to remove a key from Hash and get the remaining hash in Ruby/Rails?

in pure Ruby:

{:a => 1, :b => 2}.tap{|x| x.delete(:a)}   # => {:b=>2}

How to search a Git repository by commit message?

Try this!

git log | grep -b3 "Build 0051"

Change color of Button when Mouse is over

Try this- In this example Original color is green and mouseover color will be DarkGoldenrod

<Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Bottom" Width="50" Height="50" HorizontalContentAlignment="Left" BorderBrush="{x:Null}" Foreground="{x:Null}" Margin="50,0,0,0">
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Background" Value="Green"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Border Background="{TemplateBinding Background}">
                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Background" Value="DarkGoldenrod"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

Spring MVC - Why not able to use @RequestBody and @RequestParam together

You could also just change the @RequestParam default required status to false so that HTTP response status code 400 is not generated. This will allow you to place the Annotations in any order you feel like.

@RequestParam(required = false)String name

Java OCR implementation

I recommend trying the Java OCR project on sourceforge.net. I originally developed it, and I have a blog posting on it.

Since I put it up on sourceforge, its functionality been expanded and improved quite a bit through the great work of a volunteer researcher/developer.

Give it a try, and if you don't like it, you can always improve it!

How to convert a string to integer in C?

int atoi(const char* str){
    int num = 0;
    int i = 0;
    bool isNegetive = false;
    if(str[i] == '-'){
        isNegetive = true;
        i++;
    }
    while (str[i] && (str[i] >= '0' && str[i] <= '9')){
        num = num * 10 + (str[i] - '0');
        i++;
    }
    if(isNegetive) num = -1 * num;
    return num;
}

Input type number "only numeric value" validation

The easiest way would be to use a library like this one and specifically you want noStrings to be true

    export class CustomValidator{   // Number only validation   
      static numeric(control: AbstractControl) {
        let val = control.value;

        const hasError = validate({val: val}, {val: {numericality: {noStrings: true}}});

        if (hasError) return null;

        return val;   
      } 
    }

How to make a gui in python

If you're more into gaming you can use PyGame for GUIs.

how to change listen port from default 7001 to something different?

If you still get the exception in the server startup after changing listen port, you should try changing Pointbase server port and debug port in setDomainEnv.cmd

When to use React setState callback

Consider setState call

this.setState({ counter: this.state.counter + 1 })

IDEA

setState may be called in async function

So you cannot rely on this. If the above call was made inside a async function this will refer to state of component at that point of time but we expected this to refer to property inside state at time setState calling or beginning of async task. And as task was async call thus that property may have changed in time being. Thus it is unreliable to use this keyword to refer to some property of state thus we use callback function whose arguments are previousState and props which means when async task was done and it was time to update state using setState call prevState will refer to state now when setState has not started yet. Ensuring reliability that nextState would not be corrupted.

Wrong Code: would lead to corruption of data

this.setState(
   {counter:this.state.counter+1}
 );

Correct Code with setState having call back function:

 this.setState(
       (prevState,props)=>{
           return {counter:prevState.counter+1};
        }
    );

Thus whenever we need to update our current state to next state based on value possed by property just now and all this is happening in async fashion it is good idea to use setState as callback function.

I have tried to explain it in codepen here CODE PEN

Numpy - Replace a number with NaN

A[A==NDV]=numpy.nan

A==NDV will produce a boolean array that can be used as an index for A

Check if $_POST exists

if( isset($_POST['fromPerson']) )
{
     $fromPerson = '+from%3A'.$_POST['fromPerson'];
     echo $fromPerson;
}

cpp / c++ get pointer value or depointerize pointer

To get the value of a pointer, just de-reference the pointer.

int *ptr;
int value;
*ptr = 9;

value = *ptr;

value is now 9.

I suggest you read more about pointers, this is their base functionality.

eclipse stuck when building workspace

Rather than debug and find the exact root cause(s) for this, I just deleted the projects and the metadata folder. Eclipse will rebuild the .metadata file the next time it's launched.

I then pulled in the latest project code and the problem was solved. It was more work as I had to reconfigure everything, including my servers, but build workspace had been stopping at 50% for anywhere from 3 to 5 minutes before it would completely finish, so it was worth the effort.

Also, I've found that with Eclipse, if you stop the build workspace before it completes and shut down Eclipse if that hangs up everything, you can really mess up your configuration and waste lots of time trying to get it stable again. I'm using Eclipse Oxygen, but I've had this happen in all the versions of Eclipse I've used, so I really try to avoid it, if possible.

LINQ order by null column where order is ascending and nulls should be last

The solution for string values is really weird:

.OrderBy(f => f.SomeString == null).ThenBy(f => f.SomeString) 

The only reason that works is because the first expression, OrderBy(), sort bool values: true/false. false result go first follow by the true result (nullables) and ThenBy() sort the non-null values alphabetically.

e.g.: [null, "coconut", null, "apple", "strawberry"]
First sort: ["coconut", "apple", "strawberry", null, null]
Second sort: ["apple", "coconut", "strawberry", null, null]
So, I prefer doing something more readable such as this:
.OrderBy(f => f.SomeString ?? "z")

If SomeString is null, it will be replaced by "z" and then sort everything alphabetically.

NOTE: This is not an ultimate solution since "z" goes first than z-values like zebra.

UPDATE 9/6/2016 - About @jornhd comment, it is really a good solution, but it still a little complex, so I will recommend to wrap it in a Extension class, such as this:

public static class MyExtensions
{
    public static IOrderedEnumerable<T> NullableOrderBy<T>(this IEnumerable<T> list, Func<T, string> keySelector)
    {
        return list.OrderBy(v => keySelector(v) != null ? 0 : 1).ThenBy(keySelector);
    }
}

And simple use it like:

var sortedList = list.NullableOrderBy(f => f.SomeString);

what is the use of $this->uri->segment(3) in codeigniter pagination

By default the function returns FALSE (boolean) if the segment does not exist. There is an optional second parameter that permits you to set your own default value if the segment is missing. For example, this would tell the function to return the number zero in the event of failure: $product_id = $this->uri->segment(3, 0);

It helps avoid having to write code like this:

[if ($this->uri->segment(3) === FALSE)
{
    $product_id = 0;
}
else
{
    $product_id = $this->uri->segment(3);
}]

What is the difference between encode/decode?

To represent a unicode string as a string of bytes is known as encoding. Use u'...'.encode(encoding).

Example:

    >>> u'æøå'.encode('utf8')
    '\xc3\x83\xc2\xa6\xc3\x83\xc2\xb8\xc3\x83\xc2\xa5'
    >>> u'æøå'.encode('latin1')
    '\xc3\xa6\xc3\xb8\xc3\xa5'
    >>> u'æøå'.encode('ascii')
    UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: 
    ordinal not in range(128)

You typically encode a unicode string whenever you need to use it for IO, for instance transfer it over the network, or save it to a disk file.

To convert a string of bytes to a unicode string is known as decoding. Use unicode('...', encoding) or '...'.decode(encoding).

Example:

   >>> u'æøå'
   u'\xc3\xa6\xc3\xb8\xc3\xa5' # the interpreter prints the unicode object like so
   >>> unicode('\xc3\xa6\xc3\xb8\xc3\xa5', 'latin1')
   u'\xc3\xa6\xc3\xb8\xc3\xa5'
   >>> '\xc3\xa6\xc3\xb8\xc3\xa5'.decode('latin1')
   u'\xc3\xa6\xc3\xb8\xc3\xa5'

You typically decode a string of bytes whenever you receive string data from the network or from a disk file.

I believe there are some changes in unicode handling in python 3, so the above is probably not correct for python 3.

Some good links:

How to increase Heap size of JVM

Following are few options available to change Heap Size.

-Xms<size>        set initial Java heap size
-Xmx<size>        set maximum Java heap size
-Xss<size>        set java thread stack size


java -Xmx256m TestData.java

How to redirect stdout to both file and console with scripting?

I've tried a few solutions here and didn't find the one that writes into file and into console at the same time. So here is what I did (based on this answer)

class Logger(object):
    def __init__(self):
        self.terminal = sys.stdout

    def write(self, message):
        with open ("logfile.log", "a", encoding = 'utf-8') as self.log:            
            self.log.write(message)
        self.terminal.write(message)

    def flush(self):
        #this flush method is needed for python 3 compatibility.
        #this handles the flush command by doing nothing.
        #you might want to specify some extra behavior here.
        pass
sys.stdout = Logger()   

This solution uses more computing power, but reliably saves all of the data from stdout into logger file and uses less memeory. For my needs I've added time stamp into self.log.write(message) aswell. Works great.

How would I access variables from one class to another?

we can access/pass arguments/variables from one class to another class using object reference.

#Class1
class Test:
    def __init__(self):
        self.a = 10
        self.b = 20
        self.add = 0

    def calc(self):
        self.add = self.a+self.b

#Class 2
class Test2:
    def display(self):
        print('adding of two numbers: ',self.add)
#creating object for Class1
obj = Test()
#invoking calc method()
obj.calc()
#passing class1 object to class2
Test2.display(obj)

Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3

I just had to do import Foundation!

I was using Kitura for Swift server side and kept forgetting this!

Create a batch file to run an .exe with an additional parameter

You can use

start "" "%USERPROFILE%\Desktop\BGInfo\bginfo.exe" "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi"

or

start "" /D "%USERPROFILE%\Desktop\BGInfo" bginfo.exe dc_bginfo.bgi

or

"%USERPROFILE%\Desktop\BGInfo\bginfo.exe" "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi"

or

cd /D "%USERPROFILE%\Desktop\BGInfo"
bginfo.exe dc_bginfo.bgi

Help on commands start and cd is output by executing in a command prompt window help start or start /? and help cd or cd /?.

But I do not understand why you need a batch file at all for starting the application with the additional parameter. Create a shortcut (*.lnk) on your desktop for this application. Then right click on the shortcut, left click on Properties and append after a space character "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi" as parameter.

SQL - HAVING vs. WHERE

Didn't see an example of both in one query. So this example might help.

  /**
INTERNATIONAL_ORDERS - table of orders by company by location by day
companyId, country, city, total, date
**/

SELECT country, city, sum(total) totalCityOrders 
FROM INTERNATIONAL_ORDERS with (nolock)
WHERE companyId = 884501253109
GROUP BY country, city
HAVING country = 'MX'
ORDER BY sum(total) DESC

This filters the table first by the companyId, then groups it (by country and city) and additionally filters it down to just city aggregations of Mexico. The companyId was not needed in the aggregation but we were able to use WHERE to filter out just the rows we wanted before using GROUP BY.

Error: "setFile(null,false) call failed" when using log4j

This is your config :

log4j.appender.FILE.File=logs/${file.name}

And this error happened :

java.io.FileNotFoundException: logs (Access is denied)

So it seems that the variable file.name is not set, and java tries to write to the directory logs.


You can force the value of your variable ${file.name} calling maven with this option -D :

mvn clean test -Dfile.name=logfile.log

Bootstrap: Collapse other sections when one is expanded

If you are using Bootstrap 4, and you don't want to change your markup:

var $myGroup = $('#myGroup');
$myGroup.on('show.bs.collapse','.collapse', function() {
$myGroup.find('.collapse.show').collapse('hide');
});

How to find schema name in Oracle ? when you are connected in sql session using read only user

To create a read-only user, you have to setup a different user than the one owning the tables you want to access.

If you just create the user and grant SELECT permission to the read-only user, you'll need to prepend the schema name to each table name. To avoid this, you have basically two options:

  1. Set the current schema in your session:
ALTER SESSION SET CURRENT_SCHEMA=XYZ
  1. Create synonyms for all tables:
CREATE SYNONYM READER_USER.TABLE1 FOR XYZ.TABLE1

So if you haven't been told the name of the owner schema, you basically have three options. The last one should always work:

  1. Query the current schema setting:
SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL
  1. List your synonyms:
SELECT * FROM ALL_SYNONYMS WHERE OWNER = USER
  1. Investigate all tables (with the exception of the some well-known standard schemas):
SELECT * FROM ALL_TABLES WHERE OWNER NOT IN ('SYS', 'SYSTEM', 'CTXSYS', 'MDSYS');

What is the exact meaning of Git Bash?

At its core, Git is a set of command line utility programs that are designed to execute on a Unix style command-line environment. Modern operating systems like Linux and macOS both include built-in Unix command line terminals. This makes Linux and macOS complementary operating systems when working with Git. Microsoft Windows instead uses Windows command prompt, a non-Unix terminal environment.

What is Git Bash?

Git Bash is an application for Microsoft Windows environments which provides an emulation layer for a Git command line experience. Bash is an acronym for Bourne Again Shell. A shell is a terminal application used to interface with an operating system through written commands. Bash is a popular default shell on Linux and macOS. Git Bash is a package that installs Bash, some common bash utilities, and Git on a Windows operating system.

source : https://www.atlassian.com/git/tutorials/git-bash

Ajax using https on an http page

Here's what I do:

Generate a hidden iFrame with the data you would like to post. Since you still control that iFrame, same origin does not apply. Then submit the form in that iFrame to the ssl page. The ssl page then redirects to a non-ssl page with status messages. You have access to the iFrame.

Summarizing count and conditional aggregate functions on the same factor

Assuming that your original dataset is similar to the one you created (i.e. with NA as character. You could specify na.strings while reading the data using read.table. But, I guess NAs would be detected automatically.

The price column is factor which needs to be converted to numeric class. When you use as.numeric, all the non-numeric elements (i.e. "NA", FALSE) gets coerced to NA) with a warning.

library(dplyr)
df %>%
     mutate(price=as.numeric(as.character(price))) %>%  
     group_by(company, year, product) %>%
     summarise(total.count=n(), 
               count=sum(is.na(price)), 
               avg.price=mean(price,na.rm=TRUE),
               max.price=max(price, na.rm=TRUE))

data

I am using the same dataset (except the ... row) that was showed.

df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
 year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
 "Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
 "7.12", "12.99", "10.99", "NA",FALSE)))

getting exception "IllegalStateException: Can not perform this action after onSaveInstanceState"

I solved the issue with onconfigurationchanged. The trick is that according to android activity life cycle, when you explicitly called an intent(camera intent, or any other one); the activity is paused and onsavedInstance is called in that case. When rotating the device to a different position other than the one during which the activity was active; doing fragment operations such as fragment commit causes Illegal state exception. There are lots of complains about it. It's something about android activity lifecycle management and proper method calls. To solve it I did this: 1-Override the onsavedInstance method of your activity, and determine the current screen orientation(portrait or landscape) then set your screen orientation to it before your activity is paused. that way the activity you lock the screen rotation for your activity in case it has been rotated by another one. 2-then , override onresume method of activity, and set your orientation mode now to sensor so that after onsaved method is called it will call one more time onconfiguration to deal with the rotation properly.

You can copy/paste this code into your activity to deal with it:

@Override
protected void onSaveInstanceState(Bundle outState) {       
    super.onSaveInstanceState(outState);

    Toast.makeText(this, "Activity OnResume(): Lock Screen Orientation ", Toast.LENGTH_LONG).show();
    int orientation =this.getDisplayOrientation();
    //Lock the screen orientation to the current display orientation : Landscape or Potrait
    this.setRequestedOrientation(orientation);
}

//A method found in stackOverflow, don't remember the author, to determine the right screen orientation independently of the phone or tablet device 
public int getDisplayOrientation() {
    Display getOrient = getWindowManager().getDefaultDisplay();

    int orientation = getOrient.getOrientation();

    // Sometimes you may get undefined orientation Value is 0
    // simple logic solves the problem compare the screen
    // X,Y Co-ordinates and determine the Orientation in such cases
    if (orientation == Configuration.ORIENTATION_UNDEFINED) {
        Configuration config = getResources().getConfiguration();
        orientation = config.orientation;

        if (orientation == Configuration.ORIENTATION_UNDEFINED) {
        // if height and widht of screen are equal then
        // it is square orientation
            if (getOrient.getWidth() == getOrient.getHeight()) {
                orientation = Configuration.ORIENTATION_SQUARE;
            } else { //if widht is less than height than it is portrait
                if (getOrient.getWidth() < getOrient.getHeight()) {
                    orientation = Configuration.ORIENTATION_PORTRAIT;
                } else { // if it is not any of the above it will defineitly be landscape
                    orientation = Configuration.ORIENTATION_LANDSCAPE;
                }
            }
        }
    }
    return orientation; // return value 1 is portrait and 2 is Landscape Mode
}

@Override
public void onResume() {
    super.onResume();
    Toast.makeText(this, "Activity OnResume(): Unlock Screen Orientation ", Toast.LENGTH_LONG).show();
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
} 

Setting up a cron job in Windows

  1. Make sure you logged on as an administrator or you have the same access as an administrator.
  2. Start->Control Panel->System and Security->Administrative Tools->Task Scheduler
  3. Action->Create Basic Task->Type a name and Click Next
  4. Follow through the wizard.

Best way to script remote SSH commands in Batch (Windows)

The -m switch of PuTTY takes a path to a script file as an argument, not a command.

Reference: https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-m

So you have to save your command (command_run) to a plain text file (e.g. c:\path\command.txt) and pass that to PuTTY:

putty.exe -ssh user@host -pw password -m c:\path\command.txt

Though note that you should use Plink (a command-line connection tool from PuTTY suite). It's a console application, so you can redirect its output to a file (what you cannot do with PuTTY).

A command-line syntax is identical, an output redirection added:

plink.exe -ssh user@host -pw password -m c:\path\command.txt > output.txt

See Using the command-line connection tool Plink.

And with Plink, you can actually provide the command directly on its command-line:

plink.exe -ssh user@host -pw password command > output.txt

Similar questions:
Automating running command on Linux from Windows using PuTTY
Executing command in Plink from a batch file

Convert date formats in bash

It's enough to do:

data=`date`
datatime=`date -d "${data}" '+%Y%m%d'`
echo $datatime
20190206

If you want to add also the time you can use in that way

data=`date`
datatime=`date -d "${data}" '+%Y%m%d %T'`

echo $data
Wed Feb 6 03:57:15 EST 2019

echo $datatime
20190206 03:57:15

Make column fixed position in bootstrap

Use this, works for me and solve problems with small screen.

<div class="row">
    <!-- (fixed content) JUST VISIBLE IN LG SCREEN -->
    <div class="col-lg-3 device-lg visible-lg">
       <div class="affix">
           fixed position 
        </div>
    </div>
    <div class="col-lg-9">
    <!-- (fixed content) JUST VISIBLE IN NO LG SCREEN -->
    <div class="device-sm visible-sm device-xs visible-xs device-md visible-md ">
       <div>
           NO fixed position
        </div>
    </div>
       Normal data enter code here
    </div>
</div>

C# convert int to string with padding zeros?

i.ToString("D4");

See MSDN on format specifiers.

80-characters / right margin line in Sublime Text 3

For this to work, your font also needs to be set to monospace.
If you think about it, lines can't otherwise line up perfectly perfectly.

This answer is detailed at sublime text forum:
http://www.sublimetext.com/forum/viewtopic.php?f=3&p=42052
This answer has links for choosing an appropriate font for your OS,
and gives an answer to an edge case of fonts not lining up.

Another website that lists great monospaced free fonts for programmers. http://hivelogic.com/articles/top-10-programming-fonts

On stackoverflow, see:

Michael Ruth's answer here: How to make ruler always be shown in Sublime text 2?

MattDMo's answer here: What is the default font of Sublime Text?

I have rulers set at the following:
30
50 (git commit message titles should be limited to 50 characters)
72 (git commit message details should be limited to 72 characters)
80 (Windows Command Console Window maxes out at 80 character width)

Other viewing environments that benefit from shorter lines: github: there is no word wrap when viewing a file online
So, I try to keep .js .md and other files at 70-80 characters.
Windows Console: 80 characters.

HowTo Generate List of SQL Server Jobs and their owners

If you don't have access to sysjobs table (someone elses server etc) you might be have or be allowed access to sysjobs_view

SELECT *
 from  msdb..sysjobs_view s 
 left join master.sys.syslogins l on s.owner_sid = l.sid

or

SELECT *, SUSER_SNAME(s.owner_sid) AS owner
 from  msdb..sysjobs_view s 

How to implement Rate It feature in Android App

All those libraries are not the solution for the problem in this post. This libraries just open a webpage to the app on google play. Instead this Play core library has more consistent interface.

So I think this is the problem, ProGuard: it obfscates some classes enough https://stackoverflow.com/a/63650212/10117882

Android - Share on Facebook, Twitter, Mail, ecc

String message = "This is testing."
Intent shareText = new Intent(Intent.ACTION_SEND);
shareText .setType("text/plain");
shareText .putExtra(Intent.EXTRA_TEXT, message);

startActivity(Intent.createChooser(shareText , "Title of the dialog the system will open"));

OS X Bash, 'watch' command

With Homebrew installed:

brew install watch

For files in directory, only echo filename (no path)

if you want filename only :

for file in /home/user/*; do       
  f=$(echo "${file##*/}");
  filename=$(echo $f| cut  -d'.' -f 1); #file has extension, it return only filename
  echo $filename
done

for more information about cut command see here.

Creating your own header file in C

#ifndef MY_HEADER_H
# define MY_HEADER_H

//put your function headers here

#endif

MY_HEADER_H serves as a double-inclusion guard.

For the function declaration, you only need to define the signature, that is, without parameter names, like this:

int foo(char*);

If you really want to, you can also include the parameter's identifier, but it's not necessary because the identifier would only be used in a function's body (implementation), which in case of a header (parameter signature), it's missing.

This declares the function foo which accepts a char* and returns an int.

In your source file, you would have:

#include "my_header.h"

int foo(char* name) {
   //do stuff
   return 0;
}

How to set the 'selected option' of a select dropdown list with jquery

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#YourID option[value="3"]').attr("selected", "selected");_x000D_
  $('#YourID option:selected').attr("selected",null);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>_x000D_
<select id="YourID">_x000D_
  <option value="1">A</option>_x000D_
  <option value="2">B</option>_x000D_
  <option value="3">C</option>_x000D_
  <option value="4">D</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

async await return Task

In order to get proper responses back from async methods, you need to put await while calling those task methods. That will wait for converting it back to the returned value type rather task type.

E.g var content = await StringAsyncTask (

where public async Task<String> StringAsyncTask ())

How to grep recursively, but only in files with certain extensions?

How about:

find . -name '*.h' -o -name '*.cpp' -exec grep "CP_Image" {} \; -print

append to url and refresh page

function gotoItem( item ){
    var url = window.location.href;
    var separator = (url.indexOf('?') > -1) ? "&" : "?";
    var qs = "item=" + encodeURIComponent(item);
    window.location.href = url + separator + qs;
}

More compat version

function gotoItem( item ){
    var url = window.location.href;    
    url += (url.indexOf('?') > -1)?"&":"?" + "item=" + encodeURIComponent(item);
    window.location.href = url;
}

Pandas - How to flatten a hierarchical index in columns

All of the current answers on this thread must have been a bit dated. As of pandas version 0.24.0, the .to_flat_index() does what you need.

From panda's own documentation:

MultiIndex.to_flat_index()

Convert a MultiIndex to an Index of Tuples containing the level values.

A simple example from its documentation:

import pandas as pd
print(pd.__version__) # '0.23.4'
index = pd.MultiIndex.from_product(
        [['foo', 'bar'], ['baz', 'qux']],
        names=['a', 'b'])

print(index)
# MultiIndex(levels=[['bar', 'foo'], ['baz', 'qux']],
#           codes=[[1, 1, 0, 0], [0, 1, 0, 1]],
#           names=['a', 'b'])

Applying to_flat_index():

index.to_flat_index()
# Index([('foo', 'baz'), ('foo', 'qux'), ('bar', 'baz'), ('bar', 'qux')], dtype='object')

Using it to replace existing pandas column

An example of how you'd use it on dat, which is a DataFrame with a MultiIndex column:

dat = df.loc[:,['name','workshop_period','class_size']].groupby(['name','workshop_period']).describe()
print(dat.columns)
# MultiIndex(levels=[['class_size'], ['count', 'mean', 'std', 'min', '25%', '50%', '75%', 'max']],
#            codes=[[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 2, 3, 4, 5, 6, 7]])

dat.columns = dat.columns.to_flat_index()
print(dat.columns)
# Index([('class_size', 'count'),  ('class_size', 'mean'),
#     ('class_size', 'std'),   ('class_size', 'min'),
#     ('class_size', '25%'),   ('class_size', '50%'),
#     ('class_size', '75%'),   ('class_size', 'max')],
#  dtype='object')

HTML combo box with option to type an entry

My solution is very simple, looks exactly like a native editable combobox and yet works even in IE6 (some answers here require a lot of code or external libraries and the result is so so, e.g. the text in the textbox goes behind the dropdown icon of the combobox' part or it doesn't look like an editable combobox at all).

The point is to clip the combobox only the dropdown icon to be visible above the textbox. And the textbox is wide a bit underneath the combobox' part, so you don't see its right end - visually continues with the combobox: https://jsfiddle.net/dLsx0c5y/2/

select#programmoduleselect
{
    clip: rect(auto auto auto 331px);
    width: 351px;
    height: 23px;
    z-index: 101; 
    position: absolute;
}

input#programmodule
{
    width: 328px;
    height: 17px;
}

<table><tr>
<th>Programm / Modul:</th>
<td>
    <select id="programmoduleselect"
        onchange="var textbox = document.getElementById('programmodule'); textbox.value = (this.selectedIndex == -1 ? '' : this.options[this.selectedIndex].value); textbox.select(); fireEvent2(textbox, 'change');"
        onclick="this.selectedIndex = -1;">
        <option value=RFEM>RFEM</option>
        <option value=RSTAB>RSTAB</option>
        <option value=STAHL>STAHL</option>
        <option value=BETON>BETON</option>
        <option value=BGDK>BGDK</option>
    </select>
    <input name="programmodule" id="programmodule" value="" autocomplete="off"
        onkeypress="if (event.keyCode == 13) return false;" />
</td>
</tr></table>

(Used originally e.g. here, but don't send the form: old.dlubal.com/WishedFeatures.aspx )

EDIT: The styles need to be a bit different for macOS: Ch is ok, for FF increase the combobox' height, Safari and Opera ignore the combobox' height so increase their font size (has an upper limit, so then decrease the textbox' height a bit): https://i.stack.imgur.com/efQ9i.png

java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader

This is worked for me

If your having .so file in armeabi then mention inside ndk that folder alone.

defaultConfig {
        applicationId "com.xxx.yyy"
        minSdkVersion 17
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        renderscriptTargetApi 26
        renderscriptSupportModeEnabled true
        ndk {
            abiFilters "armeabi"
        }
    }

and then use this

android.useDeprecatedNdk=true;

in gradle.properties file

Compare a string using sh shell

You should use the = operator for string comparison:

Sourcesystem="ABC"

if [ "$Sourcesystem" = "XYZ" ]; then 
    echo "Sourcesystem Matched" 
else
    echo "Sourcesystem is NOT Matched $Sourcesystem"  
fi;

man test says that you use -z to match for empty strings.

PostgreSQL wildcard LIKE for any of a list of words

One 'elegant' solution would be to use full text search: http://www.postgresql.org/docs/9.0/interactive/textsearch.html. Then you would use full text search queries.

phpMyAdmin - The MySQL Extension is Missing

At first make sure you have mysql installed properly. You can ensure it just by checking that whether you can access mysql using mysql command promp. So if you mysql is working then probably it is not loading. For that follow the steps given below

First of all, you must find your php.ini. It could be anywhere but if you create a small php file with the

<?php phpinfo(); ?>

script it will tell you where it is. Just look at the path of loaded configuration file. Common places include /etc/apache/, /etc/php4/apache2/php.ini, /etc/php5/apache2/php.ini or even /usr/local/lib/php.ini for Windows it may be C:\Users\username\PHP\php.ini

Edit your server’s php.ini and look for the following line. Remove the ‘;’ from the start of the line and restart Apache. Things should work fine now!

;extension=mysql.so

should become

extension=mysql.so

For windows it will be

;extension=mysql.dll

should become

extension=mysql.dll

how to write procedure to insert data in to the table in phpmyadmin?

# Switch delimiter to //, so phpMyAdmin will not execute it line by line.
DELIMITER //
CREATE PROCEDURE usp_rateChapter12

(IN numRating_Chapter INT(11) UNSIGNED, 

 IN txtRating_Chapter VARCHAR(250),

 IN chapterName VARCHAR(250),

 IN addedBy VARCHAR(250)

)

BEGIN
DECLARE numRating_Chapter INT;

DECLARE txtRating_Chapter VARCHAR(250);

DECLARE chapterName1 VARCHAR(250);

DECLARE addedBy1 VARCHAR(250);

DECLARE chapterId INT;

DECLARE studentId INT;

SET chapterName1 = chapterName;
SET addedBy1 = addedBy;

SET chapterId = (SELECT chapterId 
                   FROM chapters 
                   WHERE chaptername = chapterName1);

SET studentId = (SELECT Id 
                   FROM students 
                   WHERE email = addedBy1);

SELECT chapterId;
SELECT studentId;

INSERT INTO ratechapter (rateBy, rateText, rateLevel, chapterRated)
VALUES (studentId, txtRating_Chapter, numRating_Chapter,chapterId);

END //

//DELIMITER;

Self Join to get employee manager name

SELECT e1.emp_id, e1.emp_name, e1.mgr_id, e2.emp_name as manager_name

FROM employee e1

JOIN employee e2

ON e1.mgr_id = e2.emp_id

ORDER BY e1.emp_id

*Here is the link to SQL Fiddle with a working example. http://www.sqlfiddle.com/#!17/392b5/9

What is the difference between old style and new style classes in Python?

Important behavior changes between old and new style classes

  • super added
  • MRO changed (explained below)
  • descriptors added
  • new style class objects cannot be raised unless derived from Exception (example below)
  • __slots__ added

MRO (Method Resolution Order) changed

It was mentioned in other answers, but here goes a concrete example of the difference between classic MRO and C3 MRO (used in new style classes).

The question is the order in which attributes (which include methods and member variables) are searched for in multiple inheritance.

Classic classes do a depth-first search from left to right. Stop on the first match. They do not have the __mro__ attribute.

class C: i = 0
class C1(C): pass
class C2(C): i = 2
class C12(C1, C2): pass
class C21(C2, C1): pass

assert C12().i == 0
assert C21().i == 2

try:
    C12.__mro__
except AttributeError:
    pass
else:
    assert False

New-style classes MRO is more complicated to synthesize in a single English sentence. It is explained in detail here. One of its properties is that a base class is only searched for once all its derived classes have been. They have the __mro__ attribute which shows the search order.

class C(object): i = 0
class C1(C): pass
class C2(C): i = 2
class C12(C1, C2): pass
class C21(C2, C1): pass

assert C12().i == 2
assert C21().i == 2

assert C12.__mro__ == (C12, C1, C2, C, object)
assert C21.__mro__ == (C21, C2, C1, C, object)

New style class objects cannot be raised unless derived from Exception

Around Python 2.5 many classes could be raised, and around Python 2.6 this was removed. On Python 2.7.3:

# OK, old:
class Old: pass
try:
    raise Old()
except Old:
    pass
else:
    assert False

# TypeError, new not derived from `Exception`.
class New(object): pass
try:
    raise New()
except TypeError:
    pass
else:
    assert False

# OK, derived from `Exception`.
class New(Exception): pass
try:
    raise New()
except New:
    pass
else:
    assert False

# `'str'` is a new style object, so you can't raise it:
try:
    raise 'str'
except TypeError:
    pass
else:
    assert False

Build error: "The process cannot access the file because it is being used by another process"

I had the same issue on my Xamarin application in visual studio and it was resolved by unplugging my test mobile device. The application was closed and the debugger was stopped but the error was still happening when trying to build or rebuild the solution. It only stopped after i unplugged the device because i had to receive a call.

How exactly do you configure httpOnlyCookies in ASP.NET?

If you want to do it in code, use the System.Web.HttpCookie.HttpOnly property.

This is directly from the MSDN docs:

// Create a new HttpCookie.
HttpCookie myHttpCookie = new HttpCookie("LastVisit", DateTime.Now.ToString());
// By default, the HttpOnly property is set to false 
// unless specified otherwise in configuration.
myHttpCookie.Name = "MyHttpCookie";
Response.AppendCookie(myHttpCookie);
// Show the name of the cookie.
Response.Write(myHttpCookie.Name);
// Create an HttpOnly cookie.
HttpCookie myHttpOnlyCookie = new HttpCookie("LastVisit", DateTime.Now.ToString());
// Setting the HttpOnly value to true, makes
// this cookie accessible only to ASP.NET.
myHttpOnlyCookie.HttpOnly = true;
myHttpOnlyCookie.Name = "MyHttpOnlyCookie";
Response.AppendCookie(myHttpOnlyCookie);
// Show the name of the HttpOnly cookie.
Response.Write(myHttpOnlyCookie.Name);

Doing it in code allows you to selectively choose which cookies are HttpOnly and which are not.

Where are my postgres *.conf files?

For CentOS 6 and 7 and postgresql 9.2 (and below, I suppose, possibly Fedora and Redhat as well):

/var/lib/pgsql/data

For CentOS 6 and 7 postgresql 9.3 or 9.4 (and above, I suppose):

/var/lib/pgsql/9.3/data
/var/lib/pgsql/9.4/data

For Ubuntu 14 and postgresql 9.3:

/etc/postgresql/9.3/main/postgresql.conf

Strange PostgreSQL "value too long for type character varying(500)"

Character varying is different than text. Try running

ALTER TABLE product_product ALTER COLUMN code TYPE text;

That will change the column type to text, which is limited to some very large amount of data (you would probably never actually hit it.)

How to secure MongoDB with username and password

https://docs.mongodb.com/manual/reference/configuration-options/#security.authorization

Edit the mongo settings file;

sudo nano /etc/mongod.conf

Add the line:

security.authorization : enabled

Restart the service

sudo service mongod restart

Regards

how to change onclick event with jquery?

If you want to change one specific onclick event with jQuery, you better use the functions .on() and .off() with a namespace (see documentation).

Use .on() to create your event and .off() to remove it. You can also create a global object like g_specific_events_set = {}; to avoid duplicates:

_x000D_
_x000D_
$('#alert').click(function()_x000D_
{_x000D_
    alert('First alert!');_x000D_
});_x000D_
_x000D_
g_specific_events_set = {};_x000D_
_x000D_
add_specific_event = function(namespace)_x000D_
{_x000D_
    if (!g_specific_events_set[namespace])_x000D_
    {_x000D_
        $('#alert').on('click.' + namespace, function()_x000D_
        {_x000D_
            alert('SECOND ALERT!!!!!!');_x000D_
        });_x000D_
        g_specific_events_set[namespace] = true;_x000D_
    }_x000D_
};_x000D_
_x000D_
remove_specific_event = function(namespace)_x000D_
{_x000D_
    $('#alert').off('click.' + namespace);_x000D_
    g_specific_events_set[namespace] = false;_x000D_
};_x000D_
_x000D_
_x000D_
_x000D_
$('#add').click(function(){ add_specific_event('eventnumber2'); });_x000D_
_x000D_
$('#remove').click(function(){ remove_specific_event('eventnumber2'); });
_x000D_
div {_x000D_
  display:inline-block;_x000D_
  vertical-align:top;_x000D_
  margin:0 5px 1px 5px;_x000D_
  padding:5px 20px;_x000D_
  background:#ddd;_x000D_
  border:1px solid #aaa;_x000D_
  cursor:pointer;_x000D_
}_x000D_
div:active {_x000D_
  margin-top:1px;_x000D_
  margin-bottom:0px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="alert">_x000D_
  Alert_x000D_
</div>_x000D_
<div id="add">_x000D_
  Add event_x000D_
</div>_x000D_
<div id="remove">_x000D_
  Remove event_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to select the first, second, or third element with a given class name?

In the future (perhaps) you will be able to use :nth-child(an+b of s)

Actually, browser support for the “of” filter is very limited. Only Safari seems to support the syntax.

https://css-tricks.com/almanac/selectors/n/nth-child/

Check if property has attribute

There's no fast way to retrieve attributes. But code ought to look like this (credit to Aaronaught):

var t = typeof(YourClass);
var pi = t.GetProperty("Id");
var hasIsIdentity = Attribute.IsDefined(pi, typeof(IsIdentity));

If you need to retrieve attribute properties then

var t = typeof(YourClass);
var pi = t.GetProperty("Id");
var attr = (IsIdentity[])pi.GetCustomAttributes(typeof(IsIdentity), false);
if (attr.Length > 0) {
    // Use attr[0], you'll need foreach on attr if MultiUse is true
}

How do I view the SSIS packages in SQL Server Management Studio?

The wizard likely created the package as a file. Do a search on your system for files with an extension of .dtsx. This is the actual "SSIS Package" file.

As for loading it in Management Studio, you don't actually view it through there. If you have SQL Server 2005 loaded on your machine, look in the program group. You should find an application with the same icon as Visual Studio called "SQL Server Business Intelligence Development Studio". It's basically a stripped down version of VS 2005 which allows you to create SSIS packages.

Create a blank solution and add your .dtsx file to that to edit/view it.

Warning: push.default is unset; its implicit value is changing in Git 2.0

Brought my answer over from other thread that may close as a duplicate...

From GIT documentation: Git Docs

Below gives the full information. In short, simple will only push the current working branch and even then only if it also has the same name on the remote. This is a very good setting for beginners and will become the default in GIT 2.0

Whereas matching will push all branches locally that have the same name on the remote. (Without regard to your current working branch ). This means potentially many different branches will be pushed, including those that you might not even want to share.

In my personal usage, I generally use a different option: current which pushes the current working branch, (because I always branch for any changes). But for a beginner I'd suggest simple

push.default
Defines the action git push should take if no refspec is explicitly given. Different values are well-suited for specific workflows; for instance, in a purely central workflow (i.e. the fetch source is equal to the push destination), upstream is probably what you want. Possible values are:

nothing - do not push anything (error out) unless a refspec is explicitly given. This is primarily meant for people who want to avoid mistakes by always being explicit.

current - push the current branch to update a branch with the same name on the receiving end. Works in both central and non-central workflows.

upstream - push the current branch back to the branch whose changes are usually integrated into the current branch (which is called @{upstream}). This mode only makes sense if you are pushing to the same repository you would normally pull from (i.e. central workflow).

simple - in centralized workflow, work like upstream with an added safety to refuse to push if the upstream branch's name is different from the local one.

When pushing to a remote that is different from the remote you normally pull from, work as current. This is the safest option and is suited for beginners.

This mode will become the default in Git 2.0.

matching - push all branches having the same name on both ends. This makes the repository you are pushing to remember the set of branches that will be pushed out (e.g. if you always push maint and master there and no other branches, the repository you push to will have these two branches, and your local maint and master will be pushed there).

To use this mode effectively, you have to make sure all the branches you would push out are ready to be pushed out before running git push, as the whole point of this mode is to allow you to push all of the branches in one go. If you usually finish work on only one branch and push out the result, while other branches are unfinished, this mode is not for you. Also this mode is not suitable for pushing into a shared central repository, as other people may add new branches there, or update the tip of existing branches outside your control.

This is currently the default, but Git 2.0 will change the default to simple.

$(form).ajaxSubmit is not a function

Try ajaxsubmit library. It does ajax submition as well as validation via ajax.

Also configuration is very flexible to support any kind of UI.

Live demo available with js, css and html examples.

how to set default main class in java?

you can right click on the project select "set configuration" then "Customize", from there you can choose your main class. ScreenShot

How to create a simple http proxy in node.js?

Your code doesn't work for binary files because they can't be cast to strings in the data event handler. If you need to manipulate binary files you'll need to use a buffer. Sorry, I do not have an example of using a buffer because in my case I needed to manipulate HTML files. I just check the content type and then for text/html files update them as needed:

app.get('/*', function(clientRequest, clientResponse) {
  var options = { 
    hostname: 'google.com',
    port: 80, 
    path: clientRequest.url,
    method: 'GET'
  };  

  var googleRequest = http.request(options, function(googleResponse) { 
    var body = ''; 

    if (String(googleResponse.headers['content-type']).indexOf('text/html') !== -1) {
      googleResponse.on('data', function(chunk) {
        body += chunk;
      }); 

      googleResponse.on('end', function() {
        // Make changes to HTML files when they're done being read.
        body = body.replace(/google.com/gi, host + ':' + port);
        body = body.replace(
          /<\/body>/, 
          '<script src="http://localhost:3000/new-script.js" type="text/javascript"></script></body>'
        );

        clientResponse.writeHead(googleResponse.statusCode, googleResponse.headers);
        clientResponse.end(body);
      }); 
    }   
    else {
      googleResponse.pipe(clientResponse, {
        end: true
      }); 
    }   
  }); 

  googleRequest.end();
});    

How do I set up Visual Studio Code to compile C++ code?

A makefile task example for new 2.0.0 tasks.json version.

In the snippet below some comments I hope they will be useful.

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "<TASK_NAME>",
            "type": "shell",
            "command": "make",
            // use options.cwd property if the Makefile is not in the project root ${workspaceRoot} dir
            "options": {
                "cwd": "${workspaceRoot}/<DIR_WITH_MAKEFILE>"
            },
            // start the build without prompting for task selection, use "group": "build" otherwise
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "presentation": {
                "echo": true,
                "reveal": "always",
                "focus": false,
                "panel": "shared"
            },
            // arg passing example: in this case is executed make QUIET=0
            "args": ["QUIET=0"],
            // Use the standard less compilation problem matcher.
            "problemMatcher": {
                "owner": "cpp",
                "fileLocation": ["absolute"],
                "pattern": {
                    "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
                    "file": 1,
                    "line": 2,
                    "column": 3,
                    "severity": 4,
                    "message": 5
                }
            }
        }
    ]
}

How to use Jquery how to change the aria-expanded="false" part of a dom element (Bootstrap)?

You can use .attr() as a part of however you plan to toggle it:

$("button").attr("aria-expanded","true");

Set a button group's width to 100% and make buttons equal width?

BOOTSTRAP 2 (source)

The problem is that there is no width set on the buttons. Try this:

.btn {width:20%;}

EDIT:

By default the buttons take an auto width of its text length plus some padding, so I guess for your example it is probably more like 14.5% for 5 buttons (to compensate for the padding).

Note:

If you don't want to try and compensate for padding you can use box-sizing:border-box;

http://www.w3schools.com/cssref/css3_pr_box-sizing.asp

How to pass a variable from Activity to Fragment, and pass it back?

You can simply instantiate your fragment with a bundle:

Fragment fragment = Fragment.instantiate(this, RolesTeamsListFragment.class.getName(), bundle);

Structuring online documentation for a REST API

That's a very complex question for a simple answer.

You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.

Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.

At the very top level I think quality REST API docs require at least the following:

  • a list of all your API endpoints (base/relative URLs)
  • corresponding HTTP GET/POST/... method type for each endpoint
  • request/response MIME-type (how to encode params and parse replies)
  • a sample request/response, including HTTP headers
  • type and format specified for all params, including those in the URL, body and headers
  • a brief text description and important notes
  • a short code snippet showing the use of the endpoint in popular web programming languages

Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.

How to create a link to another PHP page

Html a tag

Link in html

 <a href="index1.php">page1</a>
 <a href="page2.php">page2</a>

Html in php

echo ' <a href="index1.php">page1</a>';
echo '<a href="page2.php">page2</a>';

check if file exists on remote host with ssh

You can specify the shell to be used by the remote host locally.

echo 'echo "Bash version: ${BASH_VERSION}"' | ssh -q localhost bash

And be careful to (single-)quote the variables you wish to be expanded by the remote host; otherwise variable expansion will be done by your local shell!

# example for local / remote variable expansion
{
echo "[[ $- == *i* ]] && echo 'Interactive' || echo 'Not interactive'" | 
    ssh -q localhost bash
echo '[[ $- == *i* ]] && echo "Interactive" || echo "Not interactive"' | 
    ssh -q localhost bash
}

So, to check if a certain file exists on the remote host you can do the following:

host='localhost'  # localhost as test case
file='~/.bash_history'
if `echo 'test -f '"${file}"' && exit 0 || exit 1' | ssh -q "${host}" sh`; then
#if `echo '[[ -f '"${file}"' ]] && exit 0 || exit 1' | ssh -q "${host}" bash`; then
   echo exists
else
   echo does not exist
fi

Get Absolute URL from Relative path (refactored method)

new System.Uri(Page.Request.Url, "/myRelativeUrl.aspx").AbsoluteUri

How to print out a variable in makefile

@echo $(NDK_PROJECT_PATH) is the good way to do it. I don't think the error comes from there. Generally this error appears when you mistyped the intendation : I think you have spaces where you should have a tab.

Oracle "SQL Error: Missing IN or OUT parameter at index:: 1"

I think its related with jdbc.

I have a similar problem (missing param) when I have a where condition like this:

a = :namedparameter and b = :namedparameter

It's ok, When I have like this:

a = :namedparameter and b = :namedparameter2  (the two param has the same value)

So it's a problem with named parameters. I think there is a bug around named parameter handling, it looks like if only the first parameter get the right value, the second is not set by driver classes. Maybe its not a bug, only I don't know something, but anyway I guess that's the reason for the difference between the SQL dev and the sqlplus running for you, because as far as I know SQL developer uses jdbc driver.

sql server #region

Not out of the box in Sql Server Management Studio, but it is a feature of the very good SSMS Tools Pack

Compiling an application for use in highly radioactive environments

I've really read a lot of great answers!

Here is my 2 cent: build a statistical model of the memory/register abnormality, by writing a software to check the memory or to perform frequent register comparisons. Further, create an emulator, in the style of a virtual machine where you can experiment with the issue. I guess if you vary junction size, clock frequency, vendor, casing, etc would observe a different behavior.

Even our desktop PC memory has a certain rate of failure, which however doesn't impair the day to day work.

How to convert a string to JSON object in PHP

you can use this for example

$array = json_decode($string,true)

but validate the Json before. You can validate from http://jsonviewer.stack.hu/

C Programming: How to read the whole file contents into a buffer

Portability between Linux and Windows is a big headache, since Linux is a POSIX-conformant system with - generally - a proper, high quality toolchain for C, whereas Windows doesn't even provide a lot of functions in the C standard library.

However, if you want to stick to the standard, you can write something like this:

#include <stdio.h>
#include <stdlib.h>

FILE *f = fopen("textfile.txt", "rb");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET);  /* same as rewind(f); */

char *string = malloc(fsize + 1);
fread(string, 1, fsize, f);
fclose(f);

string[fsize] = 0;

Here string will contain the contents of the text file as a properly 0-terminated C string. This code is just standard C, it's not POSIX-specific (although that it doesn't guarantee it will work/compile on Windows...)

How can I write to the console in PHP?

I have abandoned all of the above in favour of Debugger & Logger. I cannot praise it enough!

Just click on one of the tabs at top right, or on the "click here" to expand/hide.

Notice the different "categories". You can click any array to expand/collapse it.

From the web page

Main features:

  • Show globals variables ($GLOBALS, $_POST, $_GET, $_COOKIE, etc.)
  • Show PHP version and loaded extensions
  • Replace PHP built in error handler
  • Log SQL queries
  • Monitor code and SQL queries execution time
  • Inspect variables for changes
  • Function calls tracing
  • Code coverage analysis to check which lines of script where executed
  • Dump of all types of variable
  • File inspector with code highlighter to view source code
  • Send messages to JavaScript console (Chrome only), for Ajax scripts

Enter image description here

PowerMockito mock single static method and return object

What you want to do is a combination of part of 1 and all of 2.

You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.

But the 2-argument overload of mockStatic you are using supplies a default strategy for what Mockito/PowerMock should do when you call a method you haven't explicitly stubbed on the mock instance.

From the javadoc:

Creates class mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems. It is the default answer so it will be used only when you don't stub the method call.

The default default stubbing strategy is to just return null, 0 or false for object, number and boolean valued methods. By using the 2-arg overload, you're saying "No, no, no, by default use this Answer subclass' answer method to get a default value. It returns a Long, so if you have static methods which return something incompatible with Long, there is a problem.

Instead, use the 1-arg version of mockStatic to enable stubbing of static methods, then use when-thenReturn to specify what to do for a particular method. For example:

import static org.mockito.Mockito.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

class ClassWithStatics {
  public static String getString() {
    return "String";
  }

  public static int getInt() {
    return 1;
  }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
  @Test
  public void test() {
    PowerMockito.mockStatic(ClassWithStatics.class);

    when(ClassWithStatics.getString()).thenReturn("Hello!");

    System.out.println("String: " + ClassWithStatics.getString());
    System.out.println("Int: " + ClassWithStatics.getInt());
  }
}

The String-valued static method is stubbed to return "Hello!", while the int-valued static method uses the default stubbing, returning 0.

How to disable scrolling in UITableView table when the content fits on the screen

// Enable scrolling based on content height self.tableView.scrollEnabled = table.contentSize.height > table.frame.size.height;

Team Build Error: The Path ... is already mapped to workspace

I received this error, which was caused by having two build definitions that pointed to the same source. The issue was that I used a static build directory in the Build Agent.

This forum post describes my issue and resolution exactly: http://social.msdn.microsoft.com/Forums/en-US/tfsbuild/thread/60a4138a-9b28-4c46-bdf4-f9775ce43c3e/

How to print a string in C++

You need #include<string> to use string AND #include<iostream> to use cin and cout. (I didn't get it when I read the answers). Here's some code which works:

#include<string>
#include<iostream>
using namespace std;

int main()
{
    string name;
    cin >> name;
    string message("hi");
    cout << name << message;
    return 0;
}

conflicting types error when compiling c program using gcc

You have to declare your functions before main()

(or declare the function prototypes before main())

As it is, the compiler sees my_print (my_string); in main() as a function declaration.

Move your functions above main() in the file, or put:

void my_print (char *);
void my_print2 (char *);

Above main() in the file.

How to Debug Variables in Smarty like in PHP var_dump()

If you want something prettier I would advise

{"<?php\n\$data =\n"|@cat:{$yourvariable|@var_export:true|@cat:";\n?>"}|@highlight_string:true}

just replace yourvariable by your variable

How to access property of anonymous type in C#?

You could iterate over the anonymous type's properties using Reflection; see if there is a "Checked" property and if there is then get its value.

See this blog post: http://blogs.msdn.com/wriju/archive/2007/10/26/c-3-0-anonymous-type-and-net-reflection-hand-in-hand.aspx

So something like:

foreach(object o in nodes)
{
    Type t = o.GetType();

    PropertyInfo[] pi = t.GetProperties(); 

    foreach (PropertyInfo p in pi)
    {
        if (p.Name=="Checked" && !(bool)p.GetValue(o))
            Console.WriteLine("awesome!");
    }
}

Check if current directory is a Git repository

Based on @Alex Cory's answer:

[ "$(git rev-parse --is-inside-work-tree 2>/dev/null)" == "true" ]

doesn't contain any redundant operations and works in -e mode.

  • As @go2null noted, this will not work in a bare repo. If you want to work with a bare repo for whatever reason, you can just check for git rev-parse succeeding, ignoring its output.
    • I don't consider this a drawback because the above line is indended for scripting, and virtually all git commands are only valid inside a worktree. So for scripting purposes, you're most likely interested in being not just inside a "git repo" but inside a worktree.

Onclick javascript to make browser go back to previous page?

For Going to previous page

First Method

<a href="javascript: history.go(-1)">Go Back</a>

Second Method

<a href="##" onClick="history.go(-1); return false;">Go back</a> 

if we want to more than one step back then increase

For going 2 steps back history.go(-2)
For going 3 steps back history.go(-3)
For going 4 steps back history.go(-4)
and so on.......

Initialize/reset struct to zero/null

Better than all above is ever to use Standard C specification for struct initialization:

struct StructType structVar = {0};

Here are all bits zero (ever).

How to add Headers on RESTful call using Jersey Client API

If you want to add a header to all Jersey responses, you could also use a ContainerResponseFilter, from Jersey's filter documentation :

import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.Response;

@Provider
public class PoweredByResponseFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
        throws IOException {

            responseContext.getHeaders().add("X-Powered-By", "Jersey :-)");
    }
}

Make sure that you initialize it correctly in your project using the @Provider annotation or through traditional ways with web.xml.

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

Pandas will start looking from where your current python file is located. Therefore you can move from your current directory to where your data is located with '..' For example:

pd.read_csv('../../../data_folder/data.csv')

Will go 3 levels up and then into a data_folder (assuming it's there) Or

pd.read_csv('data_folder/data.csv')

assuming your data_folder is in the same directory as your .py file.

JSON datetime between Python and JavaScript

Here's a fairly complete solution for recursively encoding and decoding datetime.datetime and datetime.date objects using the standard library json module. This needs Python >= 2.6 since the %f format code in the datetime.datetime.strptime() format string is only supported in since then. For Python 2.5 support, drop the %f and strip the microseconds from the ISO date string before trying to convert it, but you'll loose microseconds precision, of course. For interoperability with ISO date strings from other sources, which may include a time zone name or UTC offset, you may also need to strip some parts of the date string before the conversion. For a complete parser for ISO date strings (and many other date formats) see the third-party dateutil module.

Decoding only works when the ISO date strings are values in a JavaScript literal object notation or in nested structures within an object. ISO date strings, which are items of a top-level array will not be decoded.

I.e. this works:

date = datetime.datetime.now()
>>> json = dumps(dict(foo='bar', innerdict=dict(date=date)))
>>> json
'{"innerdict": {"date": "2010-07-15T13:16:38.365579"}, "foo": "bar"}'
>>> loads(json)
{u'innerdict': {u'date': datetime.datetime(2010, 7, 15, 13, 16, 38, 365579)},
u'foo': u'bar'}

And this too:

>>> json = dumps(['foo', 'bar', dict(date=date)])
>>> json
'["foo", "bar", {"date": "2010-07-15T13:16:38.365579"}]'
>>> loads(json)
[u'foo', u'bar', {u'date': datetime.datetime(2010, 7, 15, 13, 16, 38, 365579)}]

But this doesn't work as expected:

>>> json = dumps(['foo', 'bar', date])
>>> json
'["foo", "bar", "2010-07-15T13:16:38.365579"]'
>>> loads(json)
[u'foo', u'bar', u'2010-07-15T13:16:38.365579']

Here's the code:

__all__ = ['dumps', 'loads']

import datetime

try:
    import json
except ImportError:
    import simplejson as json

class JSONDateTimeEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (datetime.date, datetime.datetime)):
            return obj.isoformat()
        else:
            return json.JSONEncoder.default(self, obj)

def datetime_decoder(d):
    if isinstance(d, list):
        pairs = enumerate(d)
    elif isinstance(d, dict):
        pairs = d.items()
    result = []
    for k,v in pairs:
        if isinstance(v, basestring):
            try:
                # The %f format code is only supported in Python >= 2.6.
                # For Python <= 2.5 strip off microseconds
                # v = datetime.datetime.strptime(v.rsplit('.', 1)[0],
                #     '%Y-%m-%dT%H:%M:%S')
                v = datetime.datetime.strptime(v, '%Y-%m-%dT%H:%M:%S.%f')
            except ValueError:
                try:
                    v = datetime.datetime.strptime(v, '%Y-%m-%d').date()
                except ValueError:
                    pass
        elif isinstance(v, (dict, list)):
            v = datetime_decoder(v)
        result.append((k, v))
    if isinstance(d, list):
        return [x[1] for x in result]
    elif isinstance(d, dict):
        return dict(result)

def dumps(obj):
    return json.dumps(obj, cls=JSONDateTimeEncoder)

def loads(obj):
    return json.loads(obj, object_hook=datetime_decoder)

if __name__ == '__main__':
    mytimestamp = datetime.datetime.utcnow()
    mydate = datetime.date.today()
    data = dict(
        foo = 42,
        bar = [mytimestamp, mydate],
        date = mydate,
        timestamp = mytimestamp,
        struct = dict(
            date2 = mydate,
            timestamp2 = mytimestamp
        )
    )

    print repr(data)
    jsonstring = dumps(data)
    print jsonstring
    print repr(loads(jsonstring))

Masking password input from the console : Java

Console console = System.console();
String username = console.readLine("Username: ");
char[] password = console.readPassword("Password: ");

phpMyAdmin - config.inc.php configuration?

I found that the new version of PhpMyAdmin put the 'config.inc.php' files in /var/lib/phpmyadmin/

I spend much time in the wrong dir (/usr/share) as this is where all the files also is located, but changes are not reflected.

After putting my settings in

/var/lib/phpmyadmin/config.inc.php

They worked

Is there a way to 'uniq' by column?

sort -u -t, -k1,1 file
  • -u for unique
  • -t, so comma is the delimiter
  • -k1,1 for the key field 1

Test result:

[email protected],2009-11-27 00:58:29.793000000,xx3.net,255.255.255.0 
[email protected],2009-11-27 01:05:47.893000000,xx2.net,127.0.0.1 

Counting the Number of keywords in a dictionary in python

In order to count the number of keywords in a dictionary:

def dict_finder(dict_finders):
    x=input("Enter the thing you want to find: ")
    if x in dict_finders:
        print("Element found")
    else:
        print("Nothing found:")

What is :: (double colon) in Python when subscripting sequences?

TL;DR

This visual example will show you how to a neatly select elements in a NumPy Matrix (2 dimensional array) in a pretty entertaining way (I promise). Step 2 below illustrate the usage of that "double colons" :: in question.

(Caution: this is a NumPy array specific example with the aim of illustrating the a use case of "double colons" :: for jumping of elements in multiple axes. This example does not cover native Python data structures like List).

One concrete example to rule them all...

Say we have a NumPy matrix that looks like this:

In [1]: import numpy as np

In [2]: X = np.arange(100).reshape(10,10)

In [3]: X
Out[3]:
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
       [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
       [50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
       [60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
       [70, 71, 72, 73, 74, 75, 76, 77, 78, 79],
       [80, 81, 82, 83, 84, 85, 86, 87, 88, 89],
       [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]])

Say for some reason, your boss wants you to select the following elements:

enter image description here

"But How???"... Read on! (We can do this in a 2-step approach)

Step 1 - Obtain subset

Specify the "start index" and "end index" in both row-wise and column-wise directions.

enter image description here

In code:

In [5]: X2 = X[2:9,3:8]

In [6]: X2
Out[6]:
array([[23, 24, 25, 26, 27],
       [33, 34, 35, 36, 37],
       [43, 44, 45, 46, 47],
       [53, 54, 55, 56, 57],
       [63, 64, 65, 66, 67],
       [73, 74, 75, 76, 77],
       [83, 84, 85, 86, 87]])

Notice now we've just obtained our subset, with the use of simple start and end indexing technique. Next up, how to do that "jumping"... (read on!)

Step 2 - Select elements (with the "jump step" argument)

We can now specify the "jump steps" in both row-wise and column-wise directions (to select elements in a "jumping" way) like this:

enter image description here

In code (note the double colons):

In [7]: X3 = X2[::3, ::2]

In [8]: X3
Out[8]:
array([[23, 25, 27],
       [53, 55, 57],
       [83, 85, 87]])

We have just selected all the elements as required! :)

 Consolidate Step 1 (start and end) and Step 2 ("jumping")

Now we know the concept, we can easily combine step 1 and step 2 into one consolidated step - for compactness:

In [9]: X4 = X[2:9,3:8][::3,::2]

    In [10]: X4
    Out[10]:
    array([[23, 25, 27],
           [53, 55, 57],
           [83, 85, 87]])

Done!

Get file from project folder java

This sounds like the file is embedded within your application.

You should be using getClass().getResource("/path/to/your/resource.txt"), which returns an URL or getClass().getResourceAsStream("/path/to/your/resource.txt");

If it's not an embedded resource, then you need to know the relative path from your application's execution context to where your file exists

Generating random, unique values C#

hi here i posted one video ,and it explains how to generate unique random number

  public List<int> random_generator(){

  Random random = new Random();

   List<int> random_container = new List<int>;

     do{

       int random_number = random.next(10);

      if(!random_container.contains(random_number){

       random_container.add(random_number)
  }
}
   while(random_container.count!=10);


     return random_container; 
  }

here ,,, in random container you will get non repeated 10 numbers starts from 0 to 9(10 numbers) as random.. thank you........

LINQ query to find if items in a list are contained in another list

var output = emails.Where(e => domains.All(d => !e.EndsWith(d)));

Or if you prefer:

var output = emails.Where(e => !domains.Any(d => e.EndsWith(d)));

Convert Python dict into a dataframe

This is how it worked for me :

df= pd.DataFrame([d.keys(), d.values()]).T
df.columns= ['keys', 'values']  # call them whatever you like

I hope this helps

C# Dictionary get item by index

you can easily access elements by index , by use System.Linq

Here is the sample

First add using in your class file

using System.Linq;

Then

yourDictionaryData.ElementAt(i).Key
yourDictionaryData.ElementAt(i).Value

Hope this helps.

disable Bootstrap's Collapse open/close animation

Bootstrap 2 CSS solution:

.collapse {  transition: height 0.01s; }  

NB: setting transition: none disables the collapse functionnality.


Bootstrap 4 solution:

.collapsing {
  transition: none !important;
}

Array initialization syntax when not in a declaration

Why is this blocked by Java?

You'd have to ask the Java designers. There might be some subtle grammatical reason for the restriction. Note that some of the array creation / initialization constructs were not in Java 1.0, and (IIRC) were added in Java 1.1.

But "why" is immaterial ... the restriction is there, and you have to live with it.

I know how to work around it, but from time to time it would be simpler.

You can write this:

AClass[] array;
...
array = new AClass[]{object1, object2};

How to concat a string to xsl:value-of select="...?

You can use the rather sensibly named xpath function called concat here

<a>
   <xsl:attribute name="href">
      <xsl:value-of select="concat('myText:', /*/properties/property[@name='report']/@value)" />
   </xsl:attribute>
</a>  

Of course, it doesn't have to be text here, it can be another xpath expression to select an element or attribute. And you can have any number of arguments in the concat expression.

Do note, you can make use of Attribute Value Templates (represented by the curly braces) here to simplify your expression

<a href="{concat('myText:', /*/properties/property[@name='report']/@value)}"></a>

git status shows modifications, git checkout -- <file> doesn't remove them

If you clone a repository and instantly see pending changes, then the repository is in an inconsistent state. Please do NOT comment out * text=auto from the .gitattributes file. That was put there specifically because the owner of the repository wants all files stored consistently with LF line endings.

As stated by HankCa, following the instructions on https://help.github.com/articles/dealing-with-line-endings/ is the way to go to fix the problem. Easy button:

git clone git@host:repo-name
git checkout -b normalize-line-endings
git add .
git commit -m "Normalize line endings"
git push
git push -u origin normalize-line-endings

Then merge (or pull request) the branch to the owner of the repo.

UPDATE with CASE and IN - Oracle

Got a solution that runs. Don't know if it is optimal though. What I do is to split the string according to http://blogs.oracle.com/aramamoo/2010/05/how_to_split_comma_separated_string_and_pass_to_in_clause_of_select_statement.html

Using:
select regexp_substr(' 1, 2 , 3 ','[^,]+', 1, level) from dual
connect by regexp_substr('1 , 2 , 3 ', '[^,]+', 1, level) is not null;

So my final code looks like this ($bp_gr1' are strings like 1,2,3):

UPDATE TAB1
SET    BUDGPOST_GR1 =
          CASE
             WHEN ( BUDGPOST IN (SELECT     REGEXP_SUBSTR ( '$BP_GR1',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                 FROM       DUAL
                                 CONNECT BY REGEXP_SUBSTR ( '$BP_GR1',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                               IS NOT NULL) )
             THEN
                'BP_GR1'
             WHEN ( BUDGPOST IN (SELECT     REGEXP_SUBSTR ( ' $BP_GR2',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                 FROM       DUAL
                                 CONNECT BY REGEXP_SUBSTR ( '$BP_GR2',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                               IS NOT NULL) )
             THEN
                'BP_GR2'
             WHEN ( BUDGPOST IN (SELECT     REGEXP_SUBSTR ( ' $BP_GR3',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                 FROM       DUAL
                                 CONNECT BY REGEXP_SUBSTR ( '$BP_GR3',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                               IS NOT NULL) )
             THEN
                'BP_GR3'
             WHEN ( BUDGPOST IN (SELECT     REGEXP_SUBSTR ( '$BP_GR4',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                 FROM       DUAL
                                 CONNECT BY REGEXP_SUBSTR ( '$BP_GR4',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                               IS NOT NULL) )
             THEN
                'BP_GR4'
             ELSE
                'SAKNAR BUDGETGRUPP'
          END;

Is there a way to make it run faster?

How to index characters in a Golang string?

Go doesn't really have a character type as such. byte is often used for ASCII characters, and rune is used for Unicode characters, but they are both just aliases for integer types (uint8 and int32). So if you want to force them to be printed as characters instead of numbers, you need to use Printf("%c", x). The %c format specification works for any integer type.

How can I inspect the file system of a failed `docker build`?

Debugging build step failures is indeed very annoying.

The best solution I have found is to make sure that each step that does real work succeeds, and adding a check after those that fails. That way you get a committed layer that contains the outputs of the failed step that you can inspect.

A Dockerfile, with an example after the # Run DB2 silent installer line:

#
# DB2 10.5 Client Dockerfile (Part 1)
#
# Requires
#   - DB2 10.5 Client for 64bit Linux ibm_data_server_runtime_client_linuxx64_v10.5.tar.gz
#   - Response file for DB2 10.5 Client for 64bit Linux db2rtcl_nr.rsp 
#
#
# Using Ubuntu 14.04 base image as the starting point.
FROM ubuntu:14.04

MAINTAINER David Carew <[email protected]>

# DB2 prereqs (also installing sharutils package as we use the utility uuencode to generate password - all others are required for the DB2 Client) 
RUN dpkg --add-architecture i386 && apt-get update && apt-get install -y sharutils binutils libstdc++6:i386 libpam0g:i386 && ln -s /lib/i386-linux-gnu/libpam.so.0 /lib/libpam.so.0
RUN apt-get install -y libxml2


# Create user db2clnt
# Generate strong random password and allow sudo to root w/o password
#
RUN  \
   adduser --quiet --disabled-password -shell /bin/bash -home /home/db2clnt --gecos "DB2 Client" db2clnt && \
   echo db2clnt:`dd if=/dev/urandom bs=16 count=1 2>/dev/null | uuencode -| head -n 2 | grep -v begin | cut -b 2-10` | chgpasswd && \
   adduser db2clnt sudo && \
   echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers

# Install DB2
RUN mkdir /install
# Copy DB2 tarball - ADD command will expand it automatically
ADD v10.5fp9_linuxx64_rtcl.tar.gz /install/
# Copy response file
COPY  db2rtcl_nr.rsp /install/
# Run  DB2 silent installer
RUN mkdir /logs
RUN (/install/rtcl/db2setup -t /logs/trace -l /logs/log -u /install/db2rtcl_nr.rsp && touch /install/done) || /bin/true
RUN test -f /install/done || (echo ERROR-------; echo install failed, see files in container /logs directory of the last container layer; echo run docker run '<last image id>' /bin/cat /logs/trace; echo ----------)
RUN test -f /install/done

# Clean up unwanted files
RUN rm -fr /install/rtcl

# Login as db2clnt user
CMD su - db2clnt

How can I disable notices and warnings in PHP within the .htaccess file?

I used ini_set('display_errors','off'); and it worked great.

sublime text2 python error message /usr/bin/python: can't find '__main__' module in ''

Note to anyone else:

If you have a directory like so, you can add a __main__.py file to tell the interpreter what to execute if you call the module directly.

my_module
  |
  | __init__.py
  | my_cool_file.py # print "Hello  World"
  | __main__.py # import my_cool_file

$ python my_module # Hello World

How to auto-scroll to end of div when data is added?

var objDiv = document.getElementById("divExample");
objDiv.scrollTop = objDiv.scrollHeight;

In jQuery, how do I select an element by its name attribute?

For anyone who doesn't want to include a library to do something really simple:

document.querySelector('[name="theme"]:checked').value;

jsfiddle

For a performance overview of the current answers check here

Update Query with INNER JOIN between tables in 2 different databases on 1 server

Update one table using Inner Join

  UPDATE Table1 SET name=ml.name
FROM table1 t inner JOIN
Table2 ml ON t.ID= ml.ID  

Static array vs. dynamic array in C++

static arrary meens with giving on elements in side the array

dynamic arrary meens without giving on elements in side the array

example:

     char a[10]; //static array
       char a[];  //dynamic array

How do I copy items from list to list without foreach?

OK this is working well From the suggestions above GetRange( ) does not work for me with a list as an argument...so sweetening things up a bit from posts above: ( thanks everyone :)

/*  Where __strBuf is a string list used as a dumping ground for data  */
public List < string > pullStrLst( )
{
    List < string > lst;

    lst = __strBuf.GetRange( 0, __strBuf.Count );     

    __strBuf.Clear( );

    return( lst );
}

Intersect Two Lists in C#

From performance point of view if two lists contain number of elements that differ significantly, you can try such approach (using conditional operator ?:):

1.First you need to declare a converter:

Converter<string, int> del = delegate(string s) { return Int32.Parse(s); };

2.Then you use a conditional operator:

var r = data1.Count > data2.Count ?
 data2.ConvertAll<int>(del).Intersect(data1) :
 data1.Select(v => v.ToString()).Intersect(data2).ToList<string>().ConvertAll<int>(del);

You convert elements of shorter list to match the type of longer list. Imagine an execution speed if your first set contains 1000 elements and second only 10 (or opposite as it doesn't matter) ;-)

As you want to have a result as List, in a last line you convert the result (only result) back to int.

Go to particular revision

One way would be to create all commits ever made to patches. checkout the initial commit and then apply the patches in order after reading.

use git format-patch <initial revision> and then git checkout <initial revision>. you should get a pile of files in your director starting with four digits which are the patches.

when you are done reading your revision just do git apply <filename> which should look like git apply 0001-* and count.

But I really wonder why you wouldn't just want to read the patches itself instead? Please post this in your comments because I'm curious.

the git manual also gives me this:

git show next~10:Documentation/README

Shows the contents of the file Documentation/README as they were current in the 10th last commit of the branch next.

you could also have a look at git blame filename which gives you a listing where each line is associated with a commit hash + author.

Access-Control-Allow-Origin and Angular.js $http

I've had success with express and editing the res.header. Mine matches yours pretty closely but I have a different Allow-Headers as noted below:

res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

I'm also using Angular and Node/Express, but I don't have the headers called out in the Angular code only the node/express

How to add leading zeros for for-loop in shell?

From bash 4.0 onward, you can use Brace Expansion with fixed length strings. See below for the original announcement.

It will do just what you need, and does not require anything external to the shell.

$ echo {01..05}
01 02 03 04 05

for num in {01..05}
do
  echo $num
done
01
02
03
04
05

CHANGES, release bash-4.0, section 3

This is a terse description of the new features added to bash-4.0 since the release of bash-3.2.

. . .

z. Brace expansion now allows zero-padding of expanded numeric values and will add the proper number of zeroes to make sure all values contain the same number of digits.

How to set corner radius of imageView?

There is one tiny difference in Swift 3.0 and Xcode8

Whenever you want to apply corner radius to UIView, make sure you call yourUIView.layoutIfNeeded() before calling cornerRadius.

Otherwise, it will return the default value for UIView's height and width (1000.0) which will probably make your View disappear.

Always make sure that all effects that changes the size of UIView (Interface builder constraints etc) are applied before setting any layer properties.

Example of UIView class implementation

class BadgeView: UIView {

  override func awakeFromNib() {

    self.layoutIfNeeded()
    layer.cornerRadius = self.frame.height / 2.0
    layer.masksToBounds = true

   }
 }

React won't load local images

Here is what worked for me. First, let us understand the problem. You cannot use a variable as argument to require. Webpack needs to know what files to bundle at compile time.

When I got the error, I thought it may be related to path issue as in absolute vs relative. So I passed a hard-coded value to require like below: <img src={require("../assets/images/photosnap.svg")} alt="" />. It was working fine. But in my case the value is a variable coming from props. I tried to pass a string literal variable as some suggested. It did not work. Also I tried to define a local method using switch case for all 10 values (I knew it was not best solution, but I just wanted it to work somehow). That too did not work. Then I came to know that we can NOT pass variable to the require.

As a workaround I have modified the data in the data.json file to confine it to just the name of my image. This image name which is coming from the props as a String literal. I concatenated it to the hard coded value, like so:

import React from "react";

function JobCard(props) {  

  const { logo } = props;
  
  return (
      <div className="jobCards">
          <img src={require(`../assets/images/${logo}`)} alt="" /> 
      </div>
    )
} 
  

The actual value contained in the logo would be coming from data.json file and would refer to some image name like photosnap.svg.

How can I make my string property nullable?

It's been a while when the question has been asked and C# changed not much but became a bit better. Take a look Nullable reference types (C# reference)

string notNull = "Hello";
string? nullable = default;
notNull = nullable!; // null forgiveness

C# as a language a "bit" outdated from modern languages and became misleading.

for instance in typescript, swift there's a "?" to clearly say it's a nullable type, be careful. It's pretty clear and it's awesome. C# doesn't/didn't have this ability, as a result, a simple contract IPerson very misleading. As per C# FirstName and LastName could be null but is it true? is per business logic FirstName/LastName really could be null? the answer is we don't know because C# doesn't have the ability to say it directly.

interface IPerson
{
  public string FirstName;
  public string LastName;
}

class method generates "TypeError: ... got multiple values for keyword argument ..."

Thanks for the instructive posts. I'd just like to keep a note that if you're getting "TypeError: foodo() got multiple values for keyword argument 'thing'", it may also be that you're mistakenly passing the 'self' as a parameter when calling the function (probably because you copied the line from the class declaration - it's a common error when one's in a hurry).

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

I found this free website that will make for you the policy AND host it:

https://www.freeprivacypolicy.com/

Then add it to the play store under Store Listing - at the bottom add the public link for the policy that you got from https://www.freeprivacypolicy.com/

Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve?

I just fund another way to do the same workaround. Because of I hadn' t the possibility to click on the yellow triangle (even if I have admin role), when you go inside testflight, then iOS (under "Build") instead of yellow triangle click the version number, another page will open and you will find on top right something like add compliance information (sorry if I am not totally accurate but I have the italian version but it would be really easy to find). Then you can do the same even if you, like me, are not able to click on yellow triangle.

Recursive file search using PowerShell

I use this to find files and then have PowerShell display the entire path of the results:

dir -Path C:\FolderName -Filter FileName.fileExtension -Recurse | %{$_.FullName}

You can always use the wildcard * in the FolderName and/or FileName.fileExtension. For example:

dir -Path C:\Folder* -Filter File*.file* -Recurse | %{$_.FullName}

The above example will search any folder in the C:\ drive beginning with the word Folder. So if you have a folder named FolderFoo and FolderBar PowerShell will show results from both of those folders.

The same goes for the file name and file extension. If you want to search for a file with a certain extension, but don't know the name of the file, you can use:

dir -Path C:\FolderName -Filter *.fileExtension -Recurse | %{$_.FullName}

Or vice versa:

dir -Path C:\FolderName -Filter FileName.* -Recurse | %{$_.FullName}

JQuery confirm dialog

Have you tried using the official JQueryUI implementation (not jQuery only) : ?

Insert ellipsis (...) into HTML tag if content too wide

Pure CSS Multi-line Ellipsis for text content:

_x000D_
_x000D_
.container{_x000D_
    position: relative;  /* Essential */_x000D_
    background-color: #bbb;  /* Essential */_x000D_
    padding: 20px; /* Arbritrary */_x000D_
}_x000D_
.text {_x000D_
    overflow: hidden;  /* Essential */_x000D_
    /*text-overflow: ellipsis; Not needed */_x000D_
    line-height: 16px;  /* Essential */_x000D_
    max-height: 48px; /* Multiples of line-height */_x000D_
}_x000D_
.ellipsis {_x000D_
    position: absolute;/* Relies on relative container */_x000D_
    bottom: 20px; /* Matches container padding */_x000D_
    right: 20px; /* Matches container padding */_x000D_
    height: 16px; /* Matches line height */_x000D_
    width: 30px; /* Arbritrary */_x000D_
    background-color: inherit; /* Essential...or specify a color */_x000D_
    padding-left: 8px; /* Arbritrary */_x000D_
}
_x000D_
<div class="container">_x000D_
    <div class="text">_x000D_
        Lorem ipsum dolor sit amet, consectetur eu in adipiscing elit. Aliquam consectetur venenatis blandit. Praesent vehicula, libero non pretium vulputate, lacus arcu facilisis lectus, sed feugiat tellus nulla eu dolor. Nulla porta bibendum lectus quis euismod. Aliquam volutpat ultricies porttitor. Cras risus nisi, accumsan vel cursus ut, sollicitudin vitae dolor. Fusce scelerisque eleifend lectus in bibendum. Suspendisse lacinia egestas felis a volutpat. Aliquam volutpat ultricies porttitor. Cras risus nisi, accumsan vel cursus ut, sollicitudin vitae dolor. Fusce scelerisque eleifend lectus in bibendum. Suspendisse lacinia egestas felis a volutpat._x000D_
    </div>_x000D_
    <div class="ellipsis">...</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Please checkout the snippet for a live example.

How do I purge a linux mail box with huge number of emails?

alternative way:

mail -N
d *
quit

-N Inhibits the initial display of message headers when reading mail or editing a mail folder.
d * delete all mails

What's the difference between 'git merge' and 'git rebase'?

For easy understand can see my figure.

Rebase will change commit hash, so that if you want to avoid much of conflict, just use rebase when that branch is done/complete as stable.

enter image description here

Convert SVG image to PNG with PHP

This is v. easy, have been doing work on this for the past few weeks.

You need the Batik SVG Toolkit. Download, and place the files in the same directory as the SVG you want to convert to a JPEG, also make sure you unzip it first.

Open the terminal, and run this command:

java -jar batik-rasterizer.jar -m image/jpeg -q 0.8 NAME_OF_SVG_FILE.svg

That should output a JPEG of the SVG file. Really easy. You can even just place it in a loop and convert loads of SVGs,

import os

svgs = ('test1.svg', 'test2.svg', 'etc.svg') 
for svg in svgs:
    os.system('java -jar batik-rasterizer.jar -m image/jpeg -q 0.8 '+str(svg)+'.svg')

Android how to use Environment.getExternalStorageDirectory()

Have in mind though, that getExternalStorageDirectory() is not going to work properly on some phones e.g. my Motorola razr maxx, as it has 2 cards /mnt/sdcard and /mnt/sdcard-ext - for internal and external SD cards respectfully. You will be getting the /mnt/sdcard only reply every time. Google must provide a way to deal with such a situation. As it renders many SD card aware apps (i.e card backup) failing miserably on these phones.

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

How do I initialise all entries of a matrix with a specific value?

As mentioned in other answers you can use:

>> tic; x=5*ones(10,1); toc
Elapsed time is 0.000415 seconds.

An even faster method is:

>> tic;  x=5; x=x(ones(10,1)); toc
Elapsed time is 0.000257 seconds.

Using await outside of an async function

Top level await is not supported. There are a few discussions by the standards committee on why this is, such as this Github issue.

There's also a thinkpiece on Github about why top level await is a bad idea. Specifically he suggests that if you have code like this:

// data.js
const data = await fetch( '/data.json' );
export default data;

Now any file that imports data.js won't execute until the fetch completes, so all of your module loading is now blocked. This makes it very difficult to reason about app module order, since we're used to top level Javascript executing synchronously and predictably. If this were allowed, knowing when a function gets defined becomes tricky.

My perspective is that it's bad practice for your module to have side effects simply by loading it. That means any consumer of your module will get side effects simply by requiring your module. This badly limits where your module can be used. A top level await probably means you're reading from some API or calling to some service at load time. Instead you should just export async functions that consumers can use at their own pace.

How to make a Java Generic method static?

public static <E> E[] appendToArray(E[] array, E item) { ...

Note the <E>.

Static generic methods need their own generic declaration (public static <E>) separate from the class's generic declaration (public class ArrayUtils<E>).

If the compiler complains about a type ambiguity in invoking a static generic method (again not likely in your case, but, generally speaking, just in case), here's how to explicitly invoke a static generic method using a specific type (_class_.<_generictypeparams_>_methodname_):

String[] newStrings = ArrayUtils.<String>appendToArray(strings, "another string");

This would only happen if the compiler can't determine the generic type because, e.g. the generic type isn't related to the method arguments.

"Actual or formal argument lists differs in length"

The default constructor has no arguments. You need to specify a constructor:

    public Friends( String firstName, String age) { ... }

Reading DataSet

TL;DR: - grab the datatable from the dataset and read from the rows property.

            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            DataColumn col = new DataColumn("Id", typeof(int));
            dt.Columns.Add(col);
            dt.Rows.Add(new object[] { 1 });
            ds.Tables.Add(dt);

            var row = ds.Tables[0].Rows[0];
            //access the ID column.  
            var id = (int) row.ItemArray[0];

A DataSet is a copy of data accessed from a database, but doesn't even require a database to use at all. It is preferred, though.

Note that if you are creating a new application, consider using an ORM, such as the Entity Framework or NHibernate, since DataSets are no longer preferred; however, they are still supported and as far as I can tell, are not going away any time soon.

If you are reading from standard dataset, then @KMC's answer is what you're looking for. The proper way to do this, though, is to create a Strongly-Typed DataSet and use that so you can take advantage of Intellisense. Assuming you are not using the Entity Framework, proceed.

If you don't already have a dedicated space for your data access layer, such as a project or an App_Data folder, I suggest you create one now. Otherwise, proceed as follows under your data project folder: Add > Add New Item > DataSet. The file created will have an .xsd extension.

You'll then need to create a DataTable. Create a DataTable (click on the file, then right click on the design window - the file has an .xsd extension - and click Add > DataTable). Create some columns (Right click on the datatable you just created > Add > Column). Finally, you'll need a table adapter to access the data. You'll need to setup a connection to your database to access data referenced in the dataset.

After you are done, after successfully referencing the DataSet in your project (using statement), you can access the DataSet with intellisense. This makes it so much easier than untyped datasets.

When possible, use Strongly-Typed DataSets instead of untyped ones. Although it is more work to create, it ends up saving you lots of time later with intellisense. You could do something like:

MyStronglyTypedDataSet trainDataSet = new MyStronglyTypedDataSet();
DataAdapterForThisDataSet dataAdapter = new DataAdapterForThisDataSet();
//code to fill the dataset 
//omitted - you'll have to either use the wizard to create data fill/retrieval
//methods or you'll use your own custom classes to fill the dataset.
if(trainDataSet.NextTrainDepartureTime > CurrentTime){
   trainDataSet.QueueNextTrain = true; //assumes QueueNextTrain is in your Strongly-Typed dataset
}
else
    //do some other work

The above example assumes that your Strongly-Typed DataSet has a column of type DateTime named NextTrainDepartureTime. Hope that helps!

How to make div appear in front of another?

Use the CSS z-index property. Elements with a greater z-index value are positioned in front of elements with smaller z-index values.

Note that for this to work, you also need to set a position style (position:absolute, position:relative, or position:fixed) on both/all of the elements you want to order.

R Error in x$ed : $ operator is invalid for atomic vectors

The reason you are getting this error is that you have a vector.

If you want to use the $ operator, you simply need to convert it to a data.frame. But since you only have one row in this particular case, you would also need to transpose it; otherwise bob and ed will become your row names instead of your column names which is what I think you want.

x <- c(1, 2)
x
names(x) <- c("bob", "ed")
x <- as.data.frame(t(x))
x$ed
[1] 2

Reading in a JSON File Using Swift

This worked for me with XCode 8.3.3

func fetchPersons(){

    if let pathURL = Bundle.main.url(forResource: "Person", withExtension: "json"){

        do {

            let jsonData = try Data(contentsOf: pathURL, options: .mappedIfSafe)

            let jsonResult = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as! [String: Any]
            if let persons = jsonResult["person"] as? [Any]{

                print(persons)
            }

        }catch(let error){
            print (error.localizedDescription)
        }
    }
}

Maximum concurrent Socket.IO connections

This guy appears to have succeeded in having over 1 million concurrent connections on a single Node.js server.

http://blog.caustik.com/2012/08/19/node-js-w1m-concurrent-connections/

It's not clear to me exactly how many ports he was using though.