Programs & Examples On #Atlas

The ATLAS (Automatically Tuned Linear Algebra Software) project is an ongoing research effort focusing on applying empirical techniques in order to provide portable performance.

Psql could not connect to server: No such file or directory, 5432 error?

I'm on Kali Linux. I had to remove the brew version of postgresql with

brew uninstall postgresql

sudo -u postgres psql got me into root postgres

Spring Data and Native Query with pagination

Replacing /#pageable/ with ?#{#pageable} allow to do pagination. Adding PageableDefault allow you to set size of page Elements.

How to markdown nested list items in Bitbucket?

Use 4 spaces.

# Unordered list

* Item 1
* Item 2
* Item 3
    * Item 3a
    * Item 3b
    * Item 3c

# Ordered list

1. Step 1
2. Step 2
3. Step 3
    1. Step 3.1
    2. Step 3.2
    3. Step 3.3

# List in list

1. Step 1
2. Step 2
3. Step 3
    * Item 3a
    * Item 3b
    * Item 3c

Here's a screenshot from that updated repo:

screenshot

Thanks @Waylan, your comment was exactly right.

Nginx upstream prematurely closed connection while reading response header from upstream, for large requests

I had the same error for quite a while, and here what fixed it for me.

I simply declared in service that i use what follows:

Description= Your node service description
After=network.target

[Service]
Type=forking
PIDFile=/tmp/node_pid_name.pid
Restart=on-failure
KillSignal=SIGQUIT
WorkingDirectory=/path/to/node/app/root/directory
ExecStart=/path/to/node /path/to/server.js

[Install]
WantedBy=multi-user.target

What should catch your attention here is "After=network.target". I spent days and days looking for fixes on nginx side, while the problem was just that. To be sure, stop running the node service you have, launch the ExecStart command directly and try to reproduce the bug. If it doesn't pop, it just means that your service has a problem. At least this is how i found my answer.

For everybody else, good luck!

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

Using webpack I used this in webpack.config.js:

var plugins = [

    ...

    new webpack.ProvidePlugin({
        $: "jquery",
        jQuery: "jquery",
        'window.jQuery': 'jquery',
        'window.Tether': 'tether',
        tether: 'tether',
        Tether: 'tether'
    })
];

It seems like Tether was the one it was looking for:

var Tooltip = function ($) {

  /**
   * Check for Tether dependency
   * Tether - http://tether.io/
   */
  if (typeof Tether === 'undefined') {
    throw new Error('Bootstrap tooltips require Tether (http://tether.io/)');
  }

ImportError: No module named pandas

You're missing a few (not terribly clear) steps. Pandas is distributed through pip as a wheel, which means you need to do:

pip install wheel
pip install pandas

You're probably going to run into other issues after this - it looks like you're installing on Windows which isn't the most friendly of targets for numpy/scipy/pandas. Alternatively, you could pickup a binary installer from here.

You also had an error installing numpy. Like before, I recommend grabbing a binary installer for this, as it's not a simple process. However, you can resolve your current error by installing this package from Microsoft.

While it's completely possible to get a perfect environment setup on Windows, I have found the quality-of-life for a Python dev is vastly improved by setting up a debian VM. Especially with the scientific packages, you will run into many cases like this.

What is the easiest way to install BLAS and LAPACK for scipy?

Either use SciPy whl, download the appropriate one and run pip install <whl_file>

OR

Read through SciPy Windows issue and run one of the methods.

OR

Use Miniconda.

Additionally, install Visual C++ compiler for python2.7 in-case it asks for it.

ImportError: No module named sklearn.cross_validation

May be it's due to the deprecation of sklearn.cross_validation. Please replace sklearn.cross_validation with sklearn.model_selection

Ref- https://github.com/amueller/scipy_2015_sklearn_tutorial/issues/60

How to see remote tags?

Even without cloning or fetching, you can check the list of tags on the upstream repo with git ls-remote:

git ls-remote --tags /url/to/upstream/repo

(as illustrated in "When listing git-ls-remote why there's “^{}” after the tag name?")

xbmono illustrates in the comments that quotes are needed:

git ls-remote --tags /some/url/to/repo "refs/tags/MyTag^{}"

Note that you can always push your commits and tags in one command with (git 1.8.3+, April 2013):

git push --follow-tags

See Push git commits & tags simultaneously.


Regarding Atlassian SourceTree specifically:

Note that, from this thread, SourceTree ONLY shows local tags.

There is an RFE (Request for Enhancement) logged in SRCTREEWIN-4015 since Dec. 2015.

A simple workaround:

see a list of only unpushed tags?

git push --tags

or check the "Push all tags" box on the "Push" dialog box, all tags will be pushed to your remote.

https://community.atlassian.com/tnckb94959/attachments/tnckb94959/sourcetree-questions/10923/1/Screen%20Shot%202015-12-15%20at%208.49.48%20AM.png

That way, you will be "sure that they are present in remote so that other developers can pull them".

How to rollback everything to previous commit

I searched for multiple options to get my git reset to specific commit, but most of them aren't so satisfactory.

I generally use this to reset the git to the specific commit in source tree.

  1. select commit to reset on sourcetree.

  2. In dropdowns select the active branch , first Parent Only

  3. And right click on "Reset branch to this commit" and select hard reset option (soft, mixed and hard)

  4. and then go to terminal git push -f

You should be all set!

Basic authentication for REST API using spring restTemplate

(maybe) the easiest way without importing spring-boot.

restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor("user", "password"));

How do I add Git version control (Bitbucket) to an existing source code folder?

You can init a Git directory in an directory containing other files. After that you can add files to the repository and commit there.

Create a project with some code:

$ mkdir my_project
$ cd my_project
$ echo "foobar" > some_file

Then, while inside the project's folder, do an initial commit:

$ git init
$ git add some_file
$ git commit -m "Initial commit"

Then for using Bitbucket or such you add a remote and push up:

$ git remote add some_name user@host:repo
$ git push some_name

You also might then want to configure tracking branches, etc. See git remote set-branches and related commands for that.

How to use new PasswordEncoder from Spring Security

Here is the implementation of BCrypt which is working for me.

in spring-security.xml

<authentication-manager >
    <authentication-provider ref="authProvider"></authentication-provider>  
    </authentication-manager>
<beans:bean id="authProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
  <beans:property name="userDetailsService" ref="userDetailsServiceImpl" />
  <beans:property name="passwordEncoder" ref="encoder" />
</beans:bean>
<!-- For hashing and salting user passwords -->
    <beans:bean id="encoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>

In java class

PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String hashedPassword = passwordEncoder.encode(yourpassword);

For more detailed example of spring security Click Here

Hope this will help.

Thanks

AngularJS : Custom filters and ng-repeat

One of the easiest ways to fix this is to use the $ which is the search all.

Here is a plunker that shows it working. I have changed the checkboxes to radio ( because I thought they should be complementary )..

http://plnkr.co/edit/dHzvm6hR5P8G4wPuTxoi?p=preview

If you want a very specific way of doing this ( instead of doing a generic search ) you need work with functions in the search.

The documentation is here

http://docs.angularjs.org/api/ng.filter:filter

What is the canonical way to check for errors using the CUDA runtime API?

The solution discussed here worked well for me. This solution uses built-in cuda functions and is very simple to implement.

The relevant code is copied below:

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

__global__ void foo(int *ptr)
{
  *ptr = 7;
}

int main(void)
{
  foo<<<1,1>>>(0);

  // make the host block until the device is finished with foo
  cudaDeviceSynchronize();

  // check for error
  cudaError_t error = cudaGetLastError();
  if(error != cudaSuccess)
  {
    // print the CUDA error message and exit
    printf("CUDA error: %s\n", cudaGetErrorString(error));
    exit(-1);
  }

  return 0;
}

2D cross-platform game engine for Android and iOS?

I've worked with Marmalade and I found it satisfying. Although it's not free and the developer community is also not large enough, but still you can handle most of the task using it's tutorials. (I'll write my tutorials once I got some times too).
IwGame is a good engine, developed by one of the Marmalade user. It's good for a basic game, but if you are looking for some serious advanced gaming stuff, you can also use Cocos2D-x with Marmalade. I've never used Cocos2D-x, but there's an Extension on Marmalade's Github.
Another good thing about Marmalade is it's EDK (Extension Development Kit), which lets you make an extension for whatever functionality you need which is available in native code, but not in Marmalade. I've used it to develop my own Customized Admob extension and a Facebook extension too.

Edit:
Marmalade now has it's own RAD(Rapid Application Development) tool just for 2D development, named as Marmalade Quick. Although the coding will be in Lua not in C++, but since it's built on top of C++ Marmalade, you can easily include a C++ library, and all other EDK extensions. Also the Cocos-2Dx and Box2D extensions are preincluded in the Quick. They recently launched it's Release version (It was in beta for 3-4 months). I think we you're really looking for only 2D development, you should give it a try.

Update:
Unity3D recently launched support for 2D games, which seems better than any other 2D game engine, due to it's GUI and Editor. Physics, sprite etc support is inbuilt. You can have a look on it.

Update 2
Marmalade is going to discontinue their SDK in favor of their in-house game production soon. So it won't be a wise decision to rely on that.

Dealing with "Xerces hell" in Java/Maven?

What would help, except for excluding, is modular dependencies.

With one flat classloading (standalone app), or semi-hierarchical (JBoss AS/EAP 5.x) this was a problem.

But with modular frameworks like OSGi and JBoss Modules, this is not so much pain anymore. The libraries may use whichever library they want, independently.

Of course, it's still most recommendable to stick with just a single implementation and version, but if there's no other way (using extra features from more libs), then modularizing might save you.

A good example of JBoss Modules in action is, naturally, JBoss AS 7 / EAP 6 / WildFly 8, for which it was primarily developed.

Example module definition:

<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="org.jboss.msc">
    <main-class name="org.jboss.msc.Version"/>
    <properties>
        <property name="my.property" value="foo"/>
    </properties>
    <resources>
        <resource-root path="jboss-msc-1.0.1.GA.jar"/>
    </resources>
    <dependencies>
        <module name="javax.api"/>
        <module name="org.jboss.logging"/>
        <module name="org.jboss.modules"/>
        <!-- Optional deps -->
        <module name="javax.inject.api" optional="true"/>
        <module name="org.jboss.threads" optional="true"/>
    </dependencies>
</module>

In comparison with OSGi, JBoss Modules is simpler and faster. While missing certain features, it's sufficient for most projects which are (mostly) under control of one vendor, and allow stunning fast boot (due to paralelized dependencies resolving).

Note that there's a modularization effort underway for Java 8, but AFAIK that's primarily to modularize the JRE itself, not sure whether it will be applicable to apps.

How do I get into a non-password protected Java keystore or change the password?

The password of keystore by default is: "changeit". I functioned to my commands you entered here, for the import of the certificate. I hope you have already solved your problem.

Git on Bitbucket: Always asked for password, even after uploading my public SSH key

Hello Googlers from the future.

On MacOS >= High Sierra, the SSH key is no longer saved to the KeyChain because of reasons.

Using ssh-add -K no longer survives restarts as well.

Here are 3 possible solutions.

I've used the first method successfully. I've created a file called config in ~/.ssh:

Host *
  AddKeysToAgent yes
  UseKeychain yes
  IdentityFile ~/.ssh/id_rsa

proper hibernate annotation for byte[]

What is the portable way to annotate a byte[] property?

It depends on what you want. JPA can persist a non annotated byte[]. From the JPA 2.0 spec:

11.1.6 Basic Annotation

The Basic annotation is the simplest type of mapping to a database column. The Basic annotation can be applied to a persistent property or instance variable of any of the following types: Java primitive, types, wrappers of the primitive types, java.lang.String, java.math.BigInteger, java.math.BigDecimal, java.util.Date, java.util.Calendar, java.sql.Date, java.sql.Time, java.sql.Timestamp, byte[], Byte[], char[], Character[], enums, and any other type that implements Serializable. As described in Section 2.8, the use of the Basic annotation is optional for persistent fields and properties of these types. If the Basic annotation is not specified for such a field or property, the default values of the Basic annotation will apply.

And Hibernate will map a it "by default" to a SQL VARBINARY (or a SQL LONGVARBINARY depending on the Column size?) that PostgreSQL handles with a bytea.

But if you want the byte[] to be stored in a Large Object, you should use a @Lob. From the spec:

11.1.24 Lob Annotation

A Lob annotation specifies that a persistent property or field should be persisted as a large object to a database-supported large object type. Portable applications should use the Lob annotation when mapping to a database Lob type. The Lob annotation may be used in conjunction with the Basic annotation or with the ElementCollection annotation when the element collection value is of basic type. A Lob may be either a binary or character type. The Lob type is inferred from the type of the persistent field or property and, except for string and character types, defaults to Blob.

And Hibernate will map it to a SQL BLOB that PostgreSQL handles with a oid .

Is this fixed in some recent version of hibernate?

Well, the problem is that I don't know what the problem is exactly. But I can at least say that nothing has changed since 3.5.0-Beta-2 (which is where a changed has been introduced)in the 3.5.x branch.

But my understanding of issues like HHH-4876, HHH-4617 and of PostgreSQL and BLOBs (mentioned in the javadoc of the PostgreSQLDialect) is that you are supposed to set the following property

hibernate.jdbc.use_streams_for_binary=false

if you want to use oid i.e. byte[] with @Lob (which is my understanding since VARBINARY is not what you want with Oracle). Did you try this?

As an alternative, HHH-4876 suggests using the deprecated PrimitiveByteArrayBlobType to get the old behavior (pre Hibernate 3.5).

References

  • JPA 2.0 Specification
    • Section 2.8 "Mapping Defaults for Non-Relationship Fields or Properties"
    • Section 11.1.6 "Basic Annotation"
    • Section 11.1.24 "Lob Annotation"

Resources

Could not obtain information about Windows NT group user

For me, the jobs were running under DOMAIN\Administrator and failing with the error message "The job failed. Unable to determine if the owner (DOMAIN\administrator) of job Agent history clean up: distribution has server access (reason: Could not obtain information about Windows NT group/user 'DOMAIN\administrator', error code 0x5. [SQLSTATE 42000] (Error 15404)). To fix this, I changed the owner of each failing job to sa. Worked flawlessly after that. The jobs were related to replication cleanup, but I'm unsure if they were manually added or were added as a part of the replication set-up - I wasn't involved with it, so I am not sure.

Performance of Java matrix math libraries?

There's a benchmark of various matrix packages available in java up on http://code.google.com/p/java-matrix-benchmark/ for a few different hardware configurations. But it's no substitute for doing your own benchmark.

Performance is going to vary with the type of hardware you've got (cpu, cores, memory, L1-3 cache, bus speed), the size of the matrices and the algorithms you intend to use. Different libraries have different takes on concurrency for different algorithms, so there's no single answer. You may also find that the overhead of translating to the form expected by a native library negates the performance advantage for your use case (some of the java libraries have more flexible options regarding matrix storage, which can be used for further performance optimizations).

Generally though, JAMA, Jampack and COLT are getting old, and do not represent the state of the current performance available in Java for linear algebra. More modern libraries make more effective use of multiple cores and cpu caches. JAMA was a reference implementation, and pretty much implements textbook algorithms with little regard to performance. COLT and IBM Ninja were the first java libraries to show that performance was possible in java, even if they lagged 50% behind native libraries.

Truncating a table in a stored procedure

As well as execute immediate you can also use

DBMS_UTILITY.EXEC_DDL_STATEMENT('TRUNCATE TABLE tablename;');

The statement fails because the stored proc is executing DDL and some instances of DDL could invalidate the stored proc. By using the execute immediate or exec_ddl approaches the DDL is implemented through unparsed code.

When doing this you neeed to look out for the fact that DDL issues an implicit commit both before and after execution.

Convert time fields to strings in Excel

This kind of this is always a pain in Excel, you have to convert the values using a function because once Excel converts the cells to Time they are stored internally as numbers. Here is the best way I know how to do it:

I'll assume that your times are in column A starting at row 1. In cell B1 enter this formula: =TEXT(A1,"hh:mm:ss AM/PM") , drag the formula down column B to the end of your data in column A. Select the values from column B, copy, go to column C and select "Paste Special", then select "Values". Select the cells you just copied into column C and format the cells as "Text".

What is Inversion of Control?

For example, task#1 is to create object. Without IOC concept, task#1 is supposed to be done by Programmer.But With IOC concept, task#1 would be done by container.

In short Control gets inverted from Programmer to container. So, it is called as inversion of control.

I found one good example here.

error: expected primary-expression before ')' token (C)

You should create a variable of the type SelectionneNonSelectionne.

struct SelectionneNonSelectionne var;

After that pass that variable to the function like

characterSelection(screen, var);

The error is caused since you are passing the type name SelectionneNonSelectionne

Best way to get user GPS location in background in Android

Use : GCM Network Manager

Run this to start a periodic task that will be ran even after re-boot:

PeriodicTask task = new PeriodicTask.Builder()
    .setService(MyLocationService.class)
    .setTag("periodic")
    .setPeriod(30L)
    .setPersisted(true)
    .build();
mGcmNetworkManager.schedule(task);

then in onRunTask() get current location and use it (in this example, event is submitted at the end to let UI know that location was found):

    public void getLastKnownLocation() {
    Location lastKnownGPSLocation;
    Location lastKnownNetworkLocation;
    String gpsLocationProvider = LocationManager.GPS_PROVIDER;
    String networkLocationProvider = LocationManager.NETWORK_PROVIDER;

    try {
        locationManager = (LocationManager) App.get().getSystemService(Context.LOCATION_SERVICE);

        lastKnownNetworkLocation = locationManager.getLastKnownLocation(networkLocationProvider);
        lastKnownGPSLocation = locationManager.getLastKnownLocation(gpsLocationProvider);

        if (lastKnownGPSLocation != null) {
            Log.i(TAG, "lastKnownGPSLocation is used.");
            this.mCurrentLocation = lastKnownGPSLocation;
        } else if (lastKnownNetworkLocation != null) {
            Log.i(TAG, "lastKnownNetworkLocation is used.");
            this.mCurrentLocation = lastKnownNetworkLocation;
        } else {
            Log.e(TAG, "lastLocation is not known.");
            return;
        }

        LocationChangedEvent event = new LocationChangedEvent();
        event.setLocation(mCurrentLocation);
        EventHelper.publishEvent(event);

    } catch (SecurityException sex) {
        Log.e(TAG, "Location permission is not granted!");
    }

    return;
}

The MyLocationService in whole:

public class MyLocationService extends GcmTaskService {
private static final String TAG = MyLocationService.class.getSimpleName();

private LocationManager locationManager;
private Location mCurrentLocation;

public static final String TASK_GET_LOCATION_ONCE="location_oneoff_task";
public static final String TASK_GET_LOCATION_PERIODIC="location_periodic_task";


private static final int RC_PLAY_SERVICES = 123;

@Override
public void onInitializeTasks() {
    // When your package is removed or updated, all of its network tasks are cleared by
    // the GcmNetworkManager. You can override this method to reschedule them in the case of
    // an updated package. This is not called when your application is first installed.
    //
    // This is called on your application's main thread.
    startPeriodicLocationTask(TASK_GET_LOCATION_PERIODIC,
            30L, null);
}

@Override
public int onRunTask(TaskParams taskParams) {
    Log.d(TAG, "onRunTask: " + taskParams.getTag());

    String tag = taskParams.getTag();
    Bundle extras = taskParams.getExtras();
    // Default result is success.
    int result = GcmNetworkManager.RESULT_SUCCESS;

    switch (tag) {
        case TASK_GET_LOCATION_ONCE:
            getLastKnownLocation();
            break;

        case TASK_GET_LOCATION_PERIODIC:
            getLastKnownLocation();
            break;

    }

    return result;
}


public void getLastKnownLocation() {
    Location lastKnownGPSLocation;
    Location lastKnownNetworkLocation;
    String gpsLocationProvider = LocationManager.GPS_PROVIDER;
    String networkLocationProvider = LocationManager.NETWORK_PROVIDER;

    try {
        locationManager = (LocationManager) App.get().getSystemService(Context.LOCATION_SERVICE);

        lastKnownNetworkLocation = locationManager.getLastKnownLocation(networkLocationProvider);
        lastKnownGPSLocation = locationManager.getLastKnownLocation(gpsLocationProvider);

        if (lastKnownGPSLocation != null) {
            Log.i(TAG, "lastKnownGPSLocation is used.");
            this.mCurrentLocation = lastKnownGPSLocation;
        } else if (lastKnownNetworkLocation != null) {
            Log.i(TAG, "lastKnownNetworkLocation is used.");
            this.mCurrentLocation = lastKnownNetworkLocation;
        } else {
            Log.e(TAG, "lastLocation is not known.");
            return;
        }

        LocationChangedEvent event = new LocationChangedEvent();
        event.setLocation(mCurrentLocation);
        EventHelper.publishEvent(event);

    } catch (SecurityException sex) {
        Log.e(TAG, "Location permission is not granted!");
    }

    return;
}

public static void startOneOffLocationTask(String tag, Bundle extras) {
    Log.d(TAG, "startOneOffLocationTask");

    GcmNetworkManager mGcmNetworkManager = GcmNetworkManager.getInstance(App.get());
    OneoffTask.Builder taskBuilder = new OneoffTask.Builder()
            .setService(MyLocationService.class)
            .setTag(tag);

    if (extras != null) taskBuilder.setExtras(extras);

    OneoffTask task = taskBuilder.build();
    mGcmNetworkManager.schedule(task);
}

public static void startPeriodicLocationTask(String tag, Long period, Bundle extras) {
    Log.d(TAG, "startPeriodicLocationTask");

    GcmNetworkManager mGcmNetworkManager = GcmNetworkManager.getInstance(App.get());
    PeriodicTask.Builder taskBuilder = new PeriodicTask.Builder()
            .setService(MyLocationService.class)
            .setTag(tag)
            .setPeriod(period)
            .setPersisted(true)
            .setRequiredNetwork(Task.NETWORK_STATE_CONNECTED);

    if (extras != null) taskBuilder.setExtras(extras);

    PeriodicTask task = taskBuilder.build();
    mGcmNetworkManager.schedule(task);
}




public static boolean checkPlayServicesAvailable(Activity activity) {
    GoogleApiAvailability availability = GoogleApiAvailability.getInstance();
    int resultCode = availability.isGooglePlayServicesAvailable(App.get());

    if (resultCode != ConnectionResult.SUCCESS) {
        if (availability.isUserResolvableError(resultCode)) {
            // Show dialog to resolve the error.
            availability.getErrorDialog(activity, resultCode, RC_PLAY_SERVICES).show();
        }
        return false;
    } else {
        return true;
    }
}

Also add these 2 to the AndroidManifest.xml:

 <manifest...
 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

 <application...
 <service
        android:name=".api.location.MyLocationService"
        android:exported="true"
        android:permission="com.google.android.gms.permission.BIND_NETWORK_TASK_SERVICE">
        <intent-filter>
            <action android:name="com.google.android.gms.gcm.ACTION_TASK_READY" />
        </intent-filter>
    </service>

jQuery get values of checked checkboxes into array

Needed the form elements named in the HTML as an array to be an array in the javascript object, as if the form was actually submitted.

If there is a form with multiple checkboxes such as:

<input name='breath[0]' type='checkbox' value='presence0'/>
<input name='breath[1]' type='checkbox' value='presence1'/>
<input name='breath[2]' type='checkbox' value='presence2'/>
<input name='serenity'  type='text' value='Is within the breath.'/>
...

The result is an object with:

data = {
   'breath':['presence0','presence1','presence2'],
   'serenity':'Is within the breath.'
}


var $form = $(this),
    data  = {};

$form.find("input").map(function()
{
    var $el  = $(this),
        name = $el.attr("name");

    if (/radio|checkbox/i.test($el.attr('type')) && !$el.prop('checked'))return;

    if(name.indexOf('[') > -1)
    {
        var name_ar = name.split(']').join('').split('['),
            name    = name_ar[0],
            index   = name_ar[1];

        data[name]  = data[name] || [];
        data[name][index] = $el.val();
    }
    else data[name] = $el.val();
});

And there are tons of answers here which helped improve my code, but they were either too complex or didn't do exactly want I wanted: Convert form data to JavaScript object with jQuery

Works but can be improved: only works on one-dimensional arrays and the resulting indexes may not be sequential. The length property of an array returns the next index number as the length of the array, not the actually length.

Hope this helped. Namaste!

How do I use the ternary operator ( ? : ) in PHP as a shorthand for "if / else"?

Quick and short way:

echo $address['street2'] ? : "No";

Here are some interesting examples, with one or more varied conditions.

$color = "blue";

// Condition #1 Show color without specifying variable 
echo $color ? : "Undefined";
echo "<br>";

// Condition #2
echo $color ? $color : "Undefined";
echo "<br>";

// Condition #3
echo ($color) ? $color : "Undefined";
echo "<br>";

// Condition #4
echo ($color == "blue") ? $color : "Undefined";
echo "<br>";

// Condition #5
echo ($color == "" ? $color : ($color == "blue" ? $color : "Undefined"));
echo "<br>";

// Condition #6
echo ($color == "blue" ? $color : ($color == "" ? $color : ($color == "" ? $color : "Undefined")));
echo "<br>";

// Condition #7
echo ($color != "") ? ($color != "" ? ($color == "blue" ? $color : "Undefined") : "Undefined") : "Undefined";
echo "<br>";

Find the number of columns in a table

SELECT COUNT(*)
  FROM INFORMATION_SCHEMA.COLUMNS
 WHERE table_catalog = 'database_name' -- the database
   AND table_name = 'table_name'

Fatal Error :1:1: Content is not allowed in prolog

Someone should mark Johannes Weiß's comment as the answer to this question. That is exactly why xml documents can't just be loaded in a DOM Document class.

http://en.wikipedia.org/wiki/Byte_order_mark

Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

You can find accurate answer for this query in oracle documentation page about multiple inheritance

  1. Multiple inheritance of state: Ability to inherit fields from multiple classes

    One reason why the Java programming language does not permit you to extend more than one class is to avoid the issues of multiple inheritance of state, which is the ability to inherit fields from multiple classes

    If multiple inheritance is allowed and When you create an object by instantiating that class, that object will inherit fields from all of the class's superclasses. It will cause two issues.

    1. What if methods or constructors from different super classes instantiate the same field?
    2. Which method or constructor will take precedence?
  2. Multiple inheritance of implementation: Ability to inherit method definitions from multiple classes

    Problems with this approach: name conflicts and ambiguity. If a subclass and superclass contain same method name (and signature), compiler can't determine which version to invoke.

    But java supports this type of multiple inheritance with default methods, which have been introduced since Java 8 release. The Java compiler provides some rules to determine which default method a particular class uses.

    Refer to below SE post for more details on resolving diamond problem:

    What are the differences between abstract classes and interfaces in Java 8?

  3. Multiple inheritance of type: Ability of a class to implement more than one interface.

    Since interface does not contain mutable fields, you do not have to worry about problems that result from multiple inheritance of state here.

How to create a private class method?

Just for the completeness, we can also avoid declaring private_class_method in a separate line. I personally don't like this usage but good to know that it exists.

private_class_method  def self.method_name
 ....
end

Java - checking if parseInt throws exception

You can use the try..catch statement in java, to capture an exception that may arise from Integer.parseInt().

Example:

try {
  int i = Integer.parseint(stringToParse);
  //parseInt succeded
} catch(Exception e)
{
   //parseInt failed
}

Check whether a path is valid

You could try using Path.IsPathRooted() in combination with Path.GetInvalidFileNameChars() to make sure the path is half-way okay.

Python: How to get stdout after running os.system?

These answers didn't work for me. I had to use the following:

import subprocess
p = subprocess.Popen(["pwd"], stdout=subprocess.PIPE)
out = p.stdout.read()
print out

Or as a function (using shell=True was required for me on Python 2.6.7 and check_output was not added until 2.7, making it unusable here):

def system_call(command):
    p = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True)
    return p.stdout.read()

How to configure logging to syslog in Python?

Here's the yaml dictConfig way recommended for 3.2 & later.

In log cfg.yml:

version: 1
disable_existing_loggers: true

formatters:
    default:
        format: "[%(process)d] %(name)s(%(funcName)s:%(lineno)s) - %(levelname)s: %(message)s"

handlers:
    syslog:
        class: logging.handlers.SysLogHandler
        level: DEBUG
        formatter: default
        address: /dev/log
        facility: local0

    rotating_file:
        class: logging.handlers.RotatingFileHandler
        level: DEBUG
        formatter: default
        filename: rotating.log
        maxBytes: 10485760 # 10MB
        backupCount: 20
        encoding: utf8

root:
    level: DEBUG
    handlers: [syslog, rotating_file]
    propogate: yes

loggers:
    main:
        level: DEBUG
        handlers: [syslog, rotating_file]
        propogate: yes

Load the config using:

log_config = yaml.safe_load(open('cfg.yml'))
logging.config.dictConfig(log_config)

Configured both syslog & a direct file. Note that the /dev/log is OS specific.

How can I verify a Google authentication API access token?

I need to somehow query Google and ask: Is this access token valid for [email protected]?

No. All you need is request standard login with Federated Login for Google Account Users from your API domain. And only after that you could compare "persistent user ID" with one you have from 'public interface'.

The value of realm is used on the Google Federated Login page to identify the requesting site to the user. It is also used to determine the value of the persistent user ID returned by Google.

So you need be from same domain as 'public interface'.

And do not forget that user needs to be sure that your API could be trusted ;) So Google will ask user if it allows you to check for his identity.

Adding a column to a data.frame

I believe that using "cbind" is the simplest way to add a column to a data frame in R. Below an example:

    myDf = data.frame(index=seq(1,10,1), Val=seq(1,10,1))
    newCol= seq(2,20,2)
    myDf = cbind(myDf,newCol)

How can I get the domain name of my site within a Django template?

If you want the actual HTTP Host header, see Daniel Roseman's comment on @Phsiao's answer. The other alternative is if you're using the contrib.sites framework, you can set a canonical domain name for a Site in the database (mapping the request domain to a settings file with the proper SITE_ID is something you have to do yourself via your webserver setup). In that case you're looking for:

from django.contrib.sites.models import Site

current_site = Site.objects.get_current()
current_site.domain

you'd have to put the current_site object into a template context yourself if you want to use it. If you're using it all over the place, you could package that up in a template context processor.

Can't install any package with node npm

If you're unlucky enough to be switching back and forth from a network behind a proxy and a network NOT behind a proxy, you may have forgotten that your NPM config is set to expect a proxy.

For me, I had to open up ~/.npmrc and comment out my proxy settings (while at home) and vice versa while at work (behind the proxy).

what is the use of annotations @Id and @GeneratedValue(strategy = GenerationType.IDENTITY)? Why the generationtype is identity?

Let me answer this question:
First of all, using annotations as our configure method is just a convenient method instead of coping the endless XML configuration file.

The @Idannotation is inherited from javax.persistence.Id, indicating the member field below is the primary key of current entity. Hence your Hibernate and spring framework as well as you can do some reflect works based on this annotation. for details please check javadoc for Id

The @GeneratedValue annotation is to configure the way of increment of the specified column(field). For example when using Mysql, you may specify auto_increment in the definition of table to make it self-incremental, and then use

@GeneratedValue(strategy = GenerationType.IDENTITY)

in the Java code to denote that you also acknowledged to use this database server side strategy. Also, you may change the value in this annotation to fit different requirements.

1. Define Sequence in database

For instance, Oracle has to use sequence as increment method, say we create a sequence in Oracle:

create sequence oracle_seq;

2. Refer the database sequence

Now that we have the sequence in database, but we need to establish the relation between Java and DB, by using @SequenceGenerator:

@SequenceGenerator(name="seq",sequenceName="oracle_seq")

sequenceName is the real name of a sequence in Oracle, name is what you want to call it in Java. You need to specify sequenceName if it is different from name, otherwise just use name. I usually ignore sequenceName to save my time.

3. Use sequence in Java

Finally, it is time to make use this sequence in Java. Just add @GeneratedValue:

@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq")

The generator field refers to which sequence generator you want to use. Notice it is not the real sequence name in DB, but the name you specified in name field of SequenceGenerator.

4. Complete

So the complete version should be like this:

public class MyTable
{
    @Id
    @SequenceGenerator(name="seq",sequenceName="oracle_seq")        
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq")               
    private Integer pid;
}

Now start using these annotations to make your JavaWeb development easier.

Loading context in Spring using web.xml

You can also load the context while defining the servlet itself (WebApplicationContext)

  <servlet>
    <servlet-name>admin</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>
                /WEB-INF/spring/*.xml
            </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>admin</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

rather than (ApplicationContext)

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>

<listener>
   <listener-class>
        org.springframework.web.context.ContextLoaderListener
   </listener-class>
</listener> 

or can do both together.

Drawback of just using WebApplicationContext is that it will load context only for this particular Spring entry point (DispatcherServlet) where as with above mentioned methods context will be loaded for multiple entry points (Eg. Webservice Servlet, REST servlet etc)

Context loaded by ContextLoaderListener will infact be a parent context to that loaded specifically for DisplacherServlet . So basically you can load all your business service, data access or repository beans in application context and separate out your controller, view resolver beans to WebApplicationContext.

Python memory usage of numpy arrays

In python notebooks I often want to filter out 'dangling' numpy.ndarray's, in particular the ones that are stored in _1, _2, etc that were never really meant to stay alive.

I use this code to get a listing of all of them and their size.

Not sure if locals() or globals() is better here.

import sys
import numpy
from humanize import naturalsize

for size, name in sorted(
    (value.nbytes, name)
    for name, value in locals().items()
    if isinstance(value, numpy.ndarray)):
  print("{:>30}: {:>8}".format(name, naturalsize(size)))

How to handle screen orientation change when progress dialog and background thread active?

I came up with a rock-solid solution for these issues that conforms with the 'Android Way' of things. I have all my long-running operations using the IntentService pattern.

That is, my activities broadcast intents, the IntentService does the work, saves the data in the DB and then broadcasts sticky intents. The sticky part is important, such that even if the Activity was paused during during the time after the user initiated the work and misses the real time broadcast from the IntentService we can still respond and pick up the data from the calling Activity. ProgressDialogs can work with this pattern quite nicely with onSaveInstanceState().

Basically, you need to save a flag that you have a progress dialog running in the saved instance bundle. Do not save the progress dialog object because this will leak the entire Activity. To have a persistent handle to the progress dialog, I store it as a weak reference in the application object. On orientation change or anything else that causes the Activity to pause (phone call, user hits home etc.) and then resume, I dismiss the old dialog and recreate a new dialog in the newly created Activity.

For indefinite progress dialogs this is easy. For progress bar style, you have to put the last known progress in the bundle and whatever information you're using locally in the activity to keep track of the progress. On restoring the progress, you'll use this information to re-spawn the progress bar in the same state as before and then update based on the current state of things.

So to summarize, putting long-running tasks into an IntentService coupled with judicious use of onSaveInstanceState() allows you to efficiently keep track of dialogs and restore then across the Activity life-cycle events. Relevant bits of Activity code are below. You'll also need logic in your BroadcastReceiver to handle Sticky intents appropriately, but that is beyond the scope of this.

public void doSignIn(View view) {
    waiting=true;
    AppClass app=(AppClass) getApplication();
    String logingon=getString(R.string.signon);
    app.Dialog=new WeakReference<ProgressDialog>(ProgressDialog.show(AddAccount.this, "", logingon, true));
    ...
}

@Override
protected void onSaveInstanceState(Bundle saveState) {
    super.onSaveInstanceState(saveState);
    saveState.putBoolean("waiting",waiting);
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if(savedInstanceState!=null) {
        restoreProgress(savedInstanceState);    
    }
    ...
}

private void restoreProgress(Bundle savedInstanceState) {
    waiting=savedInstanceState.getBoolean("waiting");
    if (waiting) {
        AppClass app=(AppClass) getApplication();
        ProgressDialog refresher=(ProgressDialog) app.Dialog.get();
        refresher.dismiss();
        String logingon=getString(R.string.signon);
        app.Dialog=new WeakReference<ProgressDialog>(ProgressDialog.show(AddAccount.this, "", logingon, true));
    }
}

How do I change column default value in PostgreSQL?

If you want to remove the default value constraint, you can do:

ALTER TABLE <table> ALTER COLUMN <column> DROP DEFAULT;

How to run python script in webpage

using flask library in Python you can achieve that. remember to store your HTML page to a folder named "templates" inside where you are running your python script.

so your folder would look like

  1. templates (folder which would contain your HTML file)
  2. your python script

this is a small example of your python script. This simply checks for plagiarism.

from flask import Flask
from flask import request
from flask import render_template
import stringComparison

app = Flask(__name__)

@app.route('/')
def my_form():
    return render_template("my-form.html") # this should be the name of your html file

@app.route('/', methods=['POST'])
def my_form_post():
    text1 = request.form['text1']
    text2 = request.form['text2']
    plagiarismPercent = stringComparison.extremelySimplePlagiarismChecker(text1,text2)
    if plagiarismPercent > 50 :
        return "<h1>Plagiarism Detected !</h1>"
    else :
        return "<h1>No Plagiarism Detected !</h1>"

if __name__ == '__main__':
    app.run()

This a small template of HTML file that is used

<!DOCTYPE html>
<html lang="en">
<body>
    <h1>Enter the texts to be compared</h1>
    <form action="." method="POST">
        <input type="text" name="text1">
        <input type="text" name="text2">
        <input type="submit" name="my-form" value="Check !">
    </form>
</body>
</html>

This is a small little way through which you can achieve a simple task of comparing two string and which can be easily changed to suit your requirements

Determining whether an object is a member of a collection in VBA

Your best bet is to iterate over the members of the collection and see if any match what you are looking for. Trust me I have had to do this many times.

The second solution (which is much worse) is to catch the "Item not in collection" error and then set a flag to say the item does not exist.

Create a string of variable length, filled with a repeated character

A great ES6 option would be to padStart an empty string. Like this:

var str = ''.padStart(10, "#");

Note: this won't work in IE (without a polyfill).

How to use a variable of one method in another method?

You can't. Variables defined inside a method are local to that method.

If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).


Looks like you're using instance methods instead of static ones.

If you don't want to create an object, you should declare all your methods static, so something like

private static void methodName(Argument args...)

If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.

private static int[][] array = new int[3][5];

Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.

Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.

Here's a final (shortened) example of what your code should be like:

public class Test3 {
    //Use this array in your methods
    private static int[][] scores = new int[3][5];

    /* Rather than just "Scores" name it so people know what
     * to expect
     */
    private static void createScores() {
        //Code...
    }
    //Other methods...

    /* Since you're now using static methods, you don't 
     * have to initialise an object and call its methods.
     */
    public static void main(String[] args){
        createScores();
        MD();   //Don't know what these do
        sumD(); //so I'll leave them.
    }
}

Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.

Pandas DataFrame column to list

The above solution is good if all the data is of same dtype. Numpy arrays are homogeneous containers. When you do df.values the output is an numpy array. So if the data has int and float in it then output will either have int or float and the columns will loose their original dtype. Consider df

a  b 
0  1  4
1  2  5 
2  3  6 

a    float64
b    int64 

So if you want to keep original dtype, you can do something like

row_list = df.to_csv(None, header=False, index=False).split('\n')

this will return each row as a string.

['1.0,4', '2.0,5', '3.0,6', '']

Then split each row to get list of list. Each element after splitting is a unicode. We need to convert it required datatype.

def f(row_str): 
  row_list = row_str.split(',')
  return [float(row_list[0]), int(row_list[1])]

df_list_of_list = map(f, row_list[:-1])

[[1.0, 4], [2.0, 5], [3.0, 6]]

How can I grep for a string that begins with a dash/hyphen?

grep -- -X
grep \\-X
grep '\-X'
grep "\-X"
grep -e -X
grep [-]X

How to set a JavaScript breakpoint from code in Chrome?

On the "Scripts" tab, go to where your code is. At the left of the line number, click. This will set a breakpoint.

Screenshot:

screenshot of breakpoint in chrome

You will then be able to track your breakpoints within the right tab (as shown in the screenshot).

How can I convert a string to upper- or lower-case with XSLT?

upper-case(string) and lower-case(string)

Reset git proxy to default configuration

On my Linux machine :

git config --system --get https.proxy (returns nothing)
git config --global --get https.proxy (returns nothing)

git config --system --get http.proxy (returns nothing)
git config --global --get http.proxy (returns nothing)

I found out my https_proxy and http_proxy are set, so I just unset them.

unset https_proxy
unset http_proxy

On my Windows machine :

set https_proxy=""
set http_proxy=""

Optionally use setx to set environment variables permanently on Windows and set system environment using "/m"

setx https_proxy=""
setx http_proxy=""

IE8 css selector

I have a solution that I use only when I have to, after I build my html & css valid and working in most browsers, I do the occasional hack with this amazing piece of javascript from Rafael Lima. http://rafael.adm.br/css_browser_selector/

It keeps my CSS & HTML valid and clean, I know it's not the ideal solution, using javascript to fix hacks, but as long as your code is originally as close as possible (silly IE just breaks things sometimes) then moving something a few px with javascript isn't as big of a deal as some people think. Plus for time/cost reasons is a quick & easy fix.

Error 500: Premature end of script headers

After many diff's, this was what was missing from the httpd.conf file on the server in question:

AddHandler php5-script .php

Solved the issue.

AWS ssh access 'Permission denied (publickey)' issue

You need have your private key in your local machine

You need to know the IP address or DNS name of your remote machine or server, you can get this from AWS console

If you are a linux user

  • Make sure the permissions on the private key are 600 (chmod 600 <path to private key file>)
  • Connect to your machine using ssh (ssh -i <path to private key file> <user>@<IP address or DNS name of remote server>)

If you are a windows user

Get total size of file in bytes

You can use the length() method on File which returns the size in bytes.

How to update values using pymongo?

Something I did recently, hope it helps. I have a list of dictionaries and wanted to add a value to some existing documents.

for item in my_list:
    my_collection.update({"_id" : item[key] }, {"$set" : {"New_col_name" :item[value]}})

No provider for Router?

I had the error of

No provider for Router

It happens when you try to navigate in any service.ts

this.router.navigate(['/home']); like codes in services cause that error.

You should handle navigating in your components. for example: at login.component

login().subscribe(
        (res) => this.router.navigate(['/home']),
        (error: any) => this.handleError(error));

Annoying errors happens when we are newbie :)

How to use pagination on HTML tables?

With Reference to Anusree answer above and with respect,I am tweeking the code little bit to make sure it works in most of the cases.

  1. Created a reusable function paginate('#myTableId') which can be called any number times for any table.
  2. Adding code inside ajaxComplete function to make sure paging is called once table using jquery is completely loaded. We use paging mostly for ajax based tables.
  3. Remove Pagination div and rebind on every pagination call
  4. Configuring Number of rows per page

Code:

$(document).ready(function () {
    $(document).ajaxComplete(function () {
        paginate('#myTableId',10);
        function paginate(tableName,RecordsPerPage) {
            $('#nav').remove();
            $(tableName).after('<div id="nav"></div>');
            var rowsShown = RecordsPerPage;
            var rowsTotal = $(tableName + ' tbody tr').length;
            var numPages = rowsTotal / rowsShown;
            for (i = 0; i < numPages; i++) {
                var pageNum = i + 1;
                $('#nav').append('<a href="#" rel="' + i + '">' + pageNum + '</a> ');
            }
            $(tableName + ' tbody tr').hide();
            $(tableName + ' tbody tr').slice(0, rowsShown).show();
            $('#nav a:first').addClass('active');
            $('#nav a').bind('click', function () {

                $('#nav a').removeClass('active');
                $(this).addClass('active');
                var currPage = $(this).attr('rel');
                var startItem = currPage * rowsShown;
                var endItem = startItem + rowsShown;
                $(tableName + ' tbody tr').css('opacity', '0.0').hide().slice(startItem, endItem).
                    css('display', 'table-row').animate({ opacity: 1 }, 300);
            });
        }
    });
});

Xcode Error: "The app ID cannot be registered to your development team."

Go to Build Settings tab, and then change the Product Bundle Identifier to another name. It works in mine.

Check date with todays date

another way to do this operation:

public class TimeUtils {

    /**
     * @param timestamp
     * @return
     */
    public static boolean isToday(long timestamp) {
        Calendar now = Calendar.getInstance();
        Calendar timeToCheck = Calendar.getInstance();
        timeToCheck.setTimeInMillis(timestamp);
        return (now.get(Calendar.YEAR) == timeToCheck.get(Calendar.YEAR)
                && now.get(Calendar.DAY_OF_YEAR) == timeToCheck.get(Calendar.DAY_OF_YEAR));
    }

}

Check element CSS display with JavaScript

yes.

var displayValue = document.getElementById('yourid').style.display;

Import data into Google Colaboratory

in google colabs if this is your first time,

from google.colab import drive
drive.mount('/content/drive')

run these codes and go through the outputlink then past the pass-prase to the box

when you copy you can copy as follows, go to file right click and copy the path ***don't forget to remove " /content "

f = open("drive/My Drive/RES/dimeric_force_field/Test/python_read/cropped.pdb", "r")

How to convert milliseconds into a readable date?

I just tested this and it works fine

var d = new Date(1441121836000);

The data object has a constructor which takes milliseconds as an argument.

Float to String format specifier

You can pass a format string to the ToString method, like so:

ToString("N4"); // 4 decimal points Number

If you want to see more modifiers, take a look at MSDN - Standard Numeric Format Strings

ImportError: No module named Crypto.Cipher

I've had the same problem 'ImportError: No module named Crypto.Cipher', since using GoogleAppEngineLauncher (version > 1.8.X) with GAE Boilerplate on OSX 10.8.5 (Mountain Lion). In Google App Engine SDK with python 2.7 runtime, pyCrypto 2.6 is the suggested version. The solution that worked for me was...

1) Download pycrypto2.6 source extract it somewhere(~/Downloads/pycrypto26)

e.g., git clone https://github.com/dlitz/pycrypto.git

2) cd (cd ~/Downloads/pycrypto26) then

3) Execute the following terminal command inside the previous folder in order to install pyCrypto 2.6 manually in GAE folder.

sudo python setup.py install --install-lib /Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine

How can I right-align text in a DataGridView column?

DataGridViewColumn column0 = dataGridViewGroup.Columns[0];
DataGridViewColumn column1 = dataGridViewGroup.Columns[1];
column1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
column1.Width = 120;

When do I use the PHP constant "PHP_EOL"?

PHP_EOL (string) The correct 'End Of Line' symbol for this platform. Available since PHP 4.3.10 and PHP 5.0.2

You can use this constant when you read or write text files on the server's filesystem.

Line endings do not matter in most cases as most software are capable of handling text files regardless of their origin. You ought to be consistent with your code.

If line endings matter, explicitly specify the line endings instead of using the constant. For example:

  • HTTP headers must be separated by \r\n
  • CSV files should use \r\n as row separator

Can the jQuery UI Datepicker be made to disable Saturdays and Sundays (and holidays)?

You can use noWeekends function to disable the weekend selection

  $(function() {
     $( "#datepicker" ).datepicker({
     beforeShowDay: $.datepicker.noWeekends
     });
     });

How to loop through Excel files and load them into a database using SSIS package?

Here is one possible way of doing this based on the assumption that there will not be any blank sheets in the Excel files and also all the sheets follow the exact same structure. Also, under the assumption that the file extension is only .xlsx

Following example was created using SSIS 2008 R2 and Excel 2007. The working folder for this example is F:\Temp\

In the folder path F:\Temp\, create an Excel 2007 spreadsheet file named States_1.xlsx with two worksheets.

Sheet 1 of States_1.xlsx contained the following data

States_1_Sheet_1

Sheet 2 of States_1.xlsx contained the following data

States_1_Sheet_2

In the folder path F:\Temp\, create another Excel 2007 spreadsheet file named States_2.xlsx with two worksheets.

Sheet 1 of States_2.xlsx contained the following data

States_2_Sheet_1

Sheet 2 of States_2.xlsx contained the following data

States_2_Sheet_2

Create a table in SQL Server named dbo.Destination using the below create script. Excel sheet data will be inserted into this table.

CREATE TABLE [dbo].[Destination](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [State] [nvarchar](255) NULL,
    [Country] [nvarchar](255) NULL,
    [FilePath] [nvarchar](255) NULL,
    [SheetName] [nvarchar](255) NULL,
CONSTRAINT [PK_Destination] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]
GO

The table is currently empty.

Empty table

Create a new SSIS package and on the package, create the following 4 variables. FolderPath will contain the folder where the Excel files are stored. FilePattern will contain the extension of the files that will be looped through and this example works only for .xlsx. FilePath will be assigned with a value by the Foreach Loop container but we need a valid path to begin with for design time and it is currently populated with the path F:\Temp\States_1.xlsx of the first Excel file. SheetName will contain the actual sheet name but we need to populate with initial value Sheet1$ to avoid design time error.

Variables

In the package's connection manager, create an ADO.NET connection with the following configuration and name it as ExcelSchema.

Select the provider Microsoft Office 12.0 Access Database Engine OLE DB Provider under .Net Providers for OleDb. Provide the file path F:\Temp\States_1.xlsx

ExcelSchema 1

Click on the All section on the left side and set the property Extended Properties to Excel 12.0 to denote the version of Excel. Here in this case 12.0 denotes Excel 2007. Click on the Test Connection to make sure that the connection succeeds.

ExcelSchema 2

Create an Excel connection manager named Excel as shown below.

Excel

Create an OLE DB Connection SQL Server named SQLServer. So, we should have three connections on the package as shown below.

Connections

We need to do the following connection string changes so that the Excel file is dynamically changed as the files are looped through.

On the connection ExcelSchema, configure the expression ServerName to use the variable FilePath. Click on the ellipsis button to configure the expression.

ExcelSchema ServerName

Similarly on the connection Excel, configure the expression ServerName to use the variable FilePath. Click on the ellipsis button to configure the expression.

Excel ServerName

On the Control Flow, place two Foreach Loop containers one within the other. The first Foreach Loop container named Loop files will loop through the files. The second Foreach Loop container will through the sheets within the container. Within the inner For each loop container, place a Data Flow Task that will read the Excel files and load data into SQL

Control Flow

Configure the first Foreach loop container named Loop files as shown below:

Foreach Loop 1 Collection

Foreach Loop 1 Variable Mappings

Configure the first Foreach loop container named Loop sheets as shown below:

Foreach Loop 2 Collection

Foreach Loop 2 Variable Mappings

Inside the data flow task, place an Excel Source, Derived Column and OLE DB Destination as shown below:

Data Flow Task

Configure the Excel Source to read the appropriate Excel file and the sheet that is currently being looped through.

Excel Source Connection Manager

Excel Source Columns

Configure the derived column to create new columns for file name and sheet name. This is just to demonstrate this example but has no significance.

Derived column

Configure the OLE DB destination to insert the data into the SQL table.

OLE DB Destination Connection Manager

OLE DB Destination Columns

Below screenshot shows successful execution of the package.

Execution successful

Below screenshot shows that data from the 4 workbooks in 2 Excel spreadsheets that were creating in the beginning of this answer is correctly loaded into the SQL table dbo.Destination.

SQL table

Hope that helps.

Enterprise app deployment doesn't work on iOS 7.1

Apter tried to change itms-services://?action=download-manifest&url=http://.... to itms-services://?action=download-manifest&url=https://..... It also cannot worked. The alert is cannot connect to my domain. I find out that also need update the webpage too.

The issue isn’t with the main URL being HTTPS but some of the HTML code in a link within the page. You’ll need your developers to update the webpage. I also noticed there isn’t a valid SSL certificate on your staging domain so you’ll need to get one installed or use Dropbox and here is the link maybe helpful for you

How to resolve 'unrecognized selector sent to instance'?

Very weird, but. You have to declare the class for your application instance as myApplication: UIApplication instead of myApplication: NSObject . It seems that the UIApplicationDelegate protocol doesn't implement the +registerForSystemEvents message. Crazy Apple APIs, again.

Android view layout_width - how to change programmatically?

try using

View view_instance = (View)findViewById(R.id.nutrition_bar_filled);
view_instance.setWidth(10);

use Layoutparams to do so where you can set width and height like below.

LayoutParams lp = new LayoutParams(10,LayoutParams.wrap_content);
View_instance.setLayoutParams(lp);

Using AES encryption in C#

I've recently had to bump up against this again in my own project - and wanted to share the somewhat simpler code that I've been using, as this question and series of answers kept coming up in my searches.

I'm not going to get into the security concerns around how often to update things like your Salt and Initialization Vector - that's a topic for a security forum, and there are some great resources out there to look at. This is simply a block of code to implement AesManaged in C#.

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace Your.Namespace.Security {
    public static class Cryptography {
        #region Settings

        private static int _iterations = 2;
        private static int _keySize = 256;

        private static string _hash     = "SHA1";
        private static string _salt     = "aselrias38490a32"; // Random
        private static string _vector   = "8947az34awl34kjq"; // Random

        #endregion

        public static string Encrypt(string value, string password) {
            return Encrypt<AesManaged>(value, password);
        }
        public static string Encrypt<T>(string value, string password) 
                where T : SymmetricAlgorithm, new() {
            byte[] vectorBytes = GetBytes<ASCIIEncoding>(_vector);
            byte[] saltBytes = GetBytes<ASCIIEncoding>(_salt);
            byte[] valueBytes = GetBytes<UTF8Encoding>(value);

            byte[] encrypted;
            using (T cipher = new T()) {
                PasswordDeriveBytes _passwordBytes = 
                    new PasswordDeriveBytes(password, saltBytes, _hash, _iterations);
                byte[] keyBytes = _passwordBytes.GetBytes(_keySize / 8);

                cipher.Mode = CipherMode.CBC;

                using (ICryptoTransform encryptor = cipher.CreateEncryptor(keyBytes, vectorBytes)) {
                    using (MemoryStream to = new MemoryStream()) {
                        using (CryptoStream writer = new CryptoStream(to, encryptor, CryptoStreamMode.Write)) {
                            writer.Write(valueBytes, 0, valueBytes.Length);
                            writer.FlushFinalBlock();
                            encrypted = to.ToArray();
                        }
                    }
                }
                cipher.Clear();
            }
            return Convert.ToBase64String(encrypted);
        }

        public static string Decrypt(string value, string password) {
            return Decrypt<AesManaged>(value, password);
        }
        public static string Decrypt<T>(string value, string password) where T : SymmetricAlgorithm, new() {
            byte[] vectorBytes = GetBytes<ASCIIEncoding>(_vector);
            byte[] saltBytes = GetBytes<ASCIIEncoding>(_salt);
            byte[] valueBytes = Convert.FromBase64String(value);

            byte[] decrypted;
            int decryptedByteCount = 0;

            using (T cipher = new T()) {
                PasswordDeriveBytes _passwordBytes = new PasswordDeriveBytes(password, saltBytes, _hash, _iterations);
                byte[] keyBytes = _passwordBytes.GetBytes(_keySize / 8);

                cipher.Mode = CipherMode.CBC;

                try {
                    using (ICryptoTransform decryptor = cipher.CreateDecryptor(keyBytes, vectorBytes)) {
                        using (MemoryStream from = new MemoryStream(valueBytes)) {
                            using (CryptoStream reader = new CryptoStream(from, decryptor, CryptoStreamMode.Read)) {
                                decrypted = new byte[valueBytes.Length];
                                decryptedByteCount = reader.Read(decrypted, 0, decrypted.Length);
                            }
                        }
                    }
                } catch (Exception ex) {
                    return String.Empty;
                }

                cipher.Clear();
            }
            return Encoding.UTF8.GetString(decrypted, 0, decryptedByteCount);
        }

    }
}

The code is very simple to use. It literally just requires the following:

string encrypted = Cryptography.Encrypt(data, "testpass");
string decrypted = Cryptography.Decrypt(encrypted, "testpass");

By default, the implementation uses AesManaged - but you could actually also insert any other SymmetricAlgorithm. A list of the available SymmetricAlgorithm inheritors for .NET 4.5 can be found at:

http://msdn.microsoft.com/en-us/library/system.security.cryptography.symmetricalgorithm.aspx

As of the time of this post, the current list includes:

  • AesManaged
  • RijndaelManaged
  • DESCryptoServiceProvider
  • RC2CryptoServiceProvider
  • TripleDESCryptoServiceProvider

To use RijndaelManaged with the code above, as an example, you would use:

string encrypted = Cryptography.Encrypt<RijndaelManaged>(dataToEncrypt, password);
string decrypted = Cryptography.Decrypt<RijndaelManaged>(encrypted, password);

I hope this is helpful to someone out there.

How to auto-remove trailing whitespace in Eclipse?

I would say AnyEdit too. It does not provide this specific functionalities. However, if you and your team use the AnyEdit features at each save actions, then when you open a file, it must not have any trailing whitespace.

So, if you modify this file, and if you add new trailing spaces, then during the save operation, AnyEdit will remove only these new spaces, as they are the only trailing spaces in this file.

If, for some reasons, you need to keep the trailing spaces on the lines that were not modified by you, then I have no answer for you, and I am not sure this kind of feature exists in any Eclipse plugin...

Add item to array in VBScript

this some kind of late but anyway and it is also somewhat tricky

 dim arrr 
  arr= array ("Apples", "Oranges", "Bananas")
 dim temp_var 
 temp_var = join (arr , "||") ' some character which will not occur is regular strings 
 if len(temp_var) > 0 then 
  temp_var = temp_var&"||Watermelons" 
end if 
arr  = split(temp_var , "||") ' here you got new elemet in array ' 
for each x in arr
response.write(x & "<br />")
next' 

review and tell me if this can work or initially you save all data in string and later split for array

How to asynchronously call a method in Java

This is not really related but if I was to asynchronously call a method e.g. matches(), I would use:

private final static ExecutorService service = Executors.newFixedThreadPool(10);
public static Future<Boolean> matches(final String x, final String y) {
    return service.submit(new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            return x.matches(y);
        }

    });
}

Then to call the asynchronous method I would use:

String x = "somethingelse";
try {
    System.out.println("Matches: "+matches(x, "something").get());
} catch (InterruptedException e) {
    e.printStackTrace();
} catch (ExecutionException e) {
    e.printStackTrace();
}

I have tested this and it works. Just thought it may help others if they just came for the "asynchronous method".

How can I write a byte array to a file in Java?

To write a byte array to a file use the method

public void write(byte[] b) throws IOException

from BufferedOutputStream class.

java.io.BufferedOutputStream implements a buffered output stream. By setting up such an output stream, an application can write bytes to the underlying output stream without necessarily causing a call to the underlying system for each byte written.

For your example you need something like:

String filename= "C:/SO/SOBufferedOutputStreamAnswer";
BufferedOutputStream bos = null;
try {
//create an object of FileOutputStream
FileOutputStream fos = new FileOutputStream(new File(filename));

//create an object of BufferedOutputStream
bos = new BufferedOutputStream(fos);

KeyGenerator kgen = KeyGenerator.getInstance("AES"); 
kgen.init(128); 
SecretKey key = kgen.generateKey(); 
byte[] encoded = key.getEncoded();

bos.write(encoded);

} 
// catch and handle exceptions...

In Chrome 55, prevent showing Download button for HTML 5 video

This is the solution (from this post)

video::-internal-media-controls-download-button {
    display:none;
}

video::-webkit-media-controls-enclosure {
    overflow:hidden;
}

video::-webkit-media-controls-panel {
    width: calc(100% + 30px); /* Adjust as needed */
}

Update 2 : New Solution by @Remo

<video width="512" height="380" controls controlsList="nodownload">
    <source data-src="mov_bbb.ogg" type="video/mp4">
</video>

Function that creates a timestamp in c#

when you need in a timestamp in seconds, you can use the following:

var timestamp = (int)(DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalSeconds;

Python POST binary data

You can use unirest, It provides easy method to post request. `

import unirest
 
def callback(response):
 print "code:"+ str(response.code)
 print "******************"
 print "headers:"+ str(response.headers)
 print "******************"
 print "body:"+ str(response.body)
 print "******************"
 print "raw_body:"+ str(response.raw_body)
 
# consume async post request
def consumePOSTRequestASync():
 params = {'test1':'param1','test2':'param2'}
 
 # we need to pass a dummy variable which is open method
 # actually unirest does not provide variable to shift between
 # application-x-www-form-urlencoded and
 # multipart/form-data
  
 params['dummy'] = open('dummy.txt', 'r')
 url = 'http://httpbin.org/post'
 headers = {"Accept": "application/json"}
 # call get service with headers and params
 unirest.post(url, headers = headers,params = params, callback = callback)
 
 
# post async request multipart/form-data
consumePOSTRequestASync()

Loop through a comma-separated shell variable

#/bin/bash   
TESTSTR="abc,def,ghij"

for i in $(echo $TESTSTR | tr ',' '\n')
do
echo $i
done

I prefer to use tr instead of sed, becouse sed have problems with special chars like \r \n in some cases.

other solution is to set IFS to certain separator

Running a Python script from PHP

Inspired by Alejandro Quiroz:

<?php 

$command = escapeshellcmd('python test.py');
$output = shell_exec($command);
echo $output;

?>

Need to add Python, and don't need the path.

How to set conditional breakpoints in Visual Studio?

Create a conditional function breakpoint:

  1. In the Breakpoints window, click New to create a new breakpoint.

  2. On the Function tab, type Reverse for Function. Type 1 for Line, type 1 for Character, and then set Language to Basic.

  3. Click Condition and make sure that the Condition checkbox is selected. Type instr.length > 0 for Condition, make sure that the is true option is selected, and then click OK.

  4. In the New Breakpoint dialog box, click OK.

  5. On the Debug menu, click Start.

How do I select last 5 rows in a table without sorting?

  1. You need to count number of rows inside table ( say we have 12 rows )
  2. then subtract 5 rows from them ( we are now in 7 )
  3. select * where index_column > 7

    select * from users
    where user_id > 
    ( (select COUNT(*) from users) - 5)
    

    you can order them ASC or DESC

    But when using this code

    select TOP 5 from users order by user_id DESC
    

    it will not be ordered easily.

How can I read comma separated values from a text file in Java?

Use BigDecimal, not double

The Answer by adatapost is right about using String::split but wrong about using double to represent your longitude-latitude values. The float/Float and double/Double types use floating-point technology which trades away accuracy for speed of execution.

Instead use BigDecimal to correctly represent your lat-long values.

Use Apache Commons CSV library

Also, best to let a library such as Apache Commons CSV perform the chore of reading and writing CSV or Tab-delimited files.

Example app

Here is a complete example app using that Commons CSV library. This app writes then reads a data file. It uses String::split for the writing. And the app uses BigDecimal objects to represent your lat-long values.

package work.basil.example;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;

import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

public class LatLong
{
    //----------|  Write  |-----------------------------
    public void write ( final Path path )
    {
        List < String > inputs =
                List.of(
                        "28.515046280572285,77.38258838653564" ,
                        "28.51430151808072,77.38336086273193" ,
                        "28.513566177802456,77.38413333892822" ,
                        "28.512830832397192,77.38490581512451" ,
                        "28.51208605426073,77.3856782913208" ,
                        "28.511341270865113,77.38645076751709" );

        // Use try-with-resources syntax to auto-close the `CSVPrinter`.
        try ( final CSVPrinter printer = CSVFormat.RFC4180.withHeader( "latitude" , "longitude" ).print( path , StandardCharsets.UTF_8 ) ; )
        {
            for ( String input : inputs )
            {
                String[] fields = input.split( "," );
                printer.printRecord( fields[ 0 ] , fields[ 1 ] );
            }
        } catch ( IOException e )
        {
            e.printStackTrace();
        }
    }

    //----------|  Read  |-----------------------------
    public void read ( Path path )
    {
        // TODO: Add a check for valid file existing.

        try
        {
            // Read CSV file.
            BufferedReader reader = Files.newBufferedReader( path );
            Iterable < CSVRecord > records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse( reader );
            for ( CSVRecord record : records )
            {
                BigDecimal latitude = new BigDecimal( record.get( "latitude" ) );
                BigDecimal longitude = new BigDecimal( record.get( "longitude" ) );
                System.out.println( "lat: " + latitude + " | long: " + longitude );
            }
        } catch ( IOException e )
        {
            e.printStackTrace();
        }
    }

    //----------|  Main  |-----------------------------
    public static void main ( String[] args )
    {
        LatLong app = new LatLong();

        // Write
        Path pathOutput = Paths.get( "/Users/basilbourque/lat-long.csv" );
        app.write( pathOutput );
        System.out.println( "Writing file: " + pathOutput );

        // Read
        Path pathInput = Paths.get( "/Users/basilbourque/lat-long.csv" );
        app.read( pathInput );

        System.out.println( "Done writing & reading lat-long data file. " + Instant.now() );
    }

}

Failed to execute 'createObjectURL' on 'URL':

I fixed it downloading the latest version from GgitHub GitHub url

Script to Change Row Color when a cell changes text

I think simpler (though without a script) assuming the Status column is ColumnS.

Select ColumnS and clear formatting from it. Select entire range to be formatted and Format, Conditional formatting..., Format cells if... Custom formula is and:

=and($S1<>"",search("Complete",$S1)>0)

with fill of choice and Done.

This is not case sensitive (change search to find for that) and will highlight a row where ColumnS contains the likes of Now complete (though also Not yet complete).

Angular 2 two way binding using ngModel is not working

For newer versions of Angular:

  1. -write it as [(ngModel)] = yourSearch

  2. declare a empty variable(property) named as yourSearch in .ts file

  3. add FormsModule in app.module.ts file from - @angular/forms;

  4. if your application is running, then restart it as you made changes in its module.ts file

How do I convert a javascript object array to a string array of the object attribute I want?

If your array of objects is items, you can do:

_x000D_
_x000D_
var items = [{_x000D_
  id: 1,_x000D_
  name: 'john'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'jane'_x000D_
}, {_x000D_
  id: 2000,_x000D_
  name: 'zack'_x000D_
}];_x000D_
_x000D_
var names = items.map(function(item) {_x000D_
  return item['name'];_x000D_
});_x000D_
_x000D_
console.log(names);_x000D_
console.log(items);
_x000D_
_x000D_
_x000D_

Documentation: map()

How to increase the max connections in postgres?

Just increasing max_connections is bad idea. You need to increase shared_buffers and kernel.shmmax as well.


Considerations

max_connections determines the maximum number of concurrent connections to the database server. The default is typically 100 connections.

Before increasing your connection count you might need to scale up your deployment. But before that, you should consider whether you really need an increased connection limit.

Each PostgreSQL connection consumes RAM for managing the connection or the client using it. The more connections you have, the more RAM you will be using that could instead be used to run the database.

A well-written app typically doesn't need a large number of connections. If you have an app that does need a large number of connections then consider using a tool such as pg_bouncer which can pool connections for you. As each connection consumes RAM, you should be looking to minimize their use.


How to increase max connections

1. Increase max_connection and shared_buffers

in /var/lib/pgsql/{version_number}/data/postgresql.conf

change

max_connections = 100
shared_buffers = 24MB

to

max_connections = 300
shared_buffers = 80MB

The shared_buffers configuration parameter determines how much memory is dedicated to PostgreSQL to use for caching data.

  • If you have a system with 1GB or more of RAM, a reasonable starting value for shared_buffers is 1/4 of the memory in your system.
  • it's unlikely you'll find using more than 40% of RAM to work better than a smaller amount (like 25%)
  • Be aware that if your system or PostgreSQL build is 32-bit, it might not be practical to set shared_buffers above 2 ~ 2.5GB.
  • Note that on Windows, large values for shared_buffers aren't as effective, and you may find better results keeping it relatively low and using the OS cache more instead. On Windows the useful range is 64MB to 512MB.

2. Change kernel.shmmax

You would need to increase kernel max segment size to be slightly larger than the shared_buffers.

In file /etc/sysctl.conf set the parameter as shown below. It will take effect when postgresql reboots (The following line makes the kernel max to 96Mb)

kernel.shmmax=100663296

References

Postgres Max Connections And Shared Buffers

Tuning Your PostgreSQL Server

Update row values where certain condition is met in pandas

I think you can use loc if you need update two columns to same value:

df1.loc[df1['stream'] == 2, ['feat','another_feat']] = 'aaaa'
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2        aaaa         aaaa
c       2        aaaa         aaaa
d       3  some_value   some_value

If you need update separate, one option is use:

df1.loc[df1['stream'] == 2, 'feat'] = 10
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2          10   some_value
c       2          10   some_value
d       3  some_value   some_value

Another common option is use numpy.where:

df1['feat'] = np.where(df1['stream'] == 2, 10,20)
print df1
   stream  feat another_feat
a       1    20   some_value
b       2    10   some_value
c       2    10   some_value
d       3    20   some_value

EDIT: If you need divide all columns without stream where condition is True, use:

print df1
   stream  feat  another_feat
a       1     4             5
b       2     4             5
c       2     2             9
d       3     1             7

#filter columns all without stream
cols = [col for col in df1.columns if col != 'stream']
print cols
['feat', 'another_feat']

df1.loc[df1['stream'] == 2, cols ] = df1 / 2
print df1
   stream  feat  another_feat
a       1   4.0           5.0
b       2   2.0           2.5
c       2   1.0           4.5
d       3   1.0           7.0

If working with multiple conditions is possible use multiple numpy.where or numpy.select:

df0 = pd.DataFrame({'Col':[5,0,-6]})

df0['New Col1'] = np.where((df0['Col'] > 0), 'Increasing', 
                          np.where((df0['Col'] < 0), 'Decreasing', 'No Change'))

df0['New Col2'] = np.select([df0['Col'] > 0, df0['Col'] < 0],
                            ['Increasing',  'Decreasing'], 
                            default='No Change')

print (df0)
   Col    New Col1    New Col2
0    5  Increasing  Increasing
1    0   No Change   No Change
2   -6  Decreasing  Decreasing

How do I fix the npm UNMET PEER DEPENDENCY warning?

npm-install-peers worked for me.

npm install -g npm-install-peers

Format numbers to strings in Python

I've tried this in Python 3.6.9

>>> hours, minutes, seconds = 9, 33, 35
>>> time = f'{hours:02}:{minutes:02}:{seconds:02} {"pm" if hours > 12 else "am"}'
>>> print (time)
09:33:35 am
>>> type(time)

<class 'str'>

Play audio from a stream using C#

I've tweaked the source posted in the question to allow usage with Google's TTS API in order to answer the question here:

bool waiting = false;
AutoResetEvent stop = new AutoResetEvent(false);
public void PlayMp3FromUrl(string url, int timeout)
{
    using (Stream ms = new MemoryStream())
    {
        using (Stream stream = WebRequest.Create(url)
            .GetResponse().GetResponseStream())
        {
            byte[] buffer = new byte[32768];
            int read;
            while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, read);
            }
        }
        ms.Position = 0;
        using (WaveStream blockAlignedStream =
            new BlockAlignReductionStream(
                WaveFormatConversionStream.CreatePcmStream(
                    new Mp3FileReader(ms))))
        {
            using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))
            {
                waveOut.Init(blockAlignedStream);
                waveOut.PlaybackStopped += (sender, e) =>
                {
                    waveOut.Stop();
                };
                waveOut.Play();
                waiting = true;
                stop.WaitOne(timeout);
                waiting = false;
            }
        }
    }
}

Invoke with:

var playThread = new Thread(timeout => PlayMp3FromUrl("http://translate.google.com/translate_tts?q=" + HttpUtility.UrlEncode(relatedLabel.Text), (int)timeout));
playThread.IsBackground = true;
playThread.Start(10000);

Terminate with:

if (waiting)
    stop.Set();

Notice that I'm using the ParameterizedThreadDelegate in the code above, and the thread is started with playThread.Start(10000);. The 10000 represents a maximum of 10 seconds of audio to be played so it will need to be tweaked if your stream takes longer than that to play. This is necessary because the current version of NAudio (v1.5.4.0) seems to have a problem determining when the stream is done playing. It may be fixed in a later version or perhaps there is a workaround that I didn't take the time to find.

Bootstrap 3 - set height of modal window according to screen size

I am using jquery for this. I mad a function to set desired height to the modal(You can change that according to your requirement). Then I used Modal Shown event to call this function. Remember not to use $("#modal").show() rather use $("#modal").modal('show') otherwise shown.bs.modal will not be fired.

That all I have for this scenario.

_x000D_
_x000D_
var offset=250; //You can set offset accordingly based on your UI_x000D_
function AdjustPopup() _x000D_
{_x000D_
    $(".modal-body").css("height","auto");_x000D_
    if ($(".modal-body:visible").height() > ($(window).height() - offset)) _x000D_
    {_x000D_
        $(".modal-body:visible").css("height", ($(window).height() - offset));_x000D_
    }_x000D_
}_x000D_
//Execute the function on every trigger on show() event._x000D_
$(document).ready(function(){_x000D_
$('.modal').on('shown.bs.modal', function (e) {_x000D_
        AdjustPopup();_x000D_
    });_x000D_
});_x000D_
//Remember to show modal like this_x000D_
$("#MyModal").modal('show');
_x000D_
_x000D_
_x000D_

How to set a text box for inputing password in winforms?

To set a text box for password input:

textBox1.PasswordChar = '*';

you can also change this property in design time by editing properties of the text box.

To show if "Capslock is ON":

using System;  
using System.Windows.Forms;  
//...
if (Control.IsKeyLocked(Keys.CapsLock)) {  
    MessageBox.Show("The Caps Lock key is ON.");  
}  

Accessing all items in the JToken

If you know the structure of the json that you're receiving then I'd suggest having a class structure that mirrors what you're receiving in json.

Then you can call its something like this...

AddressMap addressMap = JsonConvert.DeserializeObject<AddressMap>(json);

(Where json is a string containing the json in question)

If you don't know the format of the json you've receiving then it gets a bit more complicated and you'd probably need to manually parse it.

check out http://www.hanselman.com/blog/NuGetPackageOfTheWeek4DeserializingJSONWithJsonNET.aspx for more info

How to run test cases in a specified file?

alias testcases="sed -n 's/func.*\(Test.*\)(.*/\1/p' | xargs | sed 's/ /|/g'"

go test -v -run $(cat coordinator_test.go | testcases)

Android Studio Checkout Github Error "CreateProcess=2" (Windows)

I've solved the problem , and I will explain how :

  1. Download Github For Windows client and install it.
  2. After The client successfully installed , connect it with your github account.It should be easy , just follow the wizard.
  3. Then you should add git.exe location to your "Path Variable". The location you should add will probably be something like : C:\Users\Your_Username\AppData\Local\GitHub\PortableGit_ca477551eeb4aea0e4ae9fcd3358bd96720bb5c8\bin

Alternatively , if you don't want to add to environment variables. You can open the android studio and go to : Settings -> Version Control -> Git In text box next to "Path to Git Executable" you will see "git.exe" , just give it a full path like so : C:\Users\Your_Username\AppData\Local\GitHub\PortableGit_ca477551eeb4aea0e4ae9fcd3358bd96720bb5c8\bin\git.exe

Hope it saved your time . Happy coding :)

EDIT : For latest Github for windows versions some can find the git.exe under "...\cmd\git.exe" rather than "...\bin\git.exe".

Creating an R dataframe row-by-row

Dirk Eddelbuettel's answer is the best; here I just note that you can get away with not pre-specifying the dataframe dimensions or data types, which is sometimes useful if you have multiple data types and lots of columns:

row1<-list("a",1,FALSE) #use 'list', not 'c' or 'cbind'!
row2<-list("b",2,TRUE)  

df<-data.frame(row1,stringsAsFactors = F) #first row
df<-rbind(df,row2) #now this works as you'd expect.

SQL Plus change current directory

Could you use the SQLPATH environment variable to tell sqlplus where to look for the scripts you are trying to run? I believe you could use HOST to set SQLPATH in the script too.

There could potentially be problems if two scripts have the same name and both directories are in the SQLPATH.

Sending private messages to user

If your looking to type up the message and then your bot will send it to the user, here is the code. It also has a role restriction on it :)

_x000D_
_x000D_
case 'dm':
  mentiondm = message.mentions.users.first();
  message.channel.bulkDelete(1);
  if (!message.member.roles.cache.some(role => role.name === "Owner")) return message.channel.send('Beep Boing: This command is way too powerful for you to use!');
  if (mentiondm == null) return message.reply('Beep Boing: No user to send message to!');
  mentionMessage = message.content.slice(3);
  mentiondm.send(mentionMessage);
  console.log('Message Sent!')
  break;
_x000D_
_x000D_
_x000D_

How does one make random number between range for arc4random_uniform()?

hope this is working. make random number between range for arc4random_uniform()?

var randomNumber = Int(arc4random_uniform(6))
print(randomNumber)

How do I pass a URL with multiple parameters into a URL?

I see you're having issues with the social share links. I had a similar issue at some point and found this question, but I don't see a complete answer for it. I hope my javascript resolution from below will help:

I had default sharing links that needed to be modified so that the URL that's being shared will have additional UTM parameters concatenated.

My example will be for the Facebook social share link, but it works for all the possible social sharing network links:

The URL that needed to be shared was:

https://mywebsitesite.com/blog/post-name

The default sharing link looked like:

$facebook_default = "https://www.facebook.com/sharer.php?u=https%3A%2F%2mywebsitesite.com%2Fblog%2Fpost-name%2F&t=hello"

I first DECODED it:

console.log( decodeURIComponent($facebook_default) );
=>
https://www.facebook.com/sharer.php?u=https://mywebsitesite.com/blog/post-name/&t=hello

Then I replaced the URL with the encoded new URL (with the UTM parameters concatenated):

console.log( decodeURIComponent($facebook_default).replace( window.location.href, encodeURIComponent(window.location.href+'?utm_medium=social&utm_source=facebook')) );

=>

https://www.facebook.com/sharer.php?u=https%3A%2F%mywebsitesite.com%2Fblog%2Fpost-name%2F%3Futm_medium%3Dsocial%26utm_source%3Dfacebook&t=2018

That's it!

Complete solution:

$facebook_default = $('a.facebook_default_link').attr('href');

$('a.facebook_default_link').attr( 'href', decodeURIComponent($facebook_default).replace( window.location.href, encodeURIComponent(window.location.href+'?utm_medium=social&utm_source=facebook')) );

How to set 00:00:00 using moment.js

Moment.js stores dates it utc and can apply different timezones to it. By default it applies your local timezone. If you want to set time on utc date time you need to specify utc timezone.

Try the following code:

var m = moment().utcOffset(0);
m.set({hour:0,minute:0,second:0,millisecond:0})
m.toISOString()
m.format()

How to uncompress a tar.gz in another directory

You can use for loop to untar multiple .tar.gz files to another folder. The following code will take /destination/folder/path as an argument to the script and untar all .tar.gz files present at the current location in /destination/folder/path.

if [ $# -ne 1 ];
 then
 echo "invalid argument/s"
 echo "Usage: ./script-file-name.sh /target/directory"
 exit 0
fi
for file in *.tar.gz
do
    tar -zxvf "$file" --directory $1
done

Which is the best Linux C/C++ debugger (or front-end to gdb) to help teaching programming?

Qt Creator, apart from other goodies, also has a good debugger integration, for CDB, GDB and the Symnbian debugger, on all supported platforms. You don't need to use Qt to use the Qt Creator IDE, nor do you need to use QMake - it also has CMake integration, although QMake is very easy to use.

You may want to use Qt Creator as the IDE to teach programming with, consider it has some good features:

  • Very smart and advanced C++ editor
  • Project and build management tools
  • QMake and CMake integration
  • Integrated, context-sensitive help system
  • Excellent visual debugger (CDB, GDB and Symbian)
  • Supports GCC and VC++
  • Rapid code navigation tools
  • Supports Windows, Linux and Mac OS X

IF statement: how to leave cell blank if condition is false ("" does not work)

To Validate data in column A for Blanks

Step 1: Step 1: B1=isblank(A1)

Step 2: Drag the formula for the entire column say B1:B100; This returns Ture or False from B1 to B100 depending on the data in column A

Step 3: CTRL+A (Selct all), CTRL+C (Copy All) , CRTL+V (Paste all as values)

Step4: Ctrl+F ; Find and replace function Find "False", Replace "leave this blank field" ; Find and Replace ALL

There you go Dude!

What is the best/safest way to reinstall Homebrew?

For me, this one worked without the sudo access.

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

For more reference, please follow https://gist.github.com/mxcl/323731

enter image description here

How to get the input from the Tkinter Text Widget?

To get Tkinter input from the text box in python 3 the complete student level program used by me is as under:

#Imports all (*) classes,
#atributes, and methods of tkinter into the
#current workspace

from tkinter import *

#***********************************
#Creates an instance of the class tkinter.Tk.
#This creates what is called the "root" window. By conventon,
#the root window in Tkinter is usually called "root",
#but you are free to call it by any other name.

root = Tk()
root.title('how to get text from textbox')


#**********************************
mystring = StringVar()

####define the function that the signup button will do
def getvalue():
##    print(mystring.get())
#*************************************

Label(root, text="Text to get").grid(row=0, sticky=W)  #label
Entry(root, textvariable = mystring).grid(row=0, column=1, sticky=E) #entry textbox

WSignUp = Button(root, text="print text", command=getvalue).grid(row=3, column=0, sticky=W) #button


############################################
# executes the mainloop (that is, the event loop) method of the root
# object. The mainloop method is what keeps the root window visible.
# If you remove the line, the window created will disappear
# immediately as the script stops running. This will happen so fast
# that you will not even see the window appearing on your screen.
# Keeping the mainloop running also lets you keep the
# program running until you press the close buton
root.mainloop()

How to use breakpoints in Eclipse

Here is a video about Debugging with eclipse.

For more details read this page.

Instead of Debugging as Java program, use Debug as Android Application

May help new comers.

How can I compare strings in C using a `switch` statement?

I have published a header file to perform the switch on the strings in C. It contains a set of macro that hide the call to the strcmp() (or similar) in order to mimic a switch-like behaviour. I have tested it only with GCC in Linux, but I'm quite sure that it can be adapted to support other environment.

EDIT: added the code here, as requested

This is the header file you should include:

#ifndef __SWITCHS_H__
#define __SWITCHS_H__

#include <string.h>
#include <regex.h>
#include <stdbool.h>

/** Begin a switch for the string x */
#define switchs(x) \
    { char *__sw = (x); bool __done = false; bool __cont = false; \
        regex_t __regex; regcomp(&__regex, ".*", 0); do {

/** Check if the string matches the cases argument (case sensitive) */
#define cases(x)    } if ( __cont || !strcmp ( __sw, x ) ) \
                        { __done = true; __cont = true;

/** Check if the string matches the icases argument (case insensitive) */
#define icases(x)    } if ( __cont || !strcasecmp ( __sw, x ) ) { \
                        __done = true; __cont = true;

/** Check if the string matches the specified regular expression using regcomp(3) */
#define cases_re(x,flags) } regfree ( &__regex ); if ( __cont || ( \
                              0 == regcomp ( &__regex, x, flags ) && \
                              0 == regexec ( &__regex, __sw, 0, NULL, 0 ) ) ) { \
                                __done = true; __cont = true;

/** Default behaviour */
#define defaults    } if ( !__done || __cont ) {

/** Close the switchs */
#define switchs_end } while ( 0 ); regfree(&__regex); }

#endif // __SWITCHS_H__

And this is how you use it:

switchs(argv[1]) {
    cases("foo")
    cases("bar")
        printf("foo or bar (case sensitive)\n");
        break;

    icases("pi")
        printf("pi or Pi or pI or PI (case insensitive)\n");
        break;

    cases_re("^D.*",0)
        printf("Something that start with D (case sensitive)\n");
        break;

    cases_re("^E.*",REG_ICASE)
        printf("Something that start with E (case insensitive)\n");
        break;

    cases("1")
        printf("1\n");
        // break omitted on purpose

    cases("2")
        printf("2 (or 1)\n");
        break;

    defaults
        printf("No match\n");
        break;
} switchs_end;

removing new line character from incoming stream using sed

This might work for you:

printf "{new\nto\nlinux}" | paste -sd' '            
{new to linux}

or:

printf "{new\nto\nlinux}" | tr '\n' ' '            
{new to linux}

or:

printf "{new\nto\nlinux}" |sed -e ':a' -e '$!{' -e 'N' -e 'ba' -e '}' -e 's/\n/ /g'
{new to linux}

How do I set default terminal to terminator?

In xfce (e.g. on Arch Linux) you can change the parameter TerminalEmulator:

 TerminalEmulator=xfce4-terminal

to

TerminalEmulator=custom-TerminalEmulator

The next time you want to open a terminal window, xfce will ask you to choose an emulator. You can just pick /usr/bin/terminator.

System Defaults

/etc/xdg/xfce4/helpers.rc

User Defaults

/home/USER/.config/xfce4

android ellipsize multiline textview

Got this problem to, and finaly, I build myself a short solution. You just have to ellipsize manually the line you want, your maxLine attribute will cut your text.

This example cut your text for 3 lines max

        final TextView title = (TextView)findViewById(R.id.text);
        title.setText("A really long text");
        ViewTreeObserver vto = title.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                ViewTreeObserver obs = title.getViewTreeObserver();
                obs.removeGlobalOnLayoutListener(this);
                if(title.getLineCount() > 3){
                    Log.d("","Line["+title.getLineCount()+"]"+title.getText());
                    int lineEndIndex = title.getLayout().getLineEnd(2);
                    String text = title.getText().subSequence(0, lineEndIndex-3)+"...";
                    title.setText(text);
                    Log.d("","NewText:"+text);
                }

            }
        });

Android - Center TextView Horizontally in LinearLayout

If you set <TextView> in center in <Linearlayout> then first put android:layout_width="fill_parent" compulsory
No need of using any other gravity

    <LinearLayout
            android:layout_toRightOf="@+id/linear_profile" 
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:orientation="vertical"
            android:gravity="center_horizontal">
            <TextView 
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:text="It's.hhhhhhhh...."
                android:textColor="@color/Black"

                />
    </LinearLayout>

Disable beep of Linux Bash on Windows 10

@Andrea Tulimiero 's answer works for local, but when you ssh to a remote server, the beep turns on again. My suggestion is to disable from the Windows 10 taskbar. There is volume mixer in the right bottom corner, which works for me.

how to overlap two div in css?

See demo here you need to introduce an additiona calss for second div

.overlap{
    top: -30px;
position: relative;
left: 30px;
}

What does a (+) sign mean in an Oracle SQL WHERE clause?

This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.

In standard SQL one would write:

SELECT t0.foo, t1.bar
  FROM FIRST_TABLE t0
 RIGHT OUTER JOIN SECOND_TABLE t1;

Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :

Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]

Convert a negative number to a positive one in JavaScript

unsigned_value = Math.abs(signed_value);

How can I search sub-folders using glob.glob module?

In Python 3.5 and newer use the new recursive **/ functionality:

configfiles = glob.glob('C:/Users/sam/Desktop/file1/**/*.txt', recursive=True)

When recursive is set, ** followed by a path separator matches 0 or more subdirectories.

In earlier Python versions, glob.glob() cannot list files in subdirectories recursively.

In that case I'd use os.walk() combined with fnmatch.filter() instead:

import os
import fnmatch

path = 'C:/Users/sam/Desktop/file1'

configfiles = [os.path.join(dirpath, f)
    for dirpath, dirnames, files in os.walk(path)
    for f in fnmatch.filter(files, '*.txt')]

This'll walk your directories recursively and return all absolute pathnames to matching .txt files. In this specific case the fnmatch.filter() may be overkill, you could also use a .endswith() test:

import os

path = 'C:/Users/sam/Desktop/file1'

configfiles = [os.path.join(dirpath, f)
    for dirpath, dirnames, files in os.walk(path)
    for f in files if f.endswith('.txt')]

How to check if a .txt file is in ASCII or UTF-8 format in Windows environment?

Text files in Windows don't have a format. There's an unofficial convention that if the file starts with the BOM codepoint in UTF-8 format that it's UTF-8, but that convention isn't universally supported. That would be the 3 byte sequence "\xef\xbf\xbe", i.e. ￾ in the Latin-1 character set.

Understanding generators in Python

Generators could be thought of as shorthand for creating an iterator. They behave like a Java Iterator. Example:

>>> g = (x for x in range(10))
>>> g
<generator object <genexpr> at 0x7fac1c1e6aa0>
>>> g.next()
0
>>> g.next()
1
>>> g.next()
2
>>> list(g)   # force iterating the rest
[3, 4, 5, 6, 7, 8, 9]
>>> g.next()  # iterator is at the end; calling next again will throw
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

Hope this helps/is what you are looking for.

Update:

As many other answers are showing, there are different ways to create a generator. You can use the parentheses syntax as in my example above, or you can use yield. Another interesting feature is that generators can be "infinite" -- iterators that don't stop:

>>> def infinite_gen():
...     n = 0
...     while True:
...         yield n
...         n = n + 1
... 
>>> g = infinite_gen()
>>> g.next()
0
>>> g.next()
1
>>> g.next()
2
>>> g.next()
3
...

C++ int to byte array

An int (or any other data type for that matter) is already stored as bytes in memory. So why not just copy the memory directly?

memcpy(arrayOfByte, &x, sizeof x);

A simple elegant one liner that will also work with any other data type.



If you need the bytes reversed you can use std::reverse

memcpy(arrayOfByte, &x, sizeof x);
std::reverse(arrayOfByte, arrayOfByte + sizeof x);

or better yet, just copy the bytes in reverse to begin with

BYTE* p = (BYTE*) &x;
std::reverse_copy(p, p + sizeof x, arrayOfByte);

If you don't want to make a copy of the data at all, and just have its byte representation

BYTE* bytes = (BYTE*) &x;

Can I use Objective-C blocks as properties?

Hello, Swift

Complementing what @Francescu answered.

Adding extra parameters:

func test(function:String -> String, param1:String, param2:String) -> String
{
    return function("test"+param1 + param2)
}

func funcStyle(s:String) -> String
{
    return "FUNC__" + s + "__FUNC"
}
let resultFunc = test(funcStyle, "parameter 1", "parameter 2")

let blockStyle:(String) -> String = {s in return "BLOCK__" + s + "__BLOCK"}
let resultBlock = test(blockStyle, "parameter 1", "parameter 2")

let resultAnon = test({(s:String) -> String in return "ANON_" + s + "__ANON" }, "parameter 1", "parameter 2")


println(resultFunc)
println(resultBlock)
println(resultAnon)

Reading a date using DataReader

This may seem slightly off topic but this was the post I came across when wondering what happens when you read a column as a dateTime in c#. The post reflects the information I would have liked to be able to find about this mechanism. If you worry about utc and timezones then read on

I did a little more research as I'm always very wary of DateTime as a class because of its automatic assumptions about what timezone you are using and because it is way too easy to confuse local times and utc times.

What I'm trying to avoid here is DateTime going 'oh look the computer I'm being run on is in timezone x, therefore this time must also be in timezone x, when I get asked for my values I'll reply as if I'm in that timezone'

I was trying to read a datetime2 column.

The date time you will get back from sql server will end up being of Kind.Unspecified this seems to mean it gets treated like UTC, which is what I wanted.

When reading a date column you also have to read it as a DateTime even though it has no time and is even more prone to screwing up by timezones (as it is on midnight).

I'd certainly consider this to be safer way of reading the DateTime as I suspect it can probably be modified by either settings in sql server or static settings in your c#:

var time = reader.GetDateTime(1);
var utcTime = new DateTime(time.Ticks, DateTimeKind.Utc);

From there you can get the components (Day, Month, Year) etc and format how you like.

If what you have is actually a date + a time then Utc might not be what you want there - since you are mucking around on the client you may need to convert it to a local time first (depending on what the meaning of the time is). However that opens up a whole can of worms.. If you need to do that I'd recommend using a library like noda time. There is TimeZoneInfo in the standard library but after briefly investigating it, it doesn't seem to have a proper set of timezones. You can see the list provided by TimeZoneInfo by using the method TimeZoneInfo.GetSystemTimeZones();

I also discovered sql server management studio doesn't convert times to local time before displaying them. Which is a relief!

Generating random numbers in C

You need to seed your PRNG so it starts with a different value each time.

A simple but low quality seed is to use the current time:

srand(time(0));

This will get you started but is considered low quality (i.e. for example, don't use that if you are trying to generate RSA keys).

Background. Pseudo-random number generators do not create true random number sequences but just simulate them. Given a starting point number, a PRNG will always return the same sequence of numbers. By default, they start with the same internal state so will return the same sequence.

To not get the same sequence, you change the internal state. The act of changing the internal state is called "seeding".

How to delete columns in a CSV file?

You can directly delete the column with just

del variable_name['year']

How to map calculated properties with JPA and Hibernate

You have three options:

  • either you are calculating the attribute using a @Transient method
  • you can also use @PostLoad entity listener
  • or you can use the Hibernate specific @Formula annotation

While Hibernate allows you to use @Formula, with JPA, you can use the @PostLoad callback to populate a transient property with the result of some calculation:

@Column(name = "price")
private Double price;

@Column(name = "tax_percentage")
private Double taxes;

@Transient
private Double priceWithTaxes;

@PostLoad
private void onLoad() {
    this.priceWithTaxes = price * taxes;
}

So, you can use the Hibernate @Formula like this:

@Formula("""
    round(
       (interestRate::numeric / 100) *
       cents *
       date_part('month', age(now(), createdOn)
    )
    / 12)
    / 100::numeric
    """)
private double interestDollars;

How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?

One to one (1-1) relationship: This is relationship between primary & foreign key (primary key relating to foreign key only one record). this is one to one relationship.

One to Many (1-M) relationship: This is also relationship between primary & foreign keys relationships but here primary key relating to multiple records (i.e. Table A have book info and Table B have multiple publishers of one book).

Many to Many (M-M): Many to many includes two dimensions, explained fully as below with sample.

-- This table will hold our phone calls.
CREATE TABLE dbo.PhoneCalls
(
   ID INT IDENTITY(1, 1) NOT NULL,
   CallTime DATETIME NOT NULL DEFAULT GETDATE(),
   CallerPhoneNumber CHAR(10) NOT NULL
)
-- This table will hold our "tickets" (or cases).
CREATE TABLE dbo.Tickets
(
   ID INT IDENTITY(1, 1) NOT NULL,
   CreatedTime DATETIME NOT NULL DEFAULT GETDATE(),
   Subject VARCHAR(250) NOT NULL,
   Notes VARCHAR(8000) NOT NULL,
   Completed BIT NOT NULL DEFAULT 0
)
-- This table will link a phone call with a ticket.
CREATE TABLE dbo.PhoneCalls_Tickets
(
   PhoneCallID INT NOT NULL,
   TicketID INT NOT NULL
)

What's the maximum value for an int in PHP?

The size of PHP ints is platform dependent:

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.

PHP 6 adds "longs" (64 bit ints).

Application_Start not firing?

We had a similar problem, where global.asax.cs was being ignored.

It turns out that the site was upgraded from a precompiled .NET 2 web site to a .NET 4.0 site. On the server, the PrecompiledApp.config file had not been deleted from the root folder. After deleting it, and recycling the IIS app pool and touching web.config to restart the application, code in Global.asax.cs started working fine.

Java compile error: "reached end of file while parsing }"

You have to open and close your class with { ... } like:

public class mod_MyMod extends BaseMod
{
  public String Version()
  {
    return "1.2_02";
  }

  public void AddRecipes(CraftingManager recipes)
  {
     recipes.addRecipe(new ItemStack(Item.diamond), new Object[] {
        "#", Character.valueOf('#'), Block.dirt });
  }
}

bash: pip: command not found

To solve:

  1. Add this line to ~/.bash_profile

    export PATH="/usr/local/bin:$PATH"

  2. In a terminal window, run

    source ~/.bash_profile

Why isn't this code to plot a histogram on a continuous value Pandas column working?

Here's another way to plot the data, involves turning the date_time into an index, this might help you for future slicing

#convert column to datetime
trip_data['lpep_pickup_datetime'] = pd.to_datetime(trip_data['lpep_pickup_datetime'])
#turn the datetime to an index
trip_data.index = trip_data['lpep_pickup_datetime']
#Plot
trip_data['Trip_distance'].plot(kind='hist')
plt.show()

Command /Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 1

Do a clean. product > clean . Terminal purge & reboot didn't work for me, cleaning did.

How to compare files from two different branches?

There are many ways to compare files from two different branches:

  • Option 1: If you want to compare the file from n specific branch to another specific branch:

    git diff branch1name branch2name path/to/file
    

    Example:

    git diff mybranch/myfile.cs mysecondbranch/myfile.cs
    

    In this example you are comparing the file in “mybranch” branch to the file in the “mysecondbranch” branch.

  • Option 2: Simple way:

     git diff branch1:file branch2:file
    

    Example:

     git diff mybranch:myfile.cs mysecondbranch:myfile.cs
    

    This example is similar to the option 1.

  • Option 3: If you want to compare your current working directory to some branch:

    git diff ..someBranch path/to/file
    

    Example:

    git diff ..master myfile.cs
    

    In this example you are comparing the file from your actual branch to the file in the master branch.

Why do I have to run "composer dump-autoload" command to make migrations work in laravel?

Short answer: classmaps are static while PSR autoloading is dynamic.

If you don't want to use classmaps, use PSR autoloading instead.

How do I detect the Python version at runtime?

To make the scripts compatible with Python2 and 3 i use :

from sys import version_info
if version_info[0] < 3:
    from __future__ import print_function

seek() function?

Regarding seek() there's not too much to worry about.

First of all, it is useful when operating over an open file.

It's important to note that its syntax is as follows:

fp.seek(offset, from_what)

where fp is the file pointer you're working with; offset means how many positions you will move; from_what defines your point of reference:

  • 0: means your reference point is the beginning of the file
  • 1: means your reference point is the current file position
  • 2: means your reference point is the end of the file

if omitted, from_what defaults to 0.

Never forget that when managing files, there'll always be a position inside that file where you are currently working on. When just open, that position is the beginning of the file, but as you work with it, you may advance.
seek will be useful to you when you need to walk along that open file, just as a path you are traveling into.

Call PowerShell script PS1 from another PS1 script inside Powershell ISE

I had a problem with this. I didn't use any clever $MyInvocation stuff to fix it though. If you open the ISE by right clicking a script file and selecting edit then open the second script from within the ISE you can invoke one from the other by just using the normal .\script.ps1 syntax. My guess is that the ISE has the notion of a current folder and opening it like this sets the current folder to the folder containing the scripts. When I invoke one script from another in normal use I just use .\script.ps1, IMO it's wrong to modify the script just to make it work in the ISE properly...

How to delete a cookie?

To delete a cookie I set it again with an empty value and expiring in 1 second. In details, I always use one of the following flavours (I tend to prefer the second one):

1.

    function setCookie(key, value, expireDays, expireHours, expireMinutes, expireSeconds) {
        var expireDate = new Date();
        if (expireDays) {
            expireDate.setDate(expireDate.getDate() + expireDays);
        }
        if (expireHours) {
            expireDate.setHours(expireDate.getHours() + expireHours);
        }
        if (expireMinutes) {
            expireDate.setMinutes(expireDate.getMinutes() + expireMinutes);
        }
        if (expireSeconds) {
            expireDate.setSeconds(expireDate.getSeconds() + expireSeconds);
        }
        document.cookie = key +"="+ escape(value) +
            ";domain="+ window.location.hostname +
            ";path=/"+
            ";expires="+expireDate.toUTCString();
    }

    function deleteCookie(name) {
        setCookie(name, "", null , null , null, 1);
    }

Usage:

setCookie("reminder", "buyCoffee", null, null, 20);
deleteCookie("reminder");

2

    function setCookie(params) {
        var name            = params.name,
            value           = params.value,
            expireDays      = params.days,
            expireHours     = params.hours,
            expireMinutes   = params.minutes,
            expireSeconds   = params.seconds;

        var expireDate = new Date();
        if (expireDays) {
            expireDate.setDate(expireDate.getDate() + expireDays);
        }
        if (expireHours) {
            expireDate.setHours(expireDate.getHours() + expireHours);
        }
        if (expireMinutes) {
            expireDate.setMinutes(expireDate.getMinutes() + expireMinutes);
        }
        if (expireSeconds) {
            expireDate.setSeconds(expireDate.getSeconds() + expireSeconds);
        }

        document.cookie = name +"="+ escape(value) +
            ";domain="+ window.location.hostname +
            ";path=/"+
            ";expires="+expireDate.toUTCString();
    }

    function deleteCookie(name) {
        setCookie({name: name, value: "", seconds: 1});
    }

Usage:

setCookie({name: "reminder", value: "buyCoffee", minutes: 20});
deleteCookie("reminder");

Toggle button using two image on different state

Do this:

<ToggleButton 
        android:id="@+id/toggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/check"   <!--check.xml-->
        android:layout_margin="10dp"
        android:textOn=""
        android:textOff=""
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:layout_centerVertical="true"/>

create check.xml in drawable folder

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use grey -->
    <item android:drawable="@drawable/selected_image"
          android:state_checked="true" />
    <!-- When not selected, use white-->
    <item android:drawable="@drawable/unselected_image"
        android:state_checked="false"/>

 </selector>

How to tell if a JavaScript function is defined

Try:

if (typeof(callback) == 'function')

Retrieve column names from java.sql.ResultSet

SQLite 3

Using getMetaData();

DatabaseMetaData md = conn.getMetaData();
ResultSet rset = md.getColumns(null, null, "your_table_name", null);

System.out.println("your_table_name");
while (rset.next())
{
    System.out.println("\t" + rset.getString(4));
}

EDIT: This works with PostgreSQL as well

Combining the results of two SQL queries as separate columns

You can aliasing both query and Selecting them in the select query
http://sqlfiddle.com/#!2/ca27b/1

SELECT x.a, y.b FROM (SELECT * from a) as x, (SELECT * FROM b) as y

How to execute a .sql script from bash

You simply need to start mysql and feed it with the content of db.sql:

mysql -u user -p < db.sql

How to Increase Import Size Limit in phpMyAdmin

If you have direct root SSH access to the machine you will be able to change the settings in: /usr/local/cpanel/3rdparty/etc/phpmyadmin/php.ini

Just change the line: upload_max_filesize = 50M

How to find all occurrences of a substring?

This thread is a little old but this worked for me:

numberString = "onetwothreefourfivesixseveneightninefiveten"
testString = "five"

marker = 0
while marker < len(numberString):
    try:
        print(numberString.index("five",marker))
        marker = numberString.index("five", marker) + 1
    except ValueError:
        print("String not found")
        marker = len(numberString)

Best way to format integer as string with leading zeros?

For Python 3 and beyond: str.zfill() is still the most readable option

But it is a good idea to look into the new and powerful str.format(), what if you want to pad something that is not 0?

    # if we want to pad 22 with zeros in front, to be 5 digits in length:
    str_output = '{:0>5}'.format(22)
    print(str_output)
    # >>> 00022
    # {:0>5} meaning: ":0" means: pad with 0, ">" means move 22 to right most, "5" means the total length is 5

    # another example for comparision
    str_output = '{:#<4}'.format(11)
    print(str_output)
    # >>> 11##

    # to put it in a less hard-coded format:
    int_inputArg = 22
    int_desiredLength = 5
    str_output = '{str_0:0>{str_1}}'.format(str_0=int_inputArg, str_1=int_desiredLength)
    print(str_output)
    # >>> 00022

PHP: How to remove specific element from an array?

I'm currently using this function:

function array_delete($del_val, $array) {
    if(is_array($del_val)) {
         foreach ($del_val as $del_key => $del_value) {
            foreach ($array as $key => $value){
                if ($value == $del_value) {
                    unset($array[$key]);
                }
            }
        }
    } else {
        foreach ($array as $key => $value){
            if ($value == $del_val) {
                unset($array[$key]);
            }
        }
    }
    return array_values($array);
}

You can input an array or only a string with the element(s) which should be removed. Write it like this:

$detils = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
$detils = array_delete(array('orange', 'apple'), $detils);

OR

$detils = array_delete('orange', $detils);

It'll also reindex it.

Get git branch name in Jenkins Pipeline/Jenkinsfile

Switching to a multibranch pipeline allowed me to access the branch name. A regular pipeline was not advised.

git revert back to certain commit

git reset --hard 4a155e5 Will move the HEAD back to where you want to be. There may be other references ahead of that time that you would need to remove if you don't want anything to point to the history you just deleted.

Pandas read in table without headers

Make sure you specify pass header=None and add usecols=[3,6] for the 4th and 7th columns.

Get number of digits with JavaScript

it would be simple to get the length as

  `${NUM}`.length

where NUM is the number to get the length for

How do I convert strings between uppercase and lowercase in Java?

Coverting the first letter of word capital

input:

hello world

String A = hello;
String B = world;
System.out.println(A.toUpperCase().charAt(0)+A.substring(1) + " " + B.toUpperCase().charAt(0)+B.substring(1));

Output:

Hello World

taking input of a string word by word

Put the line in a stringstream and extract word by word back:

#include <iostream>
#include <sstream>
using namespace std;

int main()
{
    string t;
    getline(cin,t);

    istringstream iss(t);
    string word;
    while(iss >> word) {
        /* do stuff with word */
    }
}

Of course, you can just skip the getline part and read word by word from cin directly.

And here you can read why is using namespace std considered bad practice.

ASP.NET file download from server

Try this set of code to download a CSV file from the server.

byte[] Content= File.ReadAllBytes(FilePath); //missing ;
Response.ContentType = "text/csv";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".csv");
Response.BufferOutput = true;
Response.OutputStream.Write(Content, 0, Content.Length);
Response.End();

How to find server name of SQL Server Management Studio

start -> CMD -> (Write comand) SQLCMD -L first line is Server name if Server name is (local) Server name is : YourPcName\SQLEXPRESS

Convert double to float in Java

The problem is, your value cannot be stored accurately in single precision floating point type. Proof:

public class test{
    public static void main(String[] args){
        Float a = Float.valueOf("23423424666767");
        System.out.printf("%f\n", a); //23423424135168,000000
        System.out.println(a);        //2.34234241E13
    }
}

Another thing is: you don't get "2.3423424666767E13", it's just the visual representation of the number stored in memory. "How you print out" and "what is in memory" are two distinct things. Example above shows you how to print the number as float, which avoids scientific notation you were getting.

RS256 vs HS256: What's the difference?

short answer, specific to OAuth2,

  • HS256 user client secret to generate the token signature and same secret is required to validate the token in back-end. So you should have a copy of that secret in your back-end server to verify the signature.
  • RS256 use public key encryption to sign the token.Signature(hash) will create using private key and it can verify using public key. So, no need of private key or client secret to store in back-end server, but back-end server will fetch the public key from openid configuration url in your tenant (https://[tenant]/.well-known/openid-configuration) to verify the token. KID parameter inside the access_toekn will use to detect the correct key(public) from openid-configuration.

String Resource new line /n not possible?

I know this is pretty old question but it topped the list when I searched. So I wanted to update with another method.

In the strings.xml file you can do the \n or you can simply press enter:

<string name="Your string name" > This is your string.

   This is the second line of your string.\n\n Third line of your string.</string>

This will result in the following on your TextView:

This is your string.

This is the second line of your string.

Third line of your string.

This is because there were two returns between the beginning declaration of the string and the new line. I also added the \n to it for clarity, as either can be used. I like to use the carriage returns in the xml to be able to see a list or whatever multiline string I have. My two cents.

Java - Using Accessor and Mutator methods

Let's go over the basics: "Accessor" and "Mutator" are just fancy names fot a getter and a setter. A getter, "Accessor", returns a class's variable or its value. A setter, "Mutator", sets a class variable pointer or its value.

So first you need to set up a class with some variables to get/set:

public class IDCard
{
    private String mName;
    private String mFileName;
    private int mID;

}

But oh no! If you instantiate this class the default values for these variables will be meaningless. B.T.W. "instantiate" is a fancy word for doing:

IDCard test = new IDCard();

So - let's set up a default constructor, this is the method being called when you "instantiate" a class.

public IDCard()
{
    mName = "";
    mFileName = "";
    mID = -1;
}

But what if we do know the values we wanna give our variables? So let's make another constructor, one that takes parameters:

public IDCard(String name, int ID, String filename)
{
    mName = name;
    mID = ID;
    mFileName = filename;
}

Wow - this is nice. But stupid. Because we have no way of accessing (=reading) the values of our variables. So let's add a getter, and while we're at it, add a setter as well:

public String getName()
{
    return mName;
}

public void setName( String name )
{
    mName = name;
}

Nice. Now we can access mName. Add the rest of the accessors and mutators and you're now a certified Java newbie. Good luck.

How to get the number of columns from a JDBC ResultSet?

This will print the data in columns and comes to new line once last column is reached.

ResultSetMetaData resultSetMetaData = res.getMetaData();
int columnCount = resultSetMetaData.getColumnCount();
for(int i =1; i<=columnCount; i++){
                if(!(i==columnCount)){

                    System.out.print(res.getString(i)+"\t");
                }
                else{
                    System.out.println(res.getString(i));
                }

            }

Neither BindingResult nor plain target object for bean name available as request attr

Make sure you declare the bean associated with the form in GET method of the associated controller and also add it in the model model.addAttribute("uploadItem", uploadItem); which contains @RequestMapping(method = RequestMethod.GET) annotation.

For example UploadItem.java is associated with myform.jsp and controller is SecureAreaController.java

myform.jsp contains

<form:form action="/securedArea" commandName="uploadItem" enctype="multipart/form-data"></form:form>

MyFormController.java

@RequestMapping("/securedArea")
@Controller
public class SecureAreaController {

@RequestMapping(method = RequestMethod.GET)
public String showForm(Model model) {
            UploadItem uploadItem = new UploadItem(); // declareing

            model.addAttribute("uploadItem", uploadItem); // adding in model
    return "securedArea/upload";
}

}

As you can see I am declaring UploadItem.java in controller GET method.

How do I convert from int to Long in Java?

I had a great deal of trouble with this. I just wanted to:

thisBill.IntervalCount = jPaidCountSpinner.getValue();

Where IntervalCount is a Long, and the JSpinner was set to return a Long. Eventually I had to write this function:

    public static final Long getLong(Object obj) throws IllegalArgumentException {
    Long rv;

    if((obj.getClass() == Integer.class) || (obj.getClass() == Long.class) || (obj.getClass() == Double.class)) {
        rv = Long.parseLong(obj.toString());
    }
    else if((obj.getClass() == int.class) || (obj.getClass() == long.class) || (obj.getClass() == double.class)) {
        rv = (Long) obj;
    }
    else if(obj.getClass() == String.class) {
        rv = Long.parseLong(obj.toString());
    }
    else {
        throw new IllegalArgumentException("getLong: type " + obj.getClass() + " = \"" + obj.toString() + "\" unaccounted for");
    }

    return rv;
}

which seems to do the trick. No amount of simple casting, none of the above solutions worked for me. Very frustrating.

VBA Macro to compare all cells of two Excel files

A very simple check you can do with Cell formulas:

Sheet 1 (new - old)

=(if(AND(Ref_New<>"";Ref_Old="");Ref_New;"")

Sheet 2 (old - new)

=(if(AND(Ref_Old<>"";Ref_New="");Ref_Old;"")

This formulas should work for an ENGLISH Excel. For other languages they need to be translated. (For German i can assist)

You need to open all three Excel Documents, then copy the first formula into A1 of your sheet 1 and the second into A1 of sheet 2. Now click in A1 of the first cell and mark "Ref_New", now you can select your reference, go to the new file and click in the A1, go back to sheet1 and do the same for "Ref_Old" with the old file. Replace also the other "Ref_New".

Doe the same for Sheet two.

Now copy the formaula form A1 over the complete range where zour data is in the old and the new file.

But two cases are not covered here:

  1. In the compared cell of New and Old is the same data (Resulting Cell will be empty)
  2. In the compared cell of New and Old is diffe data (Resulting Cell will be empty)

To cover this two cases also, you should create your own function, means learn VBA. A very useful Excel page is cpearson.com

Find and replace string values in list

You can use, for example:

words = [word.replace('[br]','<br />') for word in words]

Clear image on picturebox

if (pictureBox1.Image != null)
{
    pictureBox1.Image.Dispose();
    pictureBox1.Image = null;
}

Rails: How can I set default values in ActiveRecord?

The Phusion guys have some nice plugin for this.

Setting SMTP details for php mail () function

Under Windows only: You may try to use ini_set() functionDocs for the SMTPDocs and smtp_portDocs settings:

ini_set('SMTP', 'mysmtphost'); 
ini_set('smtp_port', 25); 

Shortcut to open file in Vim

In GVIM, The file can be browsed using open / read / write dialog;

:browse {command}

{command} - open / read / write

open - Opens the file read - Appends the file write - SaveAs dialog

Change Screen Orientation programmatically using a Button

Wherever possible, please don't use SCREEN_ORIENTATION_LANDSCAPE or SCREEN_ORIENTATION_PORTRAIT. Instead use:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);

These allow the user to orient the device to either landscape orientation, or either portrait orientation, respectively. If you've ever had to play a game with a charging cable being driven into your stomach, then you know exactly why having both orientations available is important to the user.

Note: For phones, at least several that I've checked, it only allows the "right side up" portrait mode, however, SENSOR_PORTRAIT works properly on tablets.

Note: this feature was introduced in API Level 9, so if you must support 8 or lower (not likely at this point), then instead use:

setRequestedOrientation(Build.VERSION.SDK_INT < 9 ?
                        ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE :
                        ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
setRequestedOrientation(Build.VERSION.SDK_INT < 9 ?
                        ActivityInfo.SCREEN_ORIENTATION_PORTRAIT :
                        ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);

How do I kill background processes / jobs when my shell script exits?

To clean up some mess, trap can be used. It can provide a list of stuff executed when a specific signal arrives:

trap "echo hello" SIGINT

but can also be used to execute something if the shell exits:

trap "killall background" EXIT

It's a builtin, so help trap will give you information (works with bash). If you only want to kill background jobs, you can do

trap 'kill $(jobs -p)' EXIT

Watch out to use single ', to prevent the shell from substituting the $() immediately.

Update built-in vim on Mac OS X

This blog post was helpful for me. I used the "Homebrew built Vim" solution, which in my case saved the new version in /usr/local/bin. At this point, the post suggested hiding the system vim, which didn't work for me, so I used an alias instead.

$ brew install vim
$ alias vim='/path/to/new/vim
$ which vim
vim: aliased to /path/to/new/vim

How to find tag with particular text with Beautiful Soup?

Since Beautiful Soup 4.4.0. a parameter called string does the work that text used to do in the previous versions.

string is for finding strings, you can combine it with arguments that find tags: Beautiful Soup will find all tags whose .string matches your value for the string. This code finds the tags whose .string is “Elsie”:

soup.find_all("td", string="Elsie")

For more information about string have a look this section https://www.crummy.com/software/BeautifulSoup/bs4/doc/#the-string-argument

Setting a windows batch file variable to the day of the week

This turned out way more complex then I first suspected, and I guess that's what intrigued me, I searched every where and all the methods given wouldnt work on Windows 7.

So I have an alternate solution which uses a Visual Basic Script.

The batch creates and executes the script(DayOfWeek.vbs), assigns the scripts output (Monday, Tuesday etc) to a variable (dow), the variable is then checked and another variable (dpwnum) assigned with the days number, afterwards the VBS is deleted hope it helps:

@echo off

REM Create VBS that will get day of week in same directory as batch
echo wscript.echo WeekdayName(Weekday(Date))>>DayOfWeek.vbs

REM Cycle through output to get day of week i.e monday,tuesday etc
for /f "delims=" %%a in ('cscript /nologo DayOfWeek.vbs') do @set dow=%%a

REM delete vbs
del DayOfWeek.vbs

REM Used for testing outputs days name
echo %dow%

REM Case of the days name is important must have a capital letter at start
REM Check days name and assign value depending
IF %dow%==Monday set downum=0
IF %dow%==Tuesday set downum=1
IF %dow%==Wednesday set downum=2
IF %dow%==Thursday set downum=3
IF %dow%==Friday set downum=4
IF %dow%==Saturday set downum=5
IF %dow%==Sunday set downum=6

REM print the days number 0-mon,1-tue ... 6-sun
echo %downum%

REM set a file name using day of week number
set myfile=%downum%.bak

echo %myfile%

pause
exit

EDIT:

Though I turned to VBS, It can be done in pure batch, took me a while to get it working and a lot of searching lol, but this seems to work:

 @echo off
SETLOCAL enabledelayedexpansion
SET /a count=0
FOR /F "skip=1" %%D IN ('wmic path win32_localtime get dayofweek') DO (
    if "!count!" GTR "0" GOTO next
    set dow=%%D
    SET /a count+=1
)
:next
echo %dow%
pause

The only caveat for you on the above batch is that its day of weeks are from 1-7 and not 0-6

Get Current date in epoch from Unix shell script

The Unix Date command will display in epoch time

the command is

date +"%s"

https://linux.die.net/man/1/date

Edit: Some people have observed you asked for days, so it's the result of that command divided by 86,400

Test only if variable is not null in if statement

I don't believe the expression is sensical as it is.

Elvis means "if truthy, use the value, else use this other thing."

Your "other thing" is a closure, and the value is status != null, neither of which would seem to be what you want. If status is null, Elvis says true. If it's not, you get an extra layer of closure.

Why can't you just use:

(it.description == desc) && ((status == null) || (it.status == status))

Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find calls, just use an intermediate variable.

byte[] to hex string

There is a built in method for this:

byte[] data = { 1, 2, 4, 8, 16, 32 };

string hex = BitConverter.ToString(data);

Result: 01-02-04-08-10-20

If you want it without the dashes, just remove them:

string hex = BitConverter.ToString(data).Replace("-", string.Empty);

Result: 010204081020

If you want a more compact representation, you can use Base64:

string base64 = Convert.ToBase64String(data);

Result: AQIECBAg

How to replace list item in best way

i find best for do it fast and simple

  1. find ur item in list

    var d = Details.Where(x => x.ProductID == selectedProduct.ID).SingleOrDefault();
    
  2. make clone from current

    OrderDetail dd = d;
    
  3. Update ur clone

    dd.Quantity++;
    
  4. find index in list

    int idx = Details.IndexOf(d);
    
  5. remove founded item in (1)

      Details.Remove(d);
    
  6. insert

     if (idx > -1)
          Details.Insert(idx, dd);
      else
          Details.Insert(Details.Count, dd);
    

Count the number of all words in a string

Use the regular expression symbol \\W to match non-word characters, using + to indicate one or more in a row, along with gregexpr to find all matches in a string. Words are the number of word separators plus 1.

lengths(gregexpr("\\W+", str1)) + 1

This will fail with blank strings at the beginning or end of the character vector, when a "word" doesn't satisfy \\W's notion of non-word (one could work with other regular expressions, \\S+, [[:alpha:]], etc., but there will always be edge cases with a regex approach), etc. It is likely more efficient than strsplit solutions, which will allocate memory for each word. Regular expressions are described in ?regex.

Update As noted in the comments and in a different answer by @Andri the approach fails with (zero) and one-word strings, and with trailing punctuation

str1 = c("", "x", "x y", "x y!" , "x y! z")
lengths(gregexpr("[A-z]\\W+", str1)) + 1L
# [1] 2 2 2 3 3

Many of the other answers also fail in these or similar (e.g., multiple spaces) cases. I think my answer's caveat about 'notion of one word' in the original answer covers problems with punctuation (solution: choose a different regular expression, e.g., [[:space:]]+), but the zero and one word cases are a problem; @Andri's solution fails to distinguish between zero and one words. So taking a 'positive' approach to finding words one might

sapply(gregexpr("[[:alpha:]]+", str1), function(x) sum(x > 0))

Leading to

sapply(gregexpr("[[:alpha:]]+", str1), function(x) sum(x > 0))
# [1] 0 1 2 2 3

Again the regular expression might be refined for different notions of 'word'.

I like the use of gregexpr() because it's memory efficient. An alternative using strsplit() (like @user813966, but with a regular expression to delimit words) and making use of the original notion of delimiting words is

lengths(strsplit(str1, "\\W+"))
# [1] 0 1 2 2 3

This needs to allocate new memory for each word that is created, and for the intermediate list-of-words. This could be relatively expensive when the data is 'big', but probably it's effective and understandable for most purposes.

How to install an npm package from GitHub directly?

UPDATE now you can do: npm install git://github.com/foo/bar.git
or in package.json:

"dependencies": {
  "bar": "git://github.com/foo/bar.git"
}

How can I use a batch file to write to a text file?

@echo off Title Writing using Batch Files color 0a

echo Example Text > Filename.txt echo Additional Text >> Filename.txt

@ECHO OFF
Title Writing Using Batch Files
color 0a

echo Example Text > Filename.txt
echo Additional Text >> Filename.txt

TypeScript - Append HTML to container element in Angular 2

There is a better solution to this answer that is more Angular based.

  1. Save your string in a variable in the .ts file

    MyStrings = ["one","two","three"]

  2. In the html file use *ngFor.

    <div class="one" *ngFor="let string of MyStrings; let i = index"> <div class="two">{{string}}</div> </div>

  3. if you want to dynamically insert the div element, just push more strings into the MyStrings array

    myFunction(nextString){ this.MyString.push(nextString) }

this way every time you click the button containing the myFunction(nextString) you effectively add another class="two" div which acts the same way as inserting it into the DOM with pure javascript.

What's the difference between all the Selection Segues?

For those who prefer a bit more practical learning, select the segue in dock, open the attribute inspector and switch between different kinds of segues (dropdown "Kind"). This will reveal options specific for each of them: for example you can see that "present modally" allows you to choose a transition type etc.

What are the performance characteristics of sqlite with very large database files?

So I did some tests with sqlite for very large files, and came to some conclusions (at least for my specific application).

The tests involve a single sqlite file with either a single table, or multiple tables. Each table had about 8 columns, almost all integers, and 4 indices.

The idea was to insert enough data until sqlite files were about 50GB.

Single Table

I tried to insert multiple rows into a sqlite file with just one table. When the file was about 7GB (sorry I can't be specific about row counts) insertions were taking far too long. I had estimated that my test to insert all my data would take 24 hours or so, but it did not complete even after 48 hours.

This leads me to conclude that a single, very large sqlite table will have issues with insertions, and probably other operations as well.

I guess this is no surprise, as the table gets larger, inserting and updating all the indices take longer.

Multiple Tables

I then tried splitting the data by time over several tables, one table per day. The data for the original 1 table was split to ~700 tables.

This setup had no problems with the insertion, it did not take longer as time progressed, since a new table was created for every day.

Vacuum Issues

As pointed out by i_like_caffeine, the VACUUM command is a problem the larger the sqlite file is. As more inserts/deletes are done, the fragmentation of the file on disk will get worse, so the goal is to periodically VACUUM to optimize the file and recover file space.

However, as pointed out by documentation, a full copy of the database is made to do a vacuum, taking a very long time to complete. So, the smaller the database, the faster this operation will finish.

Conclusions

For my specific application, I'll probably be splitting out data over several db files, one per day, to get the best of both vacuum performance and insertion/delete speed.

This complicates queries, but for me, it's a worthwhile tradeoff to be able to index this much data. An additional advantage is that I can just delete a whole db file to drop a day's worth of data (a common operation for my application).

I'd probably have to monitor table size per file as well to see when the speed will become a problem.

It's too bad that there doesn't seem to be an incremental vacuum method other than auto vacuum. I can't use it because my goal for vacuum is to defragment the file (file space isn't a big deal), which auto vacuum does not do. In fact, documentation states it may make fragmentation worse, so I have to resort to periodically doing a full vacuum on the file.

HTML form submit to PHP script

It appears that in PHP you are obtaining the value of the submit button, not the select input. If you are using GET you will want to use $_GET['website_string'] or POST would be $_POST['website_string'].

You will probably want the following HTML:

<select name="website_string">
  <option value="" selected="selected"></option>
  <option value="abc">ABC</option>
  <option value="def">def</option>
  <option value="hij">hij</option>   
</select>
<input type="submit" />

With some PHP that looks like this:

<?php

$website_string = $_POST['website_string']; // or $_GET['website_string'];

?>

reactjs giving error Uncaught TypeError: Super expression must either be null or a function, not undefined

I experienced this when missing an export statement for the JSX class.

For example:

class MyComponent extends React.Component {
}
export default MyComponent // <- add me

if arguments is equal to this string, define a variable like this string

It seems that you are looking to parse commandline arguments into your bash script. I have searched for this recently myself. I came across the following which I think will assist you in parsing the arguments:

http://rsalveti.wordpress.com/2007/04/03/bash-parsing-arguments-with-getopts/

I added the snippet below as a tl;dr

#using : after a switch variable means it requires some input (ie, t: requires something after t to validate while h requires nothing.
while getopts “ht:r:p:v” OPTION
do
     case $OPTION in
         h)
             usage
             exit 1
             ;;
         t)
             TEST=$OPTARG
             ;;
         r)
             SERVER=$OPTARG
             ;;
         p)
             PASSWD=$OPTARG
             ;;
         v)
             VERBOSE=1
             ;;
         ?)
             usage
             exit
             ;;
     esac
done

if [[ -z $TEST ]] || [[ -z $SERVER ]] || [[ -z $PASSWD ]]
then
     usage
     exit 1
fi

./script.sh -t test -r server -p password -v

How can I change UIButton title color?

If you are using Swift, this will do the same:

buttonName.setTitleColor(UIColor.blackColor(), forState: .Normal)

Hope that helps!

Python lookup hostname from IP with 1 second timeout

>>> import socket
>>> socket.gethostbyaddr("69.59.196.211")
('stackoverflow.com', ['211.196.59.69.in-addr.arpa'], ['69.59.196.211'])

For implementing the timeout on the function, this stackoverflow thread has answers on that.

Pandas: convert dtype 'object' to int

It's simple

pd.factorize(df.purchase)[0]

Example:

labels, uniques = pd.factorize(['b', 'b', 'a', 'c', 'b'])`
labels
# array([0, 0, 1, 2, 0])
uniques
# array(['b', 'a', 'c'], dtype=object)

iOS 7's blurred overlay effect using CSS?

I've been using svg filters to achieve similar effects for sprites

<svg id="gray_calendar" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 48 48 48">
  <filter id="greyscale">
    <feColorMatrix type="saturate" values="0"/>
  </filter>
  <image width="48" height="10224" xlink:href="tango48i.png" filter="url(#greyscale)"/>
</svg>
  • The viewBox attribute will select just the portion of your included image that you want.
  • Just change the filter to any that you want, such as Keith's <feGaussianBlur stdDeviation="10"/> example.
  • Use the <image ...> tag to apply it to any image or even use multiple images.
  • You can build this up with js and use it as an image or use the id in your css.

"Adaptive Server is unavailable or does not exist" error connecting to SQL Server from PHP

1. See information about the SQL server

tsql -LH SERVER_IP_ADDRESS

locale is "C"
locale charset is "646"
ServerName TITAN
InstanceName MSSQLSERVER
IsClustered No
Version 8.00.194
tcp 1433
np \\TITAN\pipe\sql\query

2. Set your freetds.conf

tsql -C    
freetds.conf directory: /usr/local/etc

[TITAN]
host = SERVER_IP_ADDRESS
port = 1433
tds version = 7.2

3 Try

tsql -S TITAN -U user -P password

OR

 'dsn' => 'dblib:host=TITAN:1433;dbname=YOURDBNAME',

See also http://www.freetds.org/userguide/confirminstall.htm (Example 3-5.)

If you get message 20009, remember you haven't connected to the machine. It's a configuration or network issue, not a protocol failure. Verify the server is up, has the name and IP address FreeTDS is using, and is listening to the configured port.

How to get complete current url for Cakephp

for CakePHP 3:

$this->Url->build(null, true) // full URL with hostname

$this->Url->build(null) // /controller/action/params

nginx - client_max_body_size has no effect

As of March 2016, I ran into this issue trying to POST json over https (from python requests, not that it matters).

The trick is to put "client_max_body_size 200M;" in at least two places http {} and server {}:

1. the http directory

  • Typically in /etc/nginx/nginx.conf

2. the server directory in your vhost.

  • For Debian/Ubuntu users who installed via apt-get (and other distro package managers which install nginx with vhosts by default), thats /etc/nginx/sites-available/mysite.com, for those who do not have vhosts, it's probably your nginx.conf or in the same directory as it.

3. the location / directory in the same place as 2.

  • You can be more specific than /, but if its not working at all, i'd recommend applying this to / and then once its working be more specific.

Remember - if you have SSL, that will require you to set the above for the SSL server and location too, wherever that may be (ideally the same as 2.). I found that if your client tries to upload on http, and you expect them to get 301'd to https, nginx will actually drop the connection before the redirect due to the file being too large for the http server, so it has to be in both.

Recent comments suggest that there is an issue with this on SSL with newer nginx versions, but i'm on 1.4.6 and everything is good :)

How to check if a process is in hang state (Linux)

you could check the files

/proc/[pid]/task/[thread ids]/status

Is it possible to have a multi-line comments in R?

R Studio (and Eclipse + StatET): Highlight the text and use CTRL+SHIFT+C to comment multiple lines in Windows. Or, command+SHIFT+C in OS-X.

Update TensorFlow

To upgrade any python package, use pip install <pkg_name> --upgrade.

So in your case it would be pip install tensorflow --upgrade. Just updated to 1.1.0

What is Model in ModelAndView from Spring MVC?

It is all explained by the javadoc for the constructor. It is a convenience constructor that populates the model with one attribute / value pair.

So ...

   new ModelAndView(view, name, value);

is equivalent to:

   Map model = ...
   model.put(name, value);
   new ModelAndView(view, model);

How can I compare two dates in PHP?

This works because of PHP's string comparison logic. Simply you can check...

if ($startdate < $date) {// do something} 
if ($startdate > $date) {// do something}

Both dates must be in the same format. Digits need to be zero-padded to the left and ordered from most significant to least significant. Y-m-d and Y-m-d H:i:s satisfy these conditions.

How do you open an SDF file (SQL Server Compact Edition)?

You can open SQL Compact 4.0 Databases from Visual Studio 2012 directly, by going to

  1. View ->
  2. Server Explorer ->
  3. Data Connections ->
  4. Add Connection...
  5. Change... (Data Source:)
  6. Microsoft SQL Server Compact 4.0
  7. Browse...

and following the instructions there.

If you're okay with them being upgraded to 4.0, you can open older versions of SQL Compact Databases also - handy if you just want to have a look at some tables, etc for stuff like Windows Phone local database development.

(note I'm not sure if this requires a specific SKU of VS2012, if it helps I'm running Premium)

Converting VS2012 Solution to VS2010

the simplest solution is.....open your website in vs2013 and go to Debug->WebsiteProperties (last option) a new window will open..

in this window go to "Build" option and change .net framework version from 4.5 to 4.0.....then select ok. [note: this step will only work if your project does not have dependencies with vs2013...]

Now open your website in vs2010

oracle diff: how to compare two tables?

Try:

select distinct T1.id
  from TABLE1 T1
 where not exists (select distinct T2.id
                     from TABLE2 T2
                    where T2.id = T1.id)

With sql oracle 11g+

mysqli::mysqli(): (HY000/2002): Can't connect to local MySQL server through socket 'MySQL' (2)

If 'localhost' doesn't work but 127.0.0.1 does. Make sure your local hosts file points to the correct location. (/etc/hosts for linux/mac, C:\Windows\System32\drivers\etc\hosts for windows).

Also, make sure your user is allowed to connect to whatever database you're trying to select.

how to pass parameters to query in SQL (Excel)

This post is old enough that this answer will probably be little use to the OP, but I spent forever trying to answer this same question, so I thought I would update it with my findings.

This answer assumes that you already have a working SQL query in place in your Excel document. There are plenty of tutorials to show you how to accomplish this on the web, and plenty that explain how to add a parameterized query to one, except that none seem to work for an existing, OLE DB query.

So, if you, like me, got handed a legacy Excel document with a working query, but the user wants to be able to filter the results based on one of the database fields, and if you, like me, are neither an Excel nor a SQL guru, this might be able to help you out.

Most web responses to this question seem to say that you should add a “?” in your query to get Excel to prompt you for a custom parameter, or place the prompt or the cell reference in [brackets] where the parameter should be. This may work for an ODBC query, but it does not seem to work for an OLE DB, returning “No value given for one or more required parameters” in the former instance, and “Invalid column name ‘xxxx’” or “Unknown object ‘xxxx’” in the latter two. Similarly, using the mythical “Parameters…” or “Edit Query…” buttons is also not an option as they seem to be permanently greyed out in this instance. (For reference, I am using Excel 2010, but with an Excel 97-2003 Workbook (*.xls))

What we can do, however, is add a parameter cell and a button with a simple routine to programmatically update our query text.

First, add a row above your external data table (or wherever) where you can put a parameter prompt next to an empty cell and a button (Developer->Insert->Button (Form Control) – You may need to enable the Developer tab, but you can find out how to do that elsewhere), like so:

[Picture of a cell of prompt (label) text, an empty cell, then a button.]

Next, select a cell in the External Data (blue) area, then open Data->Refresh All (dropdown)->Connection Properties… to look at your query. The code in the next section assumes that you already have a parameter in your query (Connection Properties->Definition->Command Text) in the form “WHERE (DB_TABLE_NAME.Field_Name = ‘Default Query Parameter')” (including the parentheses). Clearly “DB_TABLE_NAME.Field_Name” and “Default Query Parameter” will need to be different in your code, based on the database table name, database value field (column) name, and some default value to search for when the document is opened (if you have auto-refresh set). Make note of the “DB_TABLE_NAME.Field_Name” value as you will need it in the next section, along with the “Connection name” of your query, which can be found at the top of the dialog.

Close the Connection Properties, and hit Alt+F11 to open the VBA editor. If you are not on it already, right click on the name of the sheet containing your button in the “Project” window, and select “View Code”. Paste the following code into the code window (copying is recommended, as the single/double quotes are dicey and necessary).

Sub RefreshQuery()
 Dim queryPreText As String
 Dim queryPostText As String
 Dim valueToFilter As String
 Dim paramPosition As Integer
 valueToFilter = "DB_TABLE_NAME.Field_Name ="

 With ActiveWorkbook.Connections("Connection name").OLEDBConnection
     queryPreText = .CommandText
     paramPosition = InStr(queryPreText, valueToFilter) + Len(valueToFilter) - 1
     queryPreText = Left(queryPreText, paramPosition)
     queryPostText = .CommandText
     queryPostText = Right(queryPostText, Len(queryPostText) - paramPosition)
     queryPostText = Right(queryPostText, Len(queryPostText) - InStr(queryPostText, ")") + 1)
     .CommandText = queryPreText & " '" & Range("Cell reference").Value & "'" & queryPostText
 End With
 ActiveWorkbook.Connections("Connection name").Refresh
End Sub

Replace “DB_TABLE_NAME.Field_Name” and "Connection name" (in two locations) with your values (the double quotes and the space and equals sign need to be included).

Replace "Cell reference" with the cell where your parameter will go (the empty cell from the beginning) - mine was the second cell in the first row, so I put “B1” (again, the double quotes are necessary).

Save and close the VBA editor.

Enter your parameter in the appropriate cell.

Right click your button to assign the RefreshQuery sub as the macro, then click your button. The query should update and display the right data!

Notes: Using the entire filter parameter name ("DB_TABLE_NAME.Field_Name =") is only necessary if you have joins or other occurrences of equals signs in your query, otherwise just an equals sign would be sufficient, and the Len() calculation would be superfluous. If your parameter is contained in a field that is also being used to join tables, you will need to change the "paramPosition = InStr(queryPreText, valueToFilter) + Len(valueToFilter) - 1" line in the code to "paramPosition = InStr(Right(.CommandText, Len(.CommandText) - InStrRev(.CommandText, "WHERE")), valueToFilter) + Len(valueToFilter) - 1 + InStr(.CommandText, "WHERE")" so that it only looks for the valueToFilter after the "WHERE".

This answer was created with the aid of datapig’s “BaconBits” where I found the base code for the query update.

How to force NSLocalizedString to use a specific language

As said earlier, just do:

[[NSUserDefaults standardUserDefaults] setObject: [NSArray arrayWithObjects:@"el", nil] forKey:@"AppleLanguages"];

But to avoid having to restart the app, put the line in the main method of main.m, just before UIApplicationMain(...).

How can I round down a number in Javascript?

You need to put -1 to round half down and after that multiply by -1 like the example down bellow.

<script type="text/javascript">

  function roundNumber(number, precision, isDown) {
    var factor = Math.pow(10, precision);
    var tempNumber = number * factor;
    var roundedTempNumber = 0;
    if (isDown) {
      tempNumber = -tempNumber;
      roundedTempNumber = Math.round(tempNumber) * -1;
    } else {
      roundedTempNumber = Math.round(tempNumber);
    }
    return roundedTempNumber / factor;
  }
</script>

<div class="col-sm-12">
  <p>Round number 1.25 down: <script>document.write(roundNumber(1.25, 1, true));</script>
  </p>
  <p>Round number 1.25 up: <script>document.write(roundNumber(1.25, 1, false));</script></p>
</div>

importing jar libraries into android-studio

Running Android Studio 0.4.0 Solved the problem of importing jar by

Project Structure > Modules > Dependencies > Add Files
Browse to the location of jar file and select it

For those like manual editing Open app/build.gradle

dependencies {
    compile files('src/main/libs/xxx.jar')
}

How to automatically import data from uploaded CSV or XLS file into Google Sheets

(Mar 2017) The accepted answer is not the best solution. It relies on manual translation using Apps Script, and the code may not be resilient, requiring maintenance. If your legacy system autogenerates CSV files, it's best they go into another folder for temporary processing (importing [uploading to Google Drive & converting] to Google Sheets files).

My thought is to let the Drive API do all the heavy-lifting. The Google Drive API team released v3 at the end of 2015, and in that release, insert() changed names to create() so as to better reflect the file operation. There's also no more convert flag -- you just specify MIMEtypes... imagine that!

The documentation has also been improved: there's now a special guide devoted to uploads (simple, multipart, and resumable) that comes with sample code in Java, Python, PHP, C#/.NET, Ruby, JavaScript/Node.js, and iOS/Obj-C that imports CSV files into Google Sheets format as desired.

Below is one alternate Python solution for short files ("simple upload") where you don't need the apiclient.http.MediaFileUpload class. This snippet assumes your auth code works where your service endpoint is DRIVE with a minimum auth scope of https://www.googleapis.com/auth/drive.file.

# filenames & MIMEtypes
DST_FILENAME = 'inventory'
SRC_FILENAME = DST_FILENAME + '.csv'
SHT_MIMETYPE = 'application/vnd.google-apps.spreadsheet'
CSV_MIMETYPE = 'text/csv'

# Import CSV file to Google Drive as a Google Sheets file
METADATA = {'name': DST_FILENAME, 'mimeType': SHT_MIMETYPE}
rsp = DRIVE.files().create(body=METADATA, media_body=SRC_FILENAME).execute()
if rsp:
    print('Imported %r to %r (as %s)' % (SRC_FILENAME, DST_FILENAME, rsp['mimeType']))

Better yet, rather than uploading to My Drive, you'd upload to one (or more) specific folder(s), meaning you'd add the parent folder ID(s) to METADATA. (Also see the code sample on this page.) Finally, there's no native .gsheet "file" -- that file just has a link to the online Sheet, so what's above is what you want to do.

If not using Python, you can use the snippet above as pseudocode to port to your system language. Regardless, there's much less code to maintain because there's no CSV parsing. The only thing remaining is to blow away the CSV file temp folder your legacy system wrote to.

How to check if bootstrap modal is open, so I can use jquery validate?

$("element").data('bs.modal').isShown

won't work if the modal hasn't been shown before. You will need to add an extra condition:

$("element").data('bs.modal')

so the answer taking into account first appearance:

if ($("element").data('bs.modal') && $("element").data('bs.modal').isShown){
... 
}

Escaping Strings in JavaScript

Use encodeURI()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI

Escapes pretty much all problematic characters in strings for proper JSON encoding and transit for use in web applications. It's not a perfect validation solution but it catches the low-hanging fruit.