Programs & Examples On #Recreate

Xcode 10: A valid provisioning profile for this executable was not found

I did the following :

  1. Disconnected the device where the app was not getting installed
  2. Connected a different device < It installed on this second device
  3. After some time connected the first device and it worked!

This is very weird but it worked for me, might work for others and save the frustration.

I get conflicting provisioning settings error when I try to archive to submit an iOS app

  1. General -> Signing -> check automatically manage signing and select team

  2. Build settings -> Signing -> Code Signing Identity -> SET ALL TO "IOS developer"

Kubernetes pod gets recreated when deleted

You can do kubectl get replicasets check for old deployment based on age or time

Delete old deployment based on time if you want to delete same current running pod of application

kubectl delete replicasets <Name of replicaset>

What's the source of Error: getaddrinfo EAI_AGAIN?

If you get this error from within a docker container, e.g. when running npm install inside of an alpine container, the cause could be that the network changed since the container was started.

To solve this, just stop and restart the container

docker-compose down
docker-compose up

Source: https://github.com/moby/moby/issues/32106#issuecomment-578725551

React - Preventing Form Submission

import React, { Component } from 'react';

export class Form extends Component {
  constructor(props) {
    super();
    this.state = {
      username: '',
    };
  }
  handleUsername = (event) => {
    this.setState({
      username: event.target.value,
    });
  };

  submited = (event) => {
    alert(`Username: ${this.state.username},`);
    event.preventDefault();
  };
  render() {
    return (
      <div>
        <form onSubmit={this.submited}>
          <label>Username:</label>
          <input
            type="text"
            value={this.state.username}
            onChange={this.handleUsername}
          />
          <button>Submit</button>
        </form>
      </div>
    );
  }
}

export default Form;

How to sort dates from Oldest to Newest in Excel?

Convert text to date format via the "Data" tab.

Highlight the relevant section and then select from the top menu Data> Datat Tools > Text to Column (depending on your version).

Choose the "Delimited" option.

Toggle through the Delimiter options until the entry appears in the desired format, and select "Next".

Under the Data format, select Date (DMY)

Select "finish" and the issue should be resolved.

Could not find server 'server name' in sys.servers. SQL Server 2014

I had the problem due to an extra space in the name of the linked server. "SERVER1, 1234" instead of "SERVER1,1234"

What does "Table does not support optimize, doing recreate + analyze instead" mean?

The better option is create a new table copy the rows to the destination table, drop the actual table and rename the newly created table . This method is good for small tables,

Best way to add Gradle support to IntelliJ Project

  1. Add build.gradle in your project's root directory.

  2. Then just File -> Invalidate Caches / Restart

Here is a basic build.gradle for Java projects:

plugins {
    id 'java'
}

sourceCompatibility = '1.8'
targetCompatibility = '1.8'
version = '1.2.1'

Command failed due to signal: Segmentation fault: 11

Any crash is a compiler bug (whether or not your code is valid). Try the latest beta and if it still crashes file a bug report at bugs.swift.org. The Swift team are very responsive on these.

How do I style appcompat-v7 Toolbar like Theme.AppCompat.Light.DarkActionBar?

The cleanest way I found to do this is create a child of 'ThemeOverlay.AppCompat.Dark.ActionBar'. In the example, I set the Toolbar's background color to RED and text's color to BLUE.

<style name="MyToolbar" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="android:background">#FF0000</item>
    <item name="android:textColorPrimary">#0000FF</item>
</style>

You can then apply your theme to the toolbar:

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    app:theme="@style/MyToolbar"
    android:minHeight="?attr/actionBarSize"/>

How can I copy a conditional formatting from one document to another?

To copy conditional formatting from google spreadsheet (doc1) to another (doc2) you need to do the following:

  1. Go to the bottom of doc1 and right-click on the sheet name.
  2. Select Copy to
  3. Select doc2 from the options you have (note: doc2 must be on your google drive as well)
  4. Go to doc2 and open the newly "pasted" sheet at the bottom (it should be the far-right one)
  5. Select the cell with the formatting you want to use and copy it.
  6. Go to the sheet in doc2 you would like to modify.
  7. Select the cell you want your formatting to go to.
  8. Right click and choose paste special and then paste conditional formatting only
  9. Delete the pasted sheet if you don't want it there. Done.

How to allow user to pick the image with Swift?

Incase if you don't want to have a separate button, here is a another way. Attached a gesture on imageView itself, where on tap of image a alert will popup with two option. You will have the option to choose either from gallery/photo library or to cancel the alert.

import UIKit
import CoreData

class AddDetailsViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet weak var imageView: UIImageView!

var picker:UIImagePickerController? = UIImagePickerController()

@IBAction func saveButton(sender: AnyObject) {
    let managedContext = (UIApplication.sharedApplication().delegate as? AppDelegate)!.managedObjectContext

    let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedContext)

    let person = Person(entity: entity!, insertIntoManagedObjectContext: managedContext)

    person.image = UIImageJPEGRepresentation(imageView.image!, 1.0) //imageView.image

    do {
         try person.managedObjectContext?.save()
         //people.append(person)
       } catch let error as NSError {
         print("Could not save \(error)")
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(AddDetailsViewController.tapGesture(_:)))
    imageView.addGestureRecognizer(tapGesture)
    imageView.userInteractionEnabled = true

    picker?.delegate = self
    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func tapGesture(gesture: UIGestureRecognizer) {
    let alert:UIAlertController = UIAlertController(title: "Profile Picture Options", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)

    let gallaryAction = UIAlertAction(title: "Open Gallary", style: UIAlertActionStyle.Default) {
        UIAlertAction in self.openGallary()
    }

    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
        UIAlertAction in self.cancel()
    }

    alert.addAction(gallaryAction)
    alert.addAction(cancelAction)

    self.presentViewController(alert, animated: true, completion: nil)

}


func openGallary() {
    picker!.allowsEditing = false
    picker!.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
    presentViewController(picker!, animated: true, completion: nil)
}

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        imageView.contentMode = .ScaleAspectFit
        imageView.image = pickedImage
    }

    dismissViewControllerAnimated(true, completion: nil)
}

func cancel(){
    print("Cancel Clicked")
}

}

Adding more to the question, implemented the logic to store images in CoreData.

How to delete Project from Google Developers Console

You can try delete project via Google Cloud Platform https://console.cloud.google.com/iam-admin/projects delete project from google cloud platform

Select required project and click DELETE PROJECT. The project will be completely deleted after 7 days

How to copy Docker images from one host to another without using a repository

For a flattened export of a container's filesystem, use;

docker export CONTAINER_ID > my_container.tar

Use cat my_container.tar | docker import - to import said image.

Undo git stash pop that results in merge conflict

As it turns out, Git is smart enough not to drop a stash if it doesn't apply cleanly. I was able to get to the desired state with the following steps:

  1. To unstage the merge conflicts: git reset HEAD . (note the trailing dot)
  2. To save the conflicted merge (just in case): git stash
  3. To return to master: git checkout master
  4. To pull latest changes: git fetch upstream; git merge upstream/master
  5. To correct my new branch: git checkout new-branch; git rebase master
  6. To apply the correct stashed changes (now 2nd on the stack): git stash apply stash@{1}

Sequelize, convert entity to plain object

Best and the simple way of doing is :

Just use the default way from Sequelize

db.Sensors.findAll({
    where: {
        nodeid: node.nodeid
    },
    raw : true // <----------- Magic is here
}).success(function (sensors) {
        console.log(sensors);
});

Note : [options.raw] : Return raw result. See sequelize.query for more information.


For the nested result/if we have include model , In latest version of sequlize ,

db.Sensors.findAll({
    where: {
        nodeid: node.nodeid
    },
    include : [
        { model : someModel }
    ]
    raw : true , // <----------- Magic is here
    nest : true // <----------- Magic is here
}).success(function (sensors) {
        console.log(sensors);
});

.jar error - could not find or load main class

Had this problem couldn't find the answer so i went looking on other threads, I found that i was making my app with 1.8 but for some reason my jre was out dated even though i remember updating it. I downloaded the lastes jre 8 and the jar file runs perfectly. Hope this helps.

Image overlay on responsive sized images bootstrap

<div class="col-md-4 py-3 pic-card">
          <div class="card ">
          <div class="pic-overlay"></div>
          <img class="img-fluid " src="images/Site Images/Health & Fitness-01.png" alt="">
          <div class="centeredcard">
            <h3>
              <span class="card-headings">HEALTH & FITNESS</span>
            </h3>
            <div class="content-inner mt-5">
              <p class="lead  p-overlay">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Recusandae ipsam nemo quasi quo quae voluptate.</p>
            </div>
          </div>
          </div>
        </div>


.pic-card{
     position: relative;

 }
 .pic-overlay{

    top: 0;
    left: 0;
    right:0;
    bottom:0;
    width: 100%;
    height: 100%;
    position: absolute;
    transition: background-color 0.5s ease;

 }
 .content-inner{
    position: relative;
     display: none;
 }

 .pic-card:hover{
     .pic-overlay{
        background-color: $dark-overlay;

     }

     .content-inner{
         display: block;
         cursor: pointer;
     }

     .card-headings{
        font-size: 15px;
        padding: 0;
     }

     .card-headings::after{
        content: '';
        width: 80%;
        border-bottom: solid 2px  rgb(52, 178, 179);
        position: absolute;
        left: 5%;
        top: 25%;
        z-index: 1;
     }
     .p-overlay{
         font-size: 15px;
     }
 }



enter code here

How to import a bak file into SQL Server Express

To do this via TSQL (ssms query window or sqlcmd.exe) just run:

RESTORE DATABASE MyDatabase FROM DISK='c:\backups\MyDataBase1.bak'

To do it via GUI - open SSMS, right click on Databases and follow the steps below

enter image description here enter image description here

Dilemma: when to use Fragments vs Activities:

It depends what you want to build really. For example the navigation drawer uses fragments. Tabs use fragments as well. Another good implementation,is where you have a listview. When you rotate the phone and click a row the activity is shown in the remaining half of the screen. Personally,I use fragments and fragment dialogs,as it is more professional. Plus they are handled easier in rotation.

How to re-create database for Entity Framework?

A possible very simple fix that worked for me. After deleting any database references and connections you find in server/serverobject explorer, right click the App_Data folder (didn't show any objects within the application for me) and select open. Once open put all the database/etc. files in a backup folder or if you have the guts just delete them. Run your application and it should recreate everything from scratch.

MySQL error #1054 - Unknown column in 'Field List'

You have an error in your OrderQuantity column. It is named "OrderQuantity" in the INSERT statement and "OrderQantity" in the table definition.

Also, I don't think you can use NOW() as default value in OrderDate. Try to use the following:

 OrderDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP

Example Fiddle

refresh leaflet map: map container is already initialized

Html:

<div id="weathermap"></div>

JavaScript:

function buildMap(lat,lon)  {
    document.getElementById('weathermap').innerHTML = "<div id='map' style='width: 100%; height: 100%;'></div>";
    var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
                    osmAttribution = 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors,' +
                        ' <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>',
    osmLayer = new L.TileLayer(osmUrl, {maxZoom: 18, attribution: osmAttribution});
    var map = new L.Map('map');
    map.setView(new L.LatLng(lat,lon), 9 );
    map.addLayer(osmLayer);
    var validatorsLayer = new OsmJs.Weather.LeafletLayer({lang: 'en'});
    map.addLayer(validatorsLayer);
}

I use this:

document.getElementById('weathermap').innerHTML = "<div id='map' style='width: 100%; height: 100%;'></div>";

to reload content of div where render map.

WPF C# button style

<!--Customize button -->

<LinearGradientBrush x:Key="Buttongradient" StartPoint="0.500023,0.999996" EndPoint="0.500023,4.37507e-006">
    <GradientStop Color="#5e5e5e" Offset="1" />
    <GradientStop Color="#0b0b0b" Offset="0" />
</LinearGradientBrush> 

<Style x:Key="hhh" TargetType="{x:Type Button}">
    <Setter Property="Background" Value="{DynamicResource Buttongradient}"/>
    <Setter Property="Foreground" Value="White" />
    <Setter Property="FontSize" Value="15" />
    <Setter Property="SnapsToDevicePixels" Value="True" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border CornerRadius="4" Background="{TemplateBinding Background}" BorderBrush="Black" BorderThickness="0.5">
                    <Border.Effect>
                        <DropShadowEffect ShadowDepth="0" BlurRadius="2"></DropShadowEffect>
                    </Border.Effect>

                    <Grid>

                        <Path Width="9" Height="16.5" Stretch="Fill" Fill="#000"  HorizontalAlignment="Left" Margin="16.5,0,0,0" Data="F1 M 30.0833,22.1667L 50.6665,37.6043L 50.6665,38.7918L 30.0833,53.8333L 30.0833,22.1667 Z " Opacity="0.2">

                        </Path>
                        <Path x:Name="PathIcon" Width="8" Height="15"  Stretch="Fill" Fill="#4C87B3" HorizontalAlignment="Left" Margin="17,0,0,0" Data="F1 M 30.0833,22.1667L 50.6665,37.6043L 50.6665,38.7918L 30.0833,53.8333L 30.0833,22.1667 Z ">
                            <Path.Effect>
                                <DropShadowEffect ShadowDepth="0" BlurRadius="5"></DropShadowEffect>
                            </Path.Effect>
                        </Path>


                        <Line  HorizontalAlignment="Left" Margin="40,0,0,0" Name="line4" Stroke="Black" VerticalAlignment="Top" Width="2" Y1="0" Y2="640" Opacity="0.5" />
                        <ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" />
                    </Grid>
                </Border>

                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="#E59400" />
                        <Setter Property="Foreground" Value="White" />
                        <Setter TargetName="PathIcon" Property="Fill" Value="Black" />
                    </Trigger>

                    <Trigger Property="IsPressed" Value="True">
                        <Setter Property="Background" Value="OrangeRed" />
                        <Setter Property="Foreground" Value="White" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>  

Wavy shape with css

My pure CSS implementation based on above with 100% width. Hope it helps!

_x000D_
_x000D_
#wave-container {_x000D_
  width: 100%;_x000D_
  height: 100px;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
#wave {_x000D_
  display: block;_x000D_
  position: relative;_x000D_
  height: 40px;_x000D_
  background: black;_x000D_
}_x000D_
_x000D_
#wave:before {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  border-radius: 100%;_x000D_
  width: 100%;_x000D_
  height: 300px;_x000D_
  background-color: white;_x000D_
  right: -25%;_x000D_
  top: 20px_x000D_
}_x000D_
_x000D_
#wave:after {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  border-radius: 100%;_x000D_
  width: 100%;_x000D_
  height: 300px;_x000D_
  background-color: black;_x000D_
  left: -25%;_x000D_
  top: -240px;_x000D_
}
_x000D_
<div id="wave-container">_x000D_
  <div id="wave">_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to delete and recreate from scratch an existing EF Code First database

Let me help in updating the answers here since new users will find it useful. I believe the aim is to delete the database itself and recreate it using EF Code First approach. 1.Open your project in Visual Studio using the ".sln" extention. 2.Select Server Explorer( it is oftentimes on the left) 3.Select SQL Server Object Explorer. 4.The database you want to delete would be listed under any of the localDB. Right-Click it and select delete.

How to reset db in Django? I get a command 'reset' not found error

reset has been replaced by flush with Django 1.5, see:

python manage.py help flush

How to convert variable (object) name into String

You can use deparse and substitute to get the name of a function argument:

myfunc <- function(v1) {
  deparse(substitute(v1))
}

myfunc(foo)
[1] "foo"

Open Popup window using javascript

To create a popup you'll need the following script:

<script language="javascript" type="text/javascript">

function popitup(url) {
newwindow=window.open(url,'name','height=200,width=150');
if (window.focus) {newwindow.focus()}
return false;
}


</script>

Then, you link to it by:

  <a href="popupex.html" onclick="return popitup('popupex.html')">Link to popup</a>

If you want you can call the function directly from document.ready also. Or maybe from another function.

SQL Server database restore error: specified cast is not valid. (SqlManagerUI)

The GUI can be fickle at times. The error you got when using T-SQL is because you're trying to overwrite an existing database, but did not specify to overwrite/replace the existing database. The following might work:

Use Master
Go
RESTORE DATABASE Publications
  FROM DISK = 'C:\Publications_backup_2012_10_15_010004_5648316.bak'
  WITH 
    MOVE 'Publications' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS2008R2\MSSQL\DATA\Publications.mdf',--adjust path
    MOVE 'Publications_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS2008R2\MSSQL\DATA\Publications.ldf'
, REPLACE -- Add REPLACE to specify the existing database which should be overwritten.

After updating Entity Framework model, Visual Studio does not see changes

Are you working in an N-Tiered project? If so, try rebuilding your Data Layer (or wherever your EDMX file is stored) before using it.

Entity Framework Migrations renaming tables and columns

In ef core, you can change the migration that was created after add migration. And then do update-database. A sample has given below:

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.RenameColumn(name: "Type", table: "Users", newName: "Discriminator", schema: "dbo");
}

protected override void Down(MigrationBuilder migrationBuilder)
{            
    migrationBuilder.RenameColumn(name: "Discriminator", table: "Users", newName: "Type", schema: "dbo");
}

VC++ fatal error LNK1168: cannot open filename.exe for writing

Start your program as an administrator. The program can't rewrite your files cause your files are in a protected location on your hard drive.

"Prevent saving changes that require the table to be re-created" negative effects

SQL Server drops and recreates the tables only if you:

  • Add a new column
  • Change the Allow Nulls setting for a column
  • Change the column order in the table
  • Change the column data type

Using ALTER is safer, as in case the metadata is lost while you re-create the table, your data will be lost.

How do I set a fixed background image for a PHP file?

Your question doesn't have anything to do with PHP... just CSS.

Your CSS is correct, but your browser won't typically be able to open what you have put in for a URL. At a minimum, you'll need a file: path. It would be best to reference the file by its relative path.

Understanding Fragment's setRetainInstance(boolean)

SetRetainInstance(true) allows the fragment sort of survive. Its members will be retained during configuration change like rotation. But it still may be killed when the activity is killed in the background. If the containing activity in the background is killed by the system, it's instanceState should be saved by the system you handled onSaveInstanceState properly. In another word the onSaveInstanceState will always be called. Though onCreateView won't be called if SetRetainInstance is true and fragment/activity is not killed yet, it still will be called if it's killed and being tried to be brought back.

Here are some analysis of the android activity/fragment hope it helps. http://ideaventure.blogspot.com.au/2014/01/android-activityfragment-life-cycle.html

Can't change table design in SQL Server 2008

The answer is on the MSDN site:

The Save (Not Permitted) dialog box warns you that saving changes is not permitted because the changes you have made require the listed tables to be dropped and re-created.

The following actions might require a table to be re-created:

  • Adding a new column to the middle of the table
  • Dropping a column
  • Changing column nullability
  • Changing the order of the columns
  • Changing the data type of a column

EDIT 1:

Additional useful informations from here:

To change the Prevent saving changes that require the table re-creation option, follow these steps:

  1. Open SQL Server Management Studio (SSMS).
  2. On the Tools menu, click Options.
  3. In the navigation pane of the Options window, click Designers.
  4. Select or clear the Prevent saving changes that require the table re-creation check box, and then click OK.

Note If you disable this option, you are not warned when you save the table that the changes that you made have changed the metadata structure of the table. In this case, data loss may occur when you save the table.

Risk of turning off the "Prevent saving changes that require table re-creation" option

Although turning off this option can help you avoid re-creating a table, it can also lead to changes being lost. For example, suppose that you enable the Change Tracking feature in SQL Server 2008 to track changes to the table. When you perform an operation that causes the table to be re-created, you receive the error message that is mentioned in the "Symptoms" section. However, if you turn off this option, the existing change tracking information is deleted when the table is re-created. Therefore, we recommend that you do not work around this problem by turning off the option.

Settings, screen shot

ALTER TABLE on dependent column

If your constraint is on a user type, then don't forget to see if there is a Default Constraint, usually something like DF__TableName__ColumnName__6BAEFA67, if so then you will need to drop the Default Constraint, like this:

ALTER TABLE TableName DROP CONSTRAINT [DF__TableName__ColumnName__6BAEFA67]

For more info see the comments by the brilliant Aaron Bertrand on this answer.

Xcode error - Thread 1: signal SIGABRT

You are trying to load a XIB named DetailViewController, but no such XIB exists or it's not member of your current target.

How can I alter a primary key constraint using SQL syntax?

PRIMARY KEY CONSTRAINT cannot be altered, you may only drop it and create again. For big datasets it can cause a long run time and thus - table inavailability.

ViewPager and fragments — what's the right way to store fragment's state?

What is that BasePagerAdapter? You should use one of the standard pager adapters -- either FragmentPagerAdapter or FragmentStatePagerAdapter, depending on whether you want Fragments that are no longer needed by the ViewPager to either be kept around (the former) or have their state saved (the latter) and re-created if needed again.

Sample code for using ViewPager can be found here

It is true that the management of fragments in a view pager across activity instances is a little complicated, because the FragmentManager in the framework takes care of saving the state and restoring any active fragments that the pager has made. All this really means is that the adapter when initializing needs to make sure it re-connects with whatever restored fragments there are. You can look at the code for FragmentPagerAdapter or FragmentStatePagerAdapter to see how this is done.

Strange Characters in database text: Ã, Ã, ¢, â‚ €,

If the charset of the tables is the same as it's content try to use mysql_set_charset('UTF8', $link_identifier). Note that MySQL uses UTF8 to specify the UTF-8 encoding instead of UTF-8 which is more common.

Check my other answer on a similar question too.

How to set JVM parameters for Junit Unit Tests?

You can use systemPropertyVariables (java.protocol.handler.pkgs is your JVM argument name):

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.12.4</version>
    <configuration>
        <systemPropertyVariables>
            <java.protocol.handler.pkgs>com.zunix.base</java.protocol.handler.pkgs>
            <log4j.configuration>log4j-core.properties</log4j.configuration>
        </systemPropertyVariables>
    </configuration>
</plugin>

http://maven.apache.org/surefire/maven-surefire-plugin/examples/system-properties.html

Sql Server 'Saving changes is not permitted' error ? Prevent saving changes that require table re-creation

1) Open tool which is on top.
2) Choose options from Picklist.
3) Now Comes the popup and you can now select designers option from the list of menus on the left side.
4) Now prevent saving changes need to be unchecked that needed table re-creation. Now Click OK.

How do I specify a password to 'psql' non-interactively?

  • in one line:

    export PGPASSWORD='password'; psql -h 'server name' -U 'user name' -d 'base name' -c 'command'
    

    with command a sql command such as "select * from schema.table"

  • or more readable:

    export PGPASSWORD='password'
    psql -h 'server name' -U 'user name' -d 'base name' \
         -c 'command' (eg. "select * from schema.table")
    

Maven does not find JUnit tests to run

/my_program/src/test/java/ClassUnderTestTests.java

should be

/my_program/src/test/java/ClassUnderTestTest.java

The Maven finds those ends Test or starts with Test to run automatically.

However, you can using

mvn surefire:test -Dtest=ClassUnderTestTests.java 

to run your tests.

Best way to create unique token in Rails?

you can user has_secure_token https://github.com/robertomiranda/has_secure_token

is really simple to use

class User
  has_secure_token :token1, :token2
end

user = User.create
user.token1 => "44539a6a59835a4ee9d7b112b48cd76e"
user.token2 => "226dd46af6be78953bde1641622497a8"

Session unset, or session_destroy?

Unset will destroy a particular session variable whereas session_destroy() will destroy all the session data for that user.

It really depends on your application as to which one you should use. Just keep the above in mind.

unset($_SESSION['name']); // will delete just the name data

session_destroy(); // will delete ALL data associated with that user.

ERROR 1396 (HY000): Operation CREATE USER failed for 'jack'@'localhost'

I had the same problem as OP, and the accepted answer did not work for me. In the comments of the accepted answer, @Rathish posted a solution which worked for me, I wanted to call attention to it.

Here's the link:

https://www.rathishkumar.in/2018/10/Error-1396-HY000-Operation-CREATE-DROP-USER-failed-for-user-host.html

Rathish's solution is to revoke access for all users:

REVOKE ALL ON *.* FROM 'user'@'host';
DROP USER 'user'@'host';
FLUSH PRIVILEGES;

And he also helpfully points out that you can query the following tables by selecting "user" and "host" to determine whether you have a vestigial user left-over from a previous operation:

mysql.user: User accounts, global privileges, and other non-privilege columns
mysql.db: Database-level privileges
mysql.tables_priv: Table-level privileges
mysql.columns_priv: Column-level privileges
mysql.procs_priv: Stored procedure and function privileges
mysql.proxies_priv: Proxy-user privilege

Thank you!

HTML5 form required attribute. Set custom validation message?

The easiest and cleanest way I've found is to use a data attribute to store your custom error. Test the node for validity and handle the error by using some custom html. enter image description here

le javascript

if(node.validity.patternMismatch)
        {
            message = node.dataset.patternError;
        }

and some super HTML5

<input type="text" id="city" name="city" data-pattern-error="Please use only letters for your city." pattern="[A-z ']*" required>

Chart won't update in Excel (2007)

I had the same problem while working through a tutorial (very frustrating when you follow the steps and don't get the expected result).

The tutorial to create a pie chart wanted me to select range A3:A10, then also select non-adjacent range E3:E10. I did so. I got the chart.

It then asked me to change a value and watch the percentage change, then to look at the pie chart and see the update.

It didn't update.

I looked at the data source for the pie chart, and the range was bizarre. It had the A3:A10 range notated properly, but the E10 cell reference repeated several times, and it had all of the E cells listed in a random order. It looked like

=SERIES(,(Revenue!$A$3:$A$10,Revenue!$E$3,Revenue!$E$10,Revenue!$E$10,Revenue!$E$10,Revenue!$E$10,Revenue!$E$10,Revenue!$E$9,Revenue!$E$8,Revenue!$E$7,Revenue!$E$6,Revenue!$E$5,Revenue!$E$4),1

I changed the data source to read:

=SERIES(,Revenue!$A$3:$A$10,Revenue!$E$3:$E$10,1)

Problem solved. Sometimes it's a matter of cleaning up your code so the calculations processor has less to sort through.

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

SELECT definition, uses_ansi_nulls, uses_quoted_identifier, is_schema_bound  
FROM sys.sql_modules  
WHERE object_id = OBJECT_ID('your View Name');  

The type or namespace name could not be found

Changing the framework to

.NET Framework 4 Client Profile

did the job for me.

How to create a temporary directory?

My favorite one-liner for this is

cd $(mktemp -d)

A valid provisioning profile for this executable was not found for debug mode

I had this problem too with Xcode 5.0.1. One fine day the application simply did not want to be installed on the device to which it was installed five minutes ago without any problems.

I tried to clean settings, delete derived data, recreate provisioning profiles, sign with another certificates/profiles, remove the device from the organizer, etc.

Finally, I reset my device's content and settings and successfully built my project with old profiles, certificates and bundle ID.

Razor HtmlHelper Extensions (or other namespaces for views) Not Found

This error tells you that you do not have the razor engine properly associated with your project.

Solution: In the Solution Explorer window right click on your web project and select "Manage Nuget Packages..." then install "Microsoft ASP.NET Razor". This will make sure that the properly package is installed and it will add the necessary entries into your web.config file.

Purge or recreate a Ruby on Rails database

You can use this following command line:

rake db:drop db:create db:migrate db:seed db:test:clone

How can I get the current screen orientation?

Activity.getResources().getConfiguration().orientation

The model backing the <Database> context has changed since the database was created

After some research on this topic, I found that the error is occured basically if you have an instance of db created previously on your local sql server express. So whenever you have updates on db and try to update the db/run some code on db without running Update Database command using Package Manager Console; first of all, you have to delete previous db on our local sql express manually.

Also, this solution works unless you have AutomaticMigrationsEnabled = false;in your Configuration.

If you work with a version control system (git,svn,etc.) and some other developers update db objects in production phase then this error rises whenever you update your code base and run the application.

As stated above, there are some solutions for this on code base. However, this is the most practical one for some cases.

MySQL: selecting rows where a column is null

I had the same issue when converting databases from Access to MySQL (using vb.net to communicate with the database).

I needed to assess if a field (field type varchar(1)) was null.

This statement worked for my scenario:

SELECT * FROM [table name] WHERE [field name] = ''

java.lang.IllegalArgumentException: View not attached to window manager

alex,

I could be wrong here, but I suspect that multiple phones 'in the wild' have a bug that causes them to switch orientation on applications that are marked as statically oriented. This happens quite a bit on my personal phone, and on many of the test phones our group uses (including droid, n1, g1, hero). Typically an app marked as statically oriented (perhaps vertically) will lay itself out for a second or two using a horizontal orientation, and then immediately switch back. End result is that even though you don't want your app to switch orientation, you have to be prepared that it may. I don't know under what exact conditions this behavior can be reproduced, I don't know if it is specific to a version of Android. All I know is that I have seen it happen plenty of times :(

I would recommend using the solution provided in the link you posted that suggests overriding the Activity onCreateDialog method and letting the Android OS manage the lifecycle of your Dialogs. It looks to me like even though you don't want your activity to switch orientations, it is switching orientation somewhere. You can try to track down a method that will always prevent orientation switching, but I am trying to tell you that I personally don't believe there is a foolproof way that works on all current Android phones in the market.

Programmatically relaunch/recreate an activity?

UPDATE: Android SDK 11 added a recreate() method to activities.


I've done that by simply reusing the intent that started the activity. Define an intent starterIntent in your class and assign it in onCreate() using starterIntent = getIntent();. Then when you want to restart the activity, call finish(); startActivity(starterIntent);

It isn't a very elegant solution, but it's a simple way to restart your activity and force it to reload everything.

Reusing a PreparedStatement multiple times

The loop in your code is only an over-simplified example, right?

It would be better to create the PreparedStatement only once, and re-use it over and over again in the loop.

In situations where that is not possible (because it complicated the program flow too much), it is still beneficial to use a PreparedStatement, even if you use it only once, because the server-side of the work (parsing the SQL and caching the execution plan), will still be reduced.

To address the situation that you want to re-use the Java-side PreparedStatement, some JDBC drivers (such as Oracle) have a caching feature: If you create a PreparedStatement for the same SQL on the same connection, it will give you the same (cached) instance.

About multi-threading: I do not think JDBC connections can be shared across multiple threads (i.e. used concurrently by multiple threads) anyway. Every thread should get his own connection from the pool, use it, and return it to the pool again.

How do I remedy "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning?

I've done the clean and rebuild thing. That didn't work (it usually does). Now, I am attaching to w3wp before calling through the service, then let it call the service once, hit another breakpoint, then I change the point of execution so that it will run the same line (calling the service) again, then it actually stops at my breakpoint inside the service method.

SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session

I know it is an old question but i faced this error today.

and i found that, this error can be thrown when a database table trigger gets an error.

for your information, you can check your tables triggers too when you get this error.

How to delete mysql database through shell command

You can remove database directly as:

$ mysqladmin -h [host] -u [user] -p drop [database_name]

[Enter Password]

Do you really want to drop the 'hairfree' database [y/N]: y

.NET code to send ZPL to Zebra printers

The simplest solution is with copying files to shared printer.
Example in C#:

System.IO.File.Copy(inputFilePath, printerPath);

where:

  • inputFilePath - path to ZPL file (special extension is not required);
  • printerPath - path to shared(!) printer, for example: \127.0.0.1\zebraGX

How do I find the PublicKeyToken for a particular dll?

Using sn.exe utility:

sn -T YourAssembly.dll

or loading the assembly in Reflector.

'Must Override a Superclass Method' Errors after importing a project into Eclipse

The answer by Paul worked for me partially. I still had one error then. So, in addition to that, I also had to go to Properties-> Project Facets and there set the Java version from 1.5 to 1.6.

Maybe that helps.

Strange problem with Subversion - "File already exists" when trying to recreate a directory that USED to be in my repository

I ran into this problem today when Xcode crashed during a branch merge. Somehow the file was uploaded to the svn repository but it wasn't recorded in the svn db properly. I ran the following commands in the directory where the file existed locally:

svn revert bad.file
svn del svn://my.svnserver.com/svnDB/path/to/the/offending/file/bad.file

Then I re-added the file from my local system:

svn add bad.file
svn commit -m "Re adding bad.file"

Success!

Alter user defined type in SQL Server

1.Rename the old UDT,
2.Execute query , 3.Drop the old UDT.

CSS Layout - Dynamic width DIV

Or, if you know the width of the two "side" images and don't want to deal with floats:

<div class="container">
    <div class="left-panel"><img src="myleftimage" /></div>
    <div class="center-panel">Content goes here...</div>
    <div class="right-panel"><img src="myrightimage" /></div>
</div>

CSS:

.container {
    position:relative;
    padding-left:50px;
    padding-right:50px;
}

.container .left-panel {
    width: 50px;
    position:absolute;
    left:0px;
    top:0px;
}

.container .right-panel {
    width: 50px;
    position:absolute;
    right:0px;
    top:0px;
}

.container .center-panel {
    background: url('mymiddleimage');
}

Notes:

Position:relative on the parent div is used to make absolutely positioned children position themselves relative to that node.

Renew Provisioning Profile

For me the problem was occurring because there was no active Production certificate. I created a new one, and then went to the expired distribution provisioning profile, added the certificate and the provisioning profile got activated.

Delete all rows in table

As other have said, TRUNCATE TABLE is far quicker, but it does have some restrictions (taken from here):

You cannot use TRUNCATE TABLE on tables that:

- Are referenced by a FOREIGN KEY constraint. (You can truncate a table that has a foreign key that references itself.)
- Participate in an indexed view.
- Are published by using transactional replication or merge replication.

For tables with one or more of these characteristics, use the DELETE statement instead.

The biggest drawback is that if the table you are trying to empty has foreign keys pointing to it, then the truncate call will fail.

Recreate the default website in IIS

I suppose you want to publish and access your applications/websites from LAN; probably as virtual directories under the default website.The steps could vary depending on your IIS version, but basically it comes down to these steps:

Restore your "Default Website" Website :

  1. create a new website

  2. set "Default Website" as its name

  3. In the Binding section (bottom panel), enter your local IP address in the "IP Address" edit.

  4. Keep the "Host" edit empty

that's it: now whenever you type your local ip address in your browser, you will get the website you just added. Now if you want to access any of your other webapplications/websites from LAN, just add a virtual application under your default website pointing to the directory containing your published application/website. Now you can type : http://yourLocalIPAddress/theNameOfYourApplication to access it from your LAN.

Ship an application with a database

From what I've seen you should be be shipping a database that already has the tables setup and data. However if you want (and depending on the type of application you have) you can allow "upgrade database option". Then what you do is download the latest sqlite version, get the latest Insert/Create statements of a textfile hosted online, execute the statements and do a data transfer from the old db to the new one.

How do you migrate an IIS 7 site to another server?

MSDeploy can migrate all content, config, etc. that is what the IIS team recommends. http://www.iis.net/extensions/WebDeploymentTool

To create a package, run the following command (replace Default Web Site with your web site name):

msdeploy.exe -verb:sync -source:apphostconfig="Default Web Site" -dest:package=c:\dws.zip > DWSpackage7.log

To restore the package, run the following command:

msdeploy.exe -verb:sync -source:package=c:\dws.zip -dest:apphostconfig="Default Web Site" > DWSpackage7.log

DBCC CHECKIDENT Sets Identity to 0

Borrowing from Zyphrax's answer ...

USE DatabaseName

DECLARE @ReseedBit BIT = 
    COALESCE((SELECT SUM(CONVERT(BIGINT, ic.last_value))
                FROM sys.identity_columns ic
                INNER JOIN sys.tables t ON ic.object_id = t.object_id), 0)
DECLARE @Reseed INT = 
CASE 
    WHEN @ReseedBit = 0 THEN 1 
    WHEN @ReseedBit = 1 THEN 0 
END

DBCC CHECKIDENT ('dbo.table_name', RESEED, @Reseed);

Caveats: This is intended for use in reference data population situations where a DB is being initialized with enum type definition tables, where the ID values in those tables must always start at 1. The first time the DB is being created (e.g. during SSDT-DB publishing) @Reseed must be 0, but when resetting the data i.e. removing the data and re-inserting it, then @Reseed must be 1. So this code is intended for use in a stored procedure for resetting the DB data, which can be called manually but is also called from the post-deployment script in the SSDT-DB project. In that way the reference data inserts are only defined in one place but aren't restricted to be used only in post-deployment during publishing, they are also available for subsequent use (to support dev and automated test etc.) by calling the stored procedure to reset the DB back to a known good state.

Python object.__repr__(self) should be an expression?

>>> from datetime import date
>>>
>>> repr(date.today())        # calls date.today().__repr__()
'datetime.date(2009, 1, 16)'
>>> eval(_)                   # _ is the output of the last command
datetime.date(2009, 1, 16)

The output is a string that can be parsed by the python interpreter and results in an equal object.

If that's not possible, it should return a string in the form of <...some useful description...>.

SQL Server: Query fast, but slow from procedure

I had the same problem as the original poster but the quoted answer did not solve the problem for me. The query still ran really slow from a stored procedure.

I found another answer here "Parameter Sniffing", Thanks Omnibuzz. Boils down to using "local Variables" in your stored procedure queries, but read the original for more understanding, it's a great write up. e.g.

Slow way:

CREATE PROCEDURE GetOrderForCustomers(@CustID varchar(20))
AS
BEGIN
    SELECT * 
    FROM orders
    WHERE customerid = @CustID
END

Fast way:

CREATE PROCEDURE GetOrderForCustomersWithoutPS(@CustID varchar(20))
AS
BEGIN
    DECLARE @LocCustID varchar(20)
    SET @LocCustID = @CustID

    SELECT * 
    FROM orders
    WHERE customerid = @LocCustID
END

Hope this helps somebody else, doing this reduced my execution time from 5+ minutes to about 6-7 seconds.

How do I add an existing directory tree to a project in Visual Studio?

In Visual Studio 2015, this is how you do it.

If you want to automatically include all descendant files below a specific folder:

<Content Include="Path\To\Folder\**" />

This can be restricted to include only files within the path specified:

<Content Include="Path\To\Folder\*.*" />

Or even only files with a specified extension:

<Content Include="Path\To\Folder\*.jpg" >

Cannot truncate table because it is being referenced by a FOREIGN KEY constraint?

Correct; you cannot truncate a table which has an FK constraint on it.

Typically my process for this is:

  1. Drop the constraints
  2. Trunc the table
  3. Recreate the constraints.

(All in a transaction, of course.)

Of course, this only applies if the child has already been truncated. Otherwise I go a different route, dependent entirely on what my data looks like. (Too many variables to get into here.)

The original poster determined WHY this is the case; see this answer for more details.

How do I modify a MySQL column to allow NULL?

Your syntax error is caused by a missing "table" in the query

ALTER TABLE mytable MODIFY mycolumn varchar(255) null;

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

function getURL(url){
    return $.ajax({
        type: "GET",
        url: url,
        cache: false,
        async: false
    }).responseText;
}


//example use
var msg=getURL("message.php");
alert(msg);

Cannot access a disposed object - How to fix?

Try checking the IsDisposed property before accessing the control. You can also check it on the FormClosing event, assuming you're using the FormClosed event.

We do stop the Timer on the FormClosing event and we do check the IsDisposed property on the schedule component before using it in the Timer Tick event but it doesn't help.

Calling GC.Collect before checking IsDisposed may help, but be careful with this. Read this article by Rico Mariani "When to call GC.Collect()".

What is the difference between Cloud Computing and Grid Computing?

There are a lot of good answers to this question already but another way to take a look at it is the cloud (ala Amazon's AWS) is good for interactive use cases and the grid (ala High Performance Computing) is good for batch use cases.

Cloud is interactive in that you can get resources on demand via self service. The code you run on VMs in the cloud, such as the Apache web server, can server clients interactively.

Grid is batch in that you submit jobs to a job queue after obtaining the credentials from some HPC authority to do so. The code you run on the grid waits in that queue until there are sufficient resources to execute it.

There are good use cases for both styles of computing.

Confirm button before running deleting routine from website

Call this function onclick of button

/*pass whatever you want instead of id */
function doConfirm(id) {
    var ok = confirm("Are you sure to Delete?");
    if (ok) {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                window.location = "create_dealer.php";
            }
        }

        xmlhttp.open("GET", "delete_dealer.php?id=" + id);
        // file name where delete code is written
        xmlhttp.send();
    }
}

How to timeout a thread

I created a helper class just for this some time ago. Works great:

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
/**
 * TimeOut class - used for stopping a thread that is taking too long
 * @author Peter Goransson
 *
 */
public class TimeOut {

    Thread interrupter;
    Thread target;
    long timeout;
    boolean success;
    boolean forceStop;

    CyclicBarrier barrier;

    /**
     * 
     * @param target The Runnable target to be executed
     * @param timeout The time in milliseconds before target will be interrupted or stopped
     * @param forceStop If true, will Thread.stop() this target instead of just interrupt() 
     */
    public TimeOut(Runnable target, long timeout, boolean forceStop) {      
        this.timeout = timeout;
        this.forceStop = forceStop;

        this.target = new Thread(target);       
        this.interrupter = new Thread(new Interrupter());

        barrier = new CyclicBarrier(2); // There will always be just 2 threads waiting on this barrier
    }

    public boolean execute() throws InterruptedException {  

        // Start target and interrupter
        target.start();
        interrupter.start();

        // Wait for target to finish or be interrupted by interrupter
        target.join();  

        interrupter.interrupt(); // stop the interrupter    
        try {
            barrier.await(); // Need to wait on this barrier to make sure status is set
        } catch (BrokenBarrierException e) {
            // Something horrible happened, assume we failed
            success = false;
        } 

        return success; // status is set in the Interrupter inner class
    }

    private class Interrupter implements Runnable {

        Interrupter() {}

        public void run() {
            try {
                Thread.sleep(timeout); // Wait for timeout period and then kill this target
                if (forceStop) {
                  target.stop(); // Need to use stop instead of interrupt since we're trying to kill this thread
                }
                else {
                    target.interrupt(); // Gracefully interrupt the waiting thread
                }
                System.out.println("done");             
                success = false;
            } catch (InterruptedException e) {
                success = true;
            }


            try {
                barrier.await(); // Need to wait on this barrier
            } catch (InterruptedException e) {
                // If the Child and Interrupter finish at the exact same millisecond we'll get here
                // In this weird case assume it failed
                success = false;                
            } 
            catch (BrokenBarrierException e) {
                // Something horrible happened, assume we failed
                success = false;
            }

        }

    }
}

It is called like this:

long timeout = 10000; // number of milliseconds before timeout
TimeOut t = new TimeOut(new PhotoProcessor(filePath, params), timeout, true);
try {                       
  boolean sucess = t.execute(); // Will return false if this times out
  if (!sucess) {
    // This thread timed out
  }
  else {
    // This thread ran completely and did not timeout
  }
} catch (InterruptedException e) {}  

How to read a .xlsx file using the pandas Library in iPython?

The following worked for me:

from pandas import read_excel
my_sheet = 'Sheet1' # change it to your sheet name, you can find your sheet name at the bottom left of your excel file
file_name = 'products_and_categories.xlsx' # change it to the name of your excel file
df = read_excel(file_name, sheet_name = my_sheet)
print(df.head()) # shows headers with top 5 rows

How to rename a directory/folder on GitHub website?

If you have GitHub Desktop, change the names of the directories on your computer and then push the update from your desktop to your github account and it changes them there. :)

Hope it helps!

Angular - "has no exported member 'Observable'"

Just remove /Observable from 'rxjs/Observable';

If you then get Cannot find module 'rxjs-compat/Observable' just put below line to thr terminal and press enter.

npm install --save rxjs-compat

Why won't eclipse switch the compiler to Java 8?

Old question, but posting the answer incase it helps someone. Already build path was configured to use JDK 1.2.81 However, build was failing with the error below:

 lambda expressions are not supported in -source 1.5
[ERROR]   (use -source 8 or higher to enable lambda expressions)

In the latest Eclipse (Photon), adding the below entry to pom.xml worked.

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
  </properties>

How can I turn a DataTable to a CSV?

Here is my solution, based on previous answers by Paul Grimshaw and Anthony VO. I've submitted the code in a C# project on Github.

My main contribution is to eliminate explicitly creating and manipulating a StringBuilder and instead working only with IEnumerable. This avoids the allocation of a big buffer in memory.

public static class Util
{
    public static string EscapeQuotes(this string self) {
        return self?.Replace("\"", "\"\"") ?? "";
    }

    public static string Surround(this string self, string before, string after) {
        return $"{before}{self}{after}";
    }

    public static string Quoted(this string self, string quotes = "\"") {
        return self.Surround(quotes, quotes);
    }

    public static string QuotedCSVFieldIfNecessary(this string self) {
        return (self == null) ? "" : self.Contains('"') ? self.Quoted() : self; 
    }

    public static string ToCsvField(this string self) {
        return self.EscapeQuotes().QuotedCSVFieldIfNecessary();
    }

    public static string ToCsvRow(this IEnumerable<string> self){
        return string.Join(",", self.Select(ToCsvField));
    }

    public static IEnumerable<string> ToCsvRows(this DataTable self) {          
        yield return self.Columns.OfType<object>().Select(c => c.ToString()).ToCsvRow();
        foreach (var dr in self.Rows.OfType<DataRow>())
            yield return dr.ItemArray.Select(item => item.ToString()).ToCsvRow();
    }

    public static void ToCsvFile(this DataTable self, string path) {
        File.WriteAllLines(path, self.ToCsvRows());
    }
}

This approach combines nicely with converting IEnumerable to DataTable as asked here.

How to type ":" ("colon") in regexp?

In most regex implementations (including Java's), : has no special meaning, neither inside nor outside a character class.

Your problem is most likely due to the fact the - acts as a range operator in your class:

[A-Za-z0-9.,-:]*

where ,-: matches all ascii characters between ',' and ':'. Note that it still matches the literal ':' however!

Try this instead:

[A-Za-z0-9.,:-]*

By placing - at the start or the end of the class, it matches the literal "-". As mentioned in the comments by Keoki Zee, you can also escape the - inside the class, but most people simply add it at the end.

A demo:

public class Test {
    public static void main(String[] args) {
        System.out.println("8:".matches("[,-:]+"));      // true: '8' is in the range ','..':'
        System.out.println("8:".matches("[,:-]+"));      // false: '8' does not match ',' or ':' or '-'
        System.out.println(",,-,:,:".matches("[,:-]+")); // true: all chars match ',' or ':' or '-'
    }
}

The type arguments for method cannot be inferred from the usage

I received this error because I had made a mistake in the definition of my method. I had declared the method to accept a generic type (notice the "T" after the method name):

protected int InsertRecord<T>(CoasterModel model, IDbConnection con)

However, when I called the method, I did not use the type which, in my case, was the correct usage:

int count = InsertRecord(databaseToMigrateFrom, con);

I just removed the generic casting and it worked.

Darken background image on hover

Just try this code.

img:hover
{
    box-shadow: 0 25px 50px -25px rgba(0, 0, 0, .5) inset; 
    -webkit-box-shadow: 0 25px 50px -25px rgba(0, 0, 0, .5) inset; 
    -moz-box-shadow: 0 25px 50px -25px rgba(0, 0, 0, .5) inset; 
    -o-box-shadow: 0 25px 50px -25px rgba(0, 0, 0, .5) inset;
}

What do the crossed style properties in Google Chrome devtools mean?

When a CSS property shows as struck-through, it means that the crossed-out style was applied, but then overridden by a more specific selector, a more local rule, or by a later property within the same rule.

(Special cases: a style will also be shown as struck-through if a style exists in an matching rule but is commented out, or if you've manually disabled it by unchecking it within the Chrome developer tools. It will also show as crossed out, but with an error icon, if the style has a syntax error.)

For example, if a background color was applied to all divs, but a different background color was applied to divs with a certain id, the first color will show up but will be crossed out, as the second color has replaced it (in the property list for the div with that id).

I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely

Hello React Developers,

Instead of doing this disableHostCheck: true, in webpackDevServer.config.js. You can easily solve 'invalid host headers' error by adding a .env file to you project, add the variables HOST=0.0.0.0 and DANGEROUSLY_DISABLE_HOST_CHECK=true in .env file. If you want to make changes in webpackDevServer.config.js, you need to extract the react-scripts by using 'npm run eject' which is not recommended to do it. So the better solution is adding above mentioned variables in .env file of your project.

Happy Coding :)

The module ".dll" was loaded but the entry-point was not found

I found the answer: I need to add a new application to the service components in my computer and then add the right DLL's.

Thanks! If anyone has the same problem, I'll be happy to help.

Php - Your PHP installation appears to be missing the MySQL extension which is required by WordPress

It maybe the reason The php mysql api is deprecated. if your using below < PHP5.5 just update in your server to 5.6 and above.

How to remove an element from an array in Swift

Swift 5: Here is a cool and easy extension to remove elements in an array, without filtering :

   extension Array where Element: Equatable {

    // Remove first collection element that is equal to the given `object`:
    mutating func remove(object: Element) {
        guard let index = firstIndex(of: object) else {return}
        remove(at: index)
    }

}

Usage :

var myArray = ["cat", "barbecue", "pancake", "frog"]
let objectToRemove = "cat"

myArray.remove(object: objectToRemove) // ["barbecue", "pancake", "frog"]

Also works with other types, such as Int since Element is a generic type:

var myArray = [4, 8, 17, 6, 2]
let objectToRemove = 17

myArray.remove(object: objectToRemove) // [4, 8, 6, 2]

OTP (token) should be automatically read from the message

Sorry for late reply but still felt like posting my answer if it helps.It works for 6 digits OTP.

    @Override
    public void onOTPReceived(String messageBody)
    {
        Pattern pattern = Pattern.compile(SMSReceiver.OTP_REGEX);
        Matcher matcher = pattern.matcher(messageBody);
        String otp = HkpConstants.EMPTY;
        while (matcher.find())
        {
            otp = matcher.group();
        }
        checkAndSetOTP(otp);
    }
Adding constants here

public static final String OTP_REGEX = "[0-9]{1,6}";

For SMS listener one can follow the below class

public class SMSReceiver extends BroadcastReceiver
{
    public static final String SMS_BUNDLE = "pdus";
    public static final String OTP_REGEX = "[0-9]{1,6}";
    private static final String FORMAT = "format";

    private OnOTPSMSReceivedListener otpSMSListener;

    public SMSReceiver(OnOTPSMSReceivedListener listener)
    {
        otpSMSListener = listener;
    }

    @Override
    public void onReceive(Context context, Intent intent)
    {
        Bundle intentExtras = intent.getExtras();
        if (intentExtras != null)
        {
            Object[] sms_bundle = (Object[]) intentExtras.get(SMS_BUNDLE);
            String format = intent.getStringExtra(FORMAT);
            if (sms_bundle != null)
            {
                otpSMSListener.onOTPSMSReceived(format, sms_bundle);
            }
            else {
                // do nothing
            }
        }
    }

    @FunctionalInterface
    public interface OnOTPSMSReceivedListener
    {
        void onOTPSMSReceived(@Nullable String format, Object... smsBundle);
    }
}

    @Override
    public void onOTPSMSReceived(@Nullable String format, Object... smsBundle)
    {
        for (Object aSmsBundle : smsBundle)
        {
            SmsMessage smsMessage = getIncomingMessage(format, aSmsBundle);
            String sender = smsMessage.getDisplayOriginatingAddress();
            if (sender.toLowerCase().contains(ONEMG))
            {
                getIncomingMessage(smsMessage.getMessageBody());
            } else
            {
                // do nothing
            }
        }
    }

    private SmsMessage getIncomingMessage(@Nullable String format, Object aObject)
    {
        SmsMessage currentSMS;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && format != null)
        {
            currentSMS = SmsMessage.createFromPdu((byte[]) aObject, format);
        } else
        {
            currentSMS = SmsMessage.createFromPdu((byte[]) aObject);
        }

        return currentSMS;
    }

Is System.nanoTime() completely useless?

Absolutely not useless. Timing aficionados correctly point out the multi-core problem, but in real-word applications it is often radically better than currentTimeMillis().

When calculating graphics positions in frame refreshes nanoTime() leads to MUCH smoother motion in my program.

And I only test on multi-core machines.

Overriding interface property type defined in Typescript d.ts file

I have created this type that allows me to easily override nested interfaces:

export type DeepPartialAny<T> = {
  [P in keyof T]?: T[P] extends Obj ? DeepPartialAny<T[P]> : any;
};

export type Override<A extends Obj, AOverride extends DeepPartialAny<A>> = { [K in keyof A]:
  AOverride[K] extends never
    ? A[K]
    : AOverride[K] extends Obj
    ? Override<A[K], AOverride[K]>
    : AOverride[K]
};

And then you can use it like that:

interface Foo {
  Bar: {
    Baz: string;
  };
}
type Foo2 = Override<Foo, { Bar: { Baz: number } }>;

const bar: Foo2['Bar']['Baz'] = 1; // number;

ie8 var w= window.open() - "Message: Invalid argument."

Actually a name can be used however it cannot have spaces so window.open("../myPage","MyWindows",...) should work with no problem (window.open).

How to detect if a browser is Chrome using jQuery?

var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase() );

How can I get the baseurl of site?

This works for me.

Request.Url.OriginalString.Replace(Request.Url.PathAndQuery, "") + Request.ApplicationPath;
  • Request.Url.OriginalString: return the complete path same as browser showing.
  • Request.Url.PathAndQuery: return the (complete path) - (domain name + PORT).
  • Request.ApplicationPath: return "/" on hosted server and "application name" on local IIS deploy.

So if you want to access your domain name do consider to include the application name in case of:

  1. IIS deployment
  2. If your application deployed on the sub-domain.

====================================

For the dev.x.us/web

it return this strong text

TypeLoadException says 'no implementation', but it is implemented

The other time you can get this error is if you have an incorrect version of a signed assembly. It's not the normal symptom for this cause, but here was the scenario where I got it

  • an asp.net project contains assembly A and assembly B, B is strongly named

  • assembly A uses Activator.CreateInstance to load assembly C (i.e. there is no reference to C which is built separately)

  • C was built referencing an older version of assembly B than is currently present

hope that helps someone - it took me ages to figure this out.

css transition opacity fade background

Wrap your image with a span element with a black background.

_x000D_
_x000D_
.img-wrapper {
  display: inline-block;
  background: #000;
}

.item-fade {
  vertical-align: top;
  transition: opacity 0.3s;
  -webkit-transition: opacity 0.3s;
  opacity: 1;
}

.item-fade:hover {
  opacity: 0.2;
}
_x000D_
<span class="img-wrapper">
   <img class="item-fade" src="http://placehold.it/100x100/cf5" />
</span>
_x000D_
_x000D_
_x000D_

Excel formula to search if all cells in a range read "True", if not, then show "False"

As it appears you have the values as text, and not the numeric True/False, then you can use either COUNTIF or SUMPRODUCT

=IF(SUMPRODUCT(--(A2:D2="False")),"False","True")
=IF(COUNTIF(A3:D3,"False*"),"False","True")

How to get streaming url from online streaming radio station

Edited ZygD's answer for python 3.x.:

import re
import urllib.request
import string
url1 = input("Please enter a URL from Tunein Radio: ");
request = urllib.request.Request(url1);
response = urllib.request.urlopen(request);
raw_file = response.read().decode('utf-8');
API_key = re.findall(r"StreamUrl\":\"(.*?),\"",raw_file);
#print API_key;
#print "The API key is: " + API_key[0];
request2 = urllib.request.Request(str(API_key[0]));
response2 = urllib.request.urlopen(request2);
key_content = response2.read().decode('utf-8');
raw_stream_url = re.findall(r"Url\": \"(.*?)\"",key_content);
bandwidth = re.findall(r"Bandwidth\":(.*?),", key_content);
reliability = re.findall(r"lity\":(.*?),", key_content);
isPlaylist = re.findall(r"HasPlaylist\":(.*?),",key_content);
codec = re.findall(r"MediaType\": \"(.*?)\",", key_content);
tipe = re.findall(r"Type\": \"(.*?)\"", key_content);
total = 0
for element in raw_stream_url:
    total = total + 1
i = 0
print ("I found " + str(total) + " streams.");
for element in raw_stream_url:
    print ("Stream #" + str(i + 1));
    print ("Stream stats:");
    print ("Bandwidth: " + str(bandwidth[i]) + " kilobytes per second.");
    print ("Reliability: " + str(reliability[i]) + "%");
    print ("HasPlaylist: " + str(isPlaylist[i]));
    print ("Stream codec: " + str(codec[i]));
    print ("This audio stream is " + tipe[i].lower());
    print ("Pure streaming URL: " + str(raw_stream_url[i]));
i = i + 1
input("Press enter to close")

How should I do integer division in Perl?

you can:

use integer;

it is explained by Michael Ratanapintha or else use manually:

$a=3.7;
$b=2.1;

$c=int(int($a)/int($b));

notice, 'int' is not casting. this is function for converting number to integer form. this is because Perl 5 does not have separate integer division. exception is when you 'use integer'. Then you will lose real division.

Doing a cleanup action just before Node.js exits

After playing around with other answer, here is my solution for this task. Implementing this way helps me centralize cleanup in one place, preventing double handling the cleanup.

  1. I would like to route all other exiting codes to 'exit' code.
const others = [`SIGINT`, `SIGUSR1`, `SIGUSR2`, `uncaughtException`, `SIGTERM`]
others.forEach((eventType) => {
    process.on(eventType, exitRouter.bind(null, { exit: true }));
})
  1. What the exitRouter does is calling process.exit()
function exitRouter(options, exitCode) {
   if (exitCode || exitCode === 0) console.log(`ExitCode ${exitCode}`);
   if (options.exit) process.exit();
}
  1. On 'exit', handle the clean up with a new function
function exitHandler(exitCode) {
  console.log(`ExitCode ${exitCode}`);
  console.log('Exiting finally...')
}

process.on('exit', exitHandler)

For the demo purpose, this is link to my gist. In the file, i add a setTimeout to fake the process running.

If you run node node-exit-demo.js and do nothing, then after 2 seconds, you see the log:

The service is finish after a while.
ExitCode 0
Exiting finally...

Else if before the service finish, you terminate by ctrl+C, you'll see:

^CExitCode SIGINT
ExitCode 0
Exiting finally...

What happened is the Node process exited initially with code SIGINT, then it routes to process.exit() and finally exited with exit code 0.

PHP/MySQL insert row then get 'id'

The MySQL function LAST_INSERT_ID() does just what you need: it retrieves the id that was inserted during this session. So it is safe to use, even if there are other processes (other people calling the exact same script, for example) inserting values into the same table.

The PHP function mysql_insert_id() does the same as calling SELECT LAST_INSERT_ID() with mysql_query().

Exception.Message vs Exception.ToString()

In addition to what's already been said, don't use ToString() on the exception object for displaying to the user. Just the Message property should suffice, or a higher level custom message.

In terms of logging purposes, definitely use ToString() on the Exception, not just the Message property, as in most scenarios, you will be left scratching your head where specifically this exception occurred, and what the call stack was. The stacktrace would have told you all that.

IIS sc-win32-status codes

Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx

You can also use command line utility net to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code

Mock functions in Go

Considering unit test is the domain of this question, highly recommend you to use monkey. This Package make you to mock test without changing your original source code. Compare to other answer, it's more "non-intrusive".

main

type AA struct {
 //...
}
func (a *AA) OriginalFunc() {
//...
}

mock test

var a *AA

func NewFunc(a *AA) {
 //...
}

monkey.PatchMethod(reflect.TypeOf(a), "OriginalFunc", NewFunc)

Bad side is:

  • Reminded by Dave.C, This method is unsafe. So don't use it outside of unit test.
  • Is non-idiomatic Go.

Good side is:

  • Is non-intrusive. Make you do things without changing the main code. Like Thomas said.
  • Make you change behavior of package (maybe provided by third party) with least code.

JavaScript: How to pass object by value?

Check out this answer https://stackoverflow.com/a/5344074/746491 .

In short, JSON.parse(JSON.stringify(obj)) is a fast way to copy your objects, if your objects can be serialized to json.

How to change font size in Eclipse for Java text editors?

Running Eclipse v4.3 (Kepler), the steps outlined by AlvaroCachoperro do the trick for the Java text editor and console window text.

Many of the text font options, including the Java Editor Text Font note, are "set to default: Text Font". The 'default' can be found and configured as follows:

On the Eclipse toolbar, select Window ? Preferences. Drill down to: (General ? Appearance ? Colors and Fonts ? Basic ? Text Font) (at the bottom)

  • Click Edit and select the font, style and size
  • Click OK in the Font dialog
  • Click Apply in the Preferences dialog to check it
  • Click OK in the Preferences dialog to save it

Eclipse will remember your settings for your current workspace.

I teach programming and use the larger font for the students in the back.

Angular ng-class if else

Both John Conde's and ryeballar's answers are correct and will work.

If you want to get too geeky:

  • John's has the downside that it has to make two decisions per $digest loop (it has to decide whether to add/remove center and it has to decide whether to add/remove left), when clearly only one is needed.

  • Ryeballar's relies on the ternary operator which is probably going to be removed at some point (because the view should not contain any logic). (We can't be sure it will indeed be removed and it probably won't be any time soon, but if there is a more "safe" solution, why not ?)


So, you can do the following as an alternative:

ng-class="{true:'center',false:'left'}[page.isSelected(1)]"

How do you access the matched groups in a JavaScript regular expression?

Here’s a method you can use to get the n?th capturing group for each match:

_x000D_
_x000D_
function getMatches(string, regex, index) {_x000D_
  index || (index = 1); // default to the first capturing group_x000D_
  var matches = [];_x000D_
  var match;_x000D_
  while (match = regex.exec(string)) {_x000D_
    matches.push(match[index]);_x000D_
  }_x000D_
  return matches;_x000D_
}_x000D_
_x000D_
_x000D_
// Example :_x000D_
var myString = 'something format_abc something format_def something format_ghi';_x000D_
var myRegEx = /(?:^|\s)format_(.*?)(?:\s|$)/g;_x000D_
_x000D_
// Get an array containing the first capturing group for every match_x000D_
var matches = getMatches(myString, myRegEx, 1);_x000D_
_x000D_
// Log results_x000D_
document.write(matches.length + ' matches found: ' + JSON.stringify(matches))_x000D_
console.log(matches);
_x000D_
_x000D_
_x000D_

MySQL TEXT vs BLOB vs CLOB

TEXT is a data-type for text based input. On the other hand, you have BLOB and CLOB which are more suitable for data storage (images, etc) due to their larger capacity limits (4GB for example).

As for the difference between BLOB and CLOB, I believe CLOB has character encoding associated with it, which implies it can be suited well for very large amounts of text.

BLOB and CLOB data can take a long time to retrieve, relative to how quick data from a TEXT field can be retrieved. So, use only what you need.

Write variable to file, including name

You can use pickle

import pickle
dict = {'one': 1, 'two': 2}
file = open('dump.txt', 'wb')
pickle.dump(dict, file)
file.close()

and to read it again

file = open('dump.txt', 'rb')
dict = pickle.load(file)

EDIT: Guess I misread your question, sorry ... but pickle might help all the same. :)

Base 64 encode and decode example code

For API level 26+

String encodedString = Base64.getEncoder().encodeToString(byteArray);

Ref: https://developer.android.com/reference/java/util/Base64.Encoder.html#encodeToString(byte[])

jQuery .get error response function?

You can chain .fail() callback for error response.

$.get('http://example.com/page/2/', function(data){ 
   $(data).find('#reviews .card').appendTo('#reviews');
})
.fail(function() {
  //Error logic
})

How to remove a newline from a string in Bash

You can simply use echo -n "|$COMMAND|".

Convert String to Calendar Object in Java

Parse a time with timezone, Z in pattern is for time zone

String aTime = "2017-10-25T11:39:00+09:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault());
try {
    Calendar cal = Calendar.getInstance();
    cal.setTime(sdf.parse(aTime));
    Log.i(TAG, "time = " + cal.getTimeInMillis()); 
} catch (ParseException e) {
    e.printStackTrace();
}

Output: it will return the UTC time

1508899140000

enter image description here

If we don't set the time zone in pattern like yyyy-MM-dd'T'HH:mm:ss. SimpleDateFormat will use the time zone which have set in Setting

Checking session if empty or not

If It is simple Session you can apply NULL Check directly Session["emp_num"] != null

But if it's a session of a list Item then You need to apply any one of the following option

Option 1:

if (((List<int>)(Session["emp_num"])) != null && (List<int>)Session["emp_num"])).Count > 0)
 {
 //Your Logic here
 }

Option 2:

List<int> val= Session["emp_num"] as List<int>;  //Get the value from Session.

if (val.FirstOrDefault() != null)
 {
 //Your Logic here
 }

What is resource-ref in web.xml used for?

You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.

<resource-ref> introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.

So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB name. The container finds that web.xml has a <resource-ref> element for jdbc/primaryDB, so it will look into the container-specific configuration, that contains something similar to the following:

<resource-ref>
  <res-ref-name>jdbc/primaryDB</res-ref-name>
  <jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>

Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer.

The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.

MySQL WHERE IN ()

you must have record in table or array record in database.

example:

SELECT * FROM tabel_record
WHERE table_record.fieldName IN (SELECT fieldName FROM table_reference);

Valid to use <a> (anchor tag) without href attribute?

It is valid. You can, for example, use it to show modals (or similar things that respond to data-toggle and data-target attributes).

Something like:

<a role="button" data-toggle="modal" data-target=".bs-example-modal-sm" aria-hidden="true"><i class="fa fa-phone"></i></a>

Here I use the font-awesome icon, which is better as a a tag rather than a button, to show a modal. Also, setting role="button" makes the pointer change to an action type. Without either href or role="button", the cursor pointer does not change.

Entity Framework 5 Updating a Record

I really like the accepted answer. I believe there is yet another way to approach this as well. Let's say you have a very short list of properties that you wouldn't want to ever include in a View, so when updating the entity, those would be omitted. Let's say that those two fields are Password and SSN.

db.Users.Attach(updatedUser);

var entry = db.Entry(updatedUser);
entry.State = EntityState.Modified;

entry.Property(e => e.Password).IsModified = false;
entry.Property(e => e.SSN).IsModified = false;   

db.SaveChanges();   

This example allows you to essentially leave your business logic alone after adding a new field to your Users table and to your View.

GC overhead limit exceeded

From Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning

the following

Excessive GC Time and OutOfMemoryError

The concurrent collector will throw an OutOfMemoryError if too much time is being spent in garbage collection: if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, an OutOfMemoryError will be thrown. This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small. If necessary, this feature can be disabled by adding the option -XX:-UseGCOverheadLimit to the command line.

The policy is the same as that in the parallel collector, except that time spent performing concurrent collections is not counted toward the 98% time limit. In other words, only collections performed while the application is stopped count toward excessive GC time. Such collections are typically due to a concurrent mode failure or an explicit collection request (e.g., a call to System.gc()).

in conjunction with a passage further down

One of the most commonly encountered uses of explicit garbage collection occurs with RMIs distributed garbage collection (DGC). Applications using RMI refer to objects in other virtual machines. Garbage cannot be collected in these distributed applications without occasionally collection the local heap, so RMI forces full collections periodically. The frequency of these collections can be controlled with properties. For example,

java -Dsun.rmi.dgc.client.gcInterval=3600000

-Dsun.rmi.dgc.server.gcInterval=3600000 specifies explicit collection once per hour instead of the default rate of once per minute. However, this may also cause some objects to take much longer to be reclaimed. These properties can be set as high as Long.MAX_VALUE to make the time between explicit collections effectively infinite, if there is no desire for an upper bound on the timeliness of DGC activity.

Seems to imply that the evaluation period for determining the 98% is one minute long, but it might be configurable on Sun's JVM with the correct define.

Of course, other interpretations are possible.

C linked list inserting node at the end

This works fine:

struct node *addNode(node *head, int value) {
    node *newNode = (node *) malloc(sizeof(node));
    newNode->value = value;
    newNode->next = NULL;

    if (head == NULL) {
        // Add at the beginning
        head = newNode;
    } else {
        node *current = head;

        while (current->next != NULL) {
            current = current->next;
        };

        // Add at the end
        current->next = newNode;
    }

    return head;
}

Example usage:

struct node *head = NULL;

for (int currentIndex = 1; currentIndex < 10; currentIndex++) {
    head = addNode(head, currentIndex);
}

PHP Composer update "cannot allocate memory" error (using Laravel 4)

you can use the following to check your free (swap) memory

free -m

total used free shared buffers cached

Mem: 2048 357 1690 0 0 237
-/+ buffers/cache: 119 1928
Swap: 0 0 0

To enable the swap you can use for example:

/bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
/sbin/mkswap /var/swap.1
/sbin/swapon /var/swap.1

Decompile an APK, modify it and then recompile it

The answers are already kind of outdated or not complete. This maybe works for non-protected apks (no Proguard), but nowadays nobody deploys an unprotected apk. The way I was able to modify a (my) well-protected apk (Proguard, security check which checks for "hacking tools", security check, which checks if the app is repackaged with debug mode,...) is via apktool as already mentioned by other ones here. But nobody explained, that you have to sign the app again.

apktool d app.apk
//generates a folder with smali bytecode files. 

//Do something with it.

apktool b [folder name] -o modified.apk
//generates the modified apk.

//and then
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore ~/.android/debug.keystore modified.apk androiddebugkey
//signs the app the the debug key (the password is android)

//this apk can be installed on a device.

In my test, the original release apk had no logging. After I decompiled with apktool I exchanged a full byte code file without logging by a full byte code file with logging, re-compiled and signed it and I was able to install it on my device. Afterwards I was able to see the logs in Android Studio as I connected the app to it.

In my opinion, decompiling with dex2jar and JD-GUI is only helpful to get a better understanding what the classes are doing, just for reading purposes. But since everything is proguarded, I'm not sure that you can ever re-compile this half-baked Java code to a working apk. If so, please let me know. I think, the only way is to manipulate the byte code itself as mentioned in this example.

Jackson how to transform JsonNode to ArrayNode without casting?

Is there a method equivalent to getJSONArray in org.json so that I have proper error handling in case it isn't an array?

It depends on your input; i.e. the stuff you fetch from the URL. If the value of the "datasets" attribute is an associative array rather than a plain array, you will get a ClassCastException.

But then again, the correctness of your old version also depends on the input. In the situation where your new version throws a ClassCastException, the old version will throw JSONException. Reference: http://www.json.org/javadoc/org/json/JSONObject.html#getJSONArray(java.lang.String)

Shorten string without cutting words in JavaScript

Didn't find the voted solutions satisfactory. So I wrote something thats is kind of generic and works both first and last part of your text (something like substr but for words). Also you can set if you'd like the spaces to be left out in the char-count.

    function chopTxtMinMax(txt, firstChar, lastChar=0){
        var wordsArr = txt.split(" ");
        var newWordsArr = [];

        var totalIteratedChars = 0;
        var inclSpacesCount = true;

        for(var wordIndx in wordsArr){
            totalIteratedChars += wordsArr[wordIndx].length + (inclSpacesCount ? 1 : 0);
            if(totalIteratedChars >= firstChar && (totalIteratedChars <= lastChar || lastChar==0)){
                newWordsArr.push(wordsArr[wordIndx]);
            }
        }

        txt = newWordsArr.join(" ");
        return txt;
    }

Call and receive output from Python script in Java?

ProcessBuilder is very easy to use.

ProcessBuilder pb = new ProcessBuilder("python","Your python file",""+Command line arguments if any);
Process p = pb.start();

This should call python. Refer to the process approach here for full example!

https://bytes.com/topic/python/insights/949995-three-ways-run-python-programs-java

issue ORA-00001: unique constraint violated coming in INSERT/UPDATE

Oracle's error message should be somewhat longer. It usually looks like this:

ORA-00001: unique constraint (TABLE_UK1) violated

The name in parentheses is the constrait name. It tells you which constraint was violated.

Python, creating objects

class Student(object):
    name = ""
    age = 0
    major = ""

    # The class "constructor" - It's actually an initializer 
    def __init__(self, name, age, major):
        self.name = name
        self.age = age
        self.major = major

def make_student(name, age, major):
    student = Student(name, age, major)
    return student

Note that even though one of the principles in Python's philosophy is "there should be one—and preferably only one—obvious way to do it", there are still multiple ways to do this. You can also use the two following snippets of code to take advantage of Python's dynamic capabilities:

class Student(object):
    name = ""
    age = 0
    major = ""

def make_student(name, age, major):
    student = Student()
    student.name = name
    student.age = age
    student.major = major
    # Note: I didn't need to create a variable in the class definition before doing this.
    student.gpa = float(4.0)
    return student

I prefer the former, but there are instances where the latter can be useful – one being when working with document databases like MongoDB.

How can I kill whatever process is using port 8080 so that I can vagrant up?

In case above-accepted answer did not work, try below solution. You can use it for port 8080 or for any other ports.

sudo lsof -i tcp:3000 

Replace 3000 with whichever port you want. Run below command to kill that process.

sudo kill -9 PID

PID is process ID you want to kill.

Below is the output of commands on mac Terminal.

Command output

How to use aria-expanded="true" to change a css property

You could use querySelector() with attribute selector '[attribute="value"]', then affect css rule using .style, as you can see in the example below:

_x000D_
_x000D_
document.querySelector('a[aria-expanded="true"]').style.backgroundColor = "#42DCA3";
_x000D_
<ul><li class="active">_x000D_
  <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="true"> <span class="network-name">Google+ with aria expanded true</span></a>_x000D_
  </li>_x000D_
  <li>_x000D_
    <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="false"> <span class="network-name">Google+ with aria expanded false</span></a>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

jQuery solution :

If you want to use a jQuery solution you could simply use css() method :

$('a[aria-expanded="true"]').css('background-color','#42DCA3');

Hope this helps.

How to convert integer to string in C?

Use sprintf():

int someInt = 368;
char str[12];
sprintf(str, "%d", someInt);

All numbers that are representable by int will fit in a 12-char-array without overflow, unless your compiler is somehow using more than 32-bits for int. When using numbers with greater bitsize, e.g. long with most 64-bit compilers, you need to increase the array size—at least 21 characters for 64-bit types.

How to call gesture tap on UIView programmatically in swift

Swift 4

First, create an object of UITapGestureRecognizer

var tapGesture = UITapGestureRecognizer()

The second step is to initialise UITapGestureReconizer. Enable the user interaction, then add it.

override func viewDidLoad() {
        super.viewDidLoad()
    tapGesture = UITapGestureRecognizer(target: self, action: #selector(YourViewController.myviewTapped(_:)))
            infosView.isUserInteractionEnabled = true
            infosView.addGestureRecognizer(tapGesture)
view.addSubview(infosView)
}

Third, create a method

@objc func myviewTapped(_ recognizer: UIGestureRecognizer) {
                print("button is tapped")
            }

Access Database opens as read only

If someone else has the database open, then ask them to close it. If the database was not closed cleanly (Access or a computer crashed), then you can try to Compact and Repair the file.

I have also noticed that if the file is opened or put in a read-only state at any time, it might get 'stuck' like that. So try this:

  1. Open Access, but no database
  2. Open the file in question, but explicitly open it in read-only mode (the 'Open' button is actually a dropdown button. Use the button to open read-only
  3. Close the file (but not Access)
  4. Open the file again, but open normally.

Not sure it that's a bug or a feature, but I've seen it frustrate many a user.

Angular2 Material Dialog css, dialog size

I think you need to use /deep/, because your CSS may not see your modal class. For example, if you want to customize .modal-dialog

/deep/.modal-dialog {
  width: 75% !important;
}

But this code will modify all your modal-windows, better solution will be

:host {
  /deep/.modal-dialog {
  width: 75% !important;
  }
}

Change the color of a checked menu item in a navigation drawer

Step 1: Build a checked/unchecked selector:

selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/yellow" android:state_checked="true" />
    <item android:color="@color/white" android:state_checked="false" />
</selector>

Step 2: use the xml attribute app:itemTextColor within NavigationView widget for selecting the text color.

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    app:headerLayout="@layout/navigation_header_layout"
    app:itemTextColor="@drawable/selector"
    app:menu="@menu/navigation_menu" />

Step 3:
For some reason when you hit an item from the NavigationView menu, it doesn't consider this as a button check. So you need to manually get the selected item checked and clear the previously selected item. Use below listener to do that

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {

    int id = item.getItemId();

    // remove all colors of the items to the `unchecked` state of the selector
    removeColor(mNavigationView);

    // check the selected item to change its color set by the `checked` state of the selector
    item.setChecked(true);

    switch (item.getItemId()) {
      case R.id.dashboard:
          ...
    }

    drawerLayout.closeDrawer(GravityCompat.START);
    return true;
}

private void removeColor(NavigationView view) {
    for (int i = 0; i < view.getMenu().size(); i++) {
        MenuItem item = view.getMenu().getItem(i);
        item.setChecked(false);
    }
}

Step 4:
To change icon color, use the app:iconTint attribute in the NavigationView menu items, and set to the same selector.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/nav_account"
        android:checked="true"
        android:icon="@drawable/ic_person_black_24dp"
        android:title="My Account"
        app:iconTint="@drawable/selector" />
    <item
        android:id="@+id/nav_settings"
        android:icon="@drawable/ic_settings_black_24dp"
        android:title="Settings"
        app:iconTint="@drawable/selector" />

    <item
        android:id="@+id/nav_logout"
        android:icon="@drawable/logout"
        android:title="Log Out"
        app:iconTint="@drawable/selector" />
</menu>

Result:

javascript push multidimensional array

In JavaScript, the type of key/value store you are attempting to use is an object literal, rather than an array. You are mistakenly creating a composite array object, which happens to have other properties based on the key names you provided, but the array portion contains no elements.

Instead, declare valueToPush as an object and push that onto cookie_value_add:

// Create valueToPush as an object {} rather than an array []
var valueToPush = {};

// Add the properties to your object
// Note, you could also use the valueToPush["productID"] syntax you had
// above, but this is a more object-like syntax
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;

cookie_value_add.push(valueToPush);

// View the structure of cookie_value_add
console.dir(cookie_value_add);

Can I run Keras model on gpu?

2.0 Compatible Answer: While above mentioned answer explain in detail on how to use GPU on Keras Model, I want to explain how it can be done for Tensorflow Version 2.0.

To know how many GPUs are available, we can use the below code:

print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))

To find out which devices your operations and tensors are assigned to, put tf.debugging.set_log_device_placement(True) as the first statement of your program.

Enabling device placement logging causes any Tensor allocations or operations to be printed. For example, running the below code:

tf.debugging.set_log_device_placement(True)

# Create some tensors
a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
c = tf.matmul(a, b)

print(c)

gives the Output shown below:

Executing op MatMul in device /job:localhost/replica:0/task:0/device:GPU:0 tf.Tensor( [[22. 28.] [49. 64.]], shape=(2, 2), dtype=float32)

For more information, refer this link

Default nginx client_max_body_size

Pooja Mane's answer worked for me, but I had to put the client_max_body_size variable inside of http section.

enter image description here

Remove first Item of the array (like popping from stack)

Just use arr.slice(startingIndex, endingIndex).

If you do not specify the endingIndex, it returns all the items starting from the index provided.

In your case arr=arr.slice(1).

How to find a value in an array and remove it by using PHP array functions?

You can use array_filter to filter out elements of an array based on a callback function. The callback function takes each element of the array as an argument and you simply return false if that element should be removed. This also has the benefit of removing duplicate values since it scans the entire array.

You can use it like this:

$myArray = array('apple', 'orange', 'banana', 'plum', 'banana');
$output = array_filter($myArray, function($value) { return $value !== 'banana'; });
// content of $output after previous line:
// $output = array('apple', 'orange', 'plum');

And if you want to re-index the array, you can pass the result to array_values like this:

$output = array_values($output);

How to check View Source in Mobile Browsers (Both Android && Feature Phone)

This is an old post but still a problem within the Chrome dev tools. I find the best way to check mobile source locally is to open the site locally in Xcode's iOS Simulator. Then from there you open the Safari browser and enable dev tools, if you have not already done this (go to preferences -> advanced -> show develop menu in menu bar). Now you will see the develop option in the main menu and can go to develop -> iOS Simulator -> and the page you have open in Xcode's iOS Simulator will be there. Once you click on it, it will open the web inspector and you can edit as you would normally in the browser dev tools.

I'm afraid this solution will only work on a Mac though as it uses Xcode.

Why have header files and .cpp files?

Because the people who designed the library format didn't want to "waste" space for rarely used information like C preprocessor macros and function declarations.

Since you need that info to tell your compiler "this function is available later when the linker is doing its job", they had to come up with a second file where this shared information could be stored.

Most languages after C/C++ store this information in the output (Java bytecode, for example) or they don't use a precompiled format at all, get always distributed in source form and compile on the fly (Python, Perl).

PowerShell says "execution of scripts is disabled on this system."

I had a similar issue and noted that the default cmd on Windows Server 2012, was running the x64 one.

For Windows 7, Windows 8, Windows 10, Windows Server 2008 R2 or Windows Server 2012, run the following commands as Administrator:

x86 (32 bit)
Open C:\Windows\SysWOW64\cmd.exe
Run the command powershell Set-ExecutionPolicy RemoteSigned

x64 (64 bit)
Open C:\Windows\system32\cmd.exe
Run the command powershell Set-ExecutionPolicy RemoteSigned

You can check mode using

  • In CMD: echo %PROCESSOR_ARCHITECTURE%
  • In Powershell: [Environment]::Is64BitProcess

References:
MSDN - Windows PowerShell execution policies
Windows - 32bit vs 64bit directory explanation

Updating Anaconda fails: Environment Not Writable Error

Open this folder "C:\ProgramData\" and right-click on "\Anaconda3". go to properties -> security and check all the boxes for each user. This worked for me.

Randomize a List<T>

This is my preferred method of a shuffle when it's desirable to not modify the original. It's a variant of the Fisher–Yates "inside-out" algorithm that works on any enumerable sequence (the length of source does not need to be known from start).

public static IList<T> NextList<T>(this Random r, IEnumerable<T> source)
{
  var list = new List<T>();
  foreach (var item in source)
  {
    var i = r.Next(list.Count + 1);
    if (i == list.Count)
    {
      list.Add(item);
    }
    else
    {
      var temp = list[i];
      list[i] = item;
      list.Add(temp);
    }
  }
  return list;
}

This algorithm can also be implemented by allocating a range from 0 to length - 1 and randomly exhausting the indices by swapping the randomly chosen index with the last index until all indices have been chosen exactly once. This above code accomplishes the exact same thing but without the additional allocation. Which is pretty neat.

With regards to the Random class it's a general purpose number generator (and If I was running a lottery I'd consider using something different). It also relies on a time based seed value by default. A small alleviation of the problem is to seed the Random class with the RNGCryptoServiceProvider or you could use the RNGCryptoServiceProvider in a method similar to this (see below) to generate uniformly chosen random double floating point values but running a lottery pretty much requires understanding randomness and the nature of the randomness source.

var bytes = new byte[8];
_secureRng.GetBytes(bytes);
var v = BitConverter.ToUInt64(bytes, 0);
return (double)v / ((double)ulong.MaxValue + 1);

The point of generating a random double (between 0 and 1 exclusively) is to use to scale to an integer solution. If you need to pick something from a list based on a random double x that's always going to be 0 <= x && x < 1 is straight forward.

return list[(int)(x * list.Count)];

Enjoy!

Capitalize only first character of string and leave others alone? (Rails)

Most of these answers edit the string in place, when you are just formatting for view output you may not want to be changing the underlying string so you can use tap after a dup to get an edited copy

'test'.dup.tap { |string| string[0] = string[0].upcase }

linux execute command remotely

I guess ssh is the best secured way for this, for example :

ssh -OPTIONS -p SSH_PORT user@remote_server "remote_command1; remote_command2; remote_script.sh"  

where the OPTIONS have to be deployed according to your specific needs (for example, binding to ipv4 only) and your remote command could be starting your tomcat daemon.

Note:
If you do not want to be prompt at every ssh run, please also have a look to ssh-agent, and optionally to keychain if your system allows it. Key is... to understand the ssh keys exchange process. Please take a careful look to ssh_config (i.e. the ssh client config file) and sshd_config (i.e. the ssh server config file). Configuration filenames depend on your system, anyway you'll find them somewhere like /etc/sshd_config. Ideally, pls do not run ssh as root obviously but as a specific user on both sides, servers and client.

Some extra docs over the source project main pages :

ssh and ssh-agent
man ssh

http://www.snailbook.com/index.html
https://help.ubuntu.com/community/SSH/OpenSSH/Configuring

keychain
http://www.gentoo.org/doc/en/keychain-guide.xml
an older tuto in French (by myself :-) but might be useful too :
http://hornetbzz.developpez.com/tutoriels/debian/ssh/keychain/

When should we call System.exit in Java

If you have another program running in the JVM and you use System.exit, that second program will be closed, too. Imagine for example that you run a java job on a cluster node and that the java program that manages the cluster node runs in the same JVM. If the job would use System.exit it would not only quit the job but also "shut down the complete node". You would not be able to send another job to that cluster node since the management program has been closed accidentally.

Therefore, do not use System.exit if you want to be able to control your program from another java program within the same JVM.

Use System.exit if you want to close the complete JVM on purpose and if you want to take advantage of the possibilities that have been described in the other answers (e.g. shut down hooks: Java shutdown hook, non-zero return value for command line calls: How to get the exit status of a Java program in Windows batch file).

Also have a look at Runtime Exceptions: System.exit(num) or throw a RuntimeException from main?

With ng-bind-html-unsafe removed, how do I inject HTML?

For me, the simplest and most flexible solution is:

<div ng-bind-html="to_trusted(preview_data.preview.embed.html)"></div>

And add function to your controller:

$scope.to_trusted = function(html_code) {
    return $sce.trustAsHtml(html_code);
}

Don't forget add $sce to your controller's initialization.

How can I extract audio from video with ffmpeg?

Use -b:a instead of -ab as -ab is outdated now, also make sure your input file path is correct.

To extract audio from a video I have used below command and its working fine.

String[] complexCommand = {"-y", "-i", inputFileAbsolutePath, "-vn", "-ar", "44100", "-ac", "2", "-b:a", "256k", "-f", "mp3", outputFileAbsolutePath};

Here,

  • -y - Overwrite output files without asking.
  • -i - FFmpeg reads from an arbitrary number of input “files” specified by the -i option
  • -vn - Disable video recording
  • -ar - sets the sampling rate for audio streams if encoded
  • -ac - Set the number of audio channels.
  • -b:a - Set the audio bitrate
  • -f - format

Check out this for my complete sample FFmpeg android project on GitHub.

How to get image size (height & width) using JavaScript?

You can only really do this using a callback of the load event as the size of the image is not known until it has actually finished loading. Something like the code below...

var imgTesting = new Image();

function CreateDelegate(contextObject, delegateMethod)
{
    return function()
    {
        return delegateMethod.apply(contextObject, arguments);
    }
}

function imgTesting_onload()
{
    alert(this.width + " by " + this.height);
}


imgTesting.onload = CreateDelegate(imgTesting, imgTesting_onload);
imgTesting.src = 'yourimage.jpg';

How to build an APK file in Eclipse?

No one mentioned this, but in conjunction to the other responses, you can also get the apk file from your bin directory to your phone or tablet by putting it on a web site and just downloading it.

Your device will complain about installing it after you download it. Your device will advise you or a risk of installing programs from unknown sources and give you the option to bypass the advice.

Your question is very specific. You don't have to pull it from your emulator, just grab the apk file from the bin folder in your project and place it on your real device.

Most people are giving you valuable information for the next step (signing and publishing your apk), you are not required to do that step to get it on your real device.

Downloading it to your real device is a simple method.

Setting button text via javascript

Use textContent instead of value to set the button text.

Typically the value attribute is used to associate a value with the button when it's submitted as form data.

Note that while it's possible to set the button text with innerHTML, using textContext should be preferred because it's more performant and it can prevent cross-site scripting attacks as its value is not parsed as HTML.

JS:

var b = document.createElement('button');
b.setAttribute('content', 'test content');
b.setAttribute('class', 'btn');  
b.textContent = 'test value';

var wrapper = document.getElementById("divWrapper");
wrapper.appendChild(b);

Produces this in the DOM:

<div id="divWrapper">
    <button content="test content" class="btn">test value</button>
</div>

Demo: https://jsfiddle.net/13ucp6ob/

XPath to select Element by attribute value

As a follow on, you could select "all nodes with a particular attribute" like this:

//*[@id='4']

Cannot bulk load because the file could not be opened. Operating System Error Code 3

I dont know if you solved this issue, but i had same issue, if the instance is local you must check the permission to access the file, but if you are accessing from your computer to a server (remote access) you have to specify the path in the server, so that means to include the file in a server directory, that solved my case

example:

BULK INSERT Table
FROM 'C:\bulk\usuarios_prueba.csv' -- This is server path not local
WITH 
  (
     FIELDTERMINATOR =',',
     ROWTERMINATOR ='\n'
  );

Change action bar color in android

Maybe this can help you also. It's from the website:

http://nathanael.hevenet.com/android-dev-changing-the-title-bar-background/

First things first you need to have a custom theme declared for your application (or activity, depending on your needs). Something like…

<!-- Somewhere in AndroidManifest.xml -->
<application ... android:theme="@style/ThemeSelector">

Then, declare your custom theme for two cases, API versions with and without the Holo Themes. For the old themes we’ll customize the windowTitleBackgroundStyle attribute, and for the newer ones the ActionBarStyle.

<!-- res/values/styles.xml -->
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="ThemeSelector" parent="android:Theme.Light">
        <item name="android:windowTitleBackgroundStyle">@style/WindowTitleBackground</item>
    </style>

    <style name="WindowTitleBackground">     
        <item name="android:background">@color/title_background</item>
    </style>

</resources>

<!-- res/values-v11/styles.xml -->
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="ThemeSelector" parent="android:Theme.Holo.Light">
        <item name="android:actionBarStyle">@style/ActionBar</item>
    </style>

    <style name="ActionBar" parent="android:style/Widget.Holo.ActionBar">     
        <item name="android:background">@color/title_background</item>
    </style>

</resources>

That’s it!

Converting dictionary to JSON

Defining r as a dictionary should do the trick:

>>> r: dict = {'is_claimed': 'True', 'rating': 3.5}
>>> print(r['rating'])
3.5
>>> type(r)
<class 'dict'>

How to get the last char of a string in PHP?

I'd advise to go for Gordon's solution as it is more performant than substr():

<?php 

$string = 'abcdef';
$repetitions = 10000000;

echo "\n\n";
echo "----------------------------------\n";
echo $repetitions . " repetitions...\n";
echo "----------------------------------\n";
echo "\n\n";

$start = microtime(true);
for($i=0; $i<$repetitions; $i++)
    $x = substr($string, -1);

echo "substr() took " . (microtime(true) - $start) . "seconds\n";

$start = microtime(true);
for($i=0; $i<$repetitions; $i++)
    $x = $string[strlen($string)-1];

echo "array access took " . (microtime(true) - $start) . "seconds\n";

die();

outputs something like

 ---------------------------------- 
 10000000 repetitions...
 ----------------------------------

 substr() took 2.0285921096802seconds 
 array access took 1.7474739551544seconds

Get integer value from string in swift

The method you want is toInt() -- you have to be a little careful, since the toInt() returns an optional Int.

let stringNumber = "1234"
let numberFromString = stringNumber.toInt()
// numberFromString is of type Int? with value 1234

let notANumber = "Uh oh"
let wontBeANumber = notANumber.toInt()
// wontBeANumber is of type Int? with value nil

Reading a column from CSV file using JAVA

If you are using Java 7+, you may want to use NIO.2, e.g.:

Code:

public static void main(String[] args) throws Exception {

    File file = new File("test.csv");

    List<String> lines = Files.readAllLines(file.toPath(), 
            StandardCharsets.UTF_8);

    for (String line : lines) {
        String[] array = line.split(",", -1);
        System.out.println(array[0]);
    }

}

Output:

a
1RW
1RW
1RW
1RW
1RW
1RW
1R1W
1R1W
1R1W

How to find index of all occurrences of element in array?

You can write a simple readable solution to this by using both map and filter:

const nanoIndexes = Cars
  .map((car, i) => car === 'Nano' ? i : -1)
  .filter(index => index !== -1);

EDIT: If you don't need to support IE/Edge (or are transpiling your code), ES2019 gave us flatMap, which lets you do this in a simple one-liner:

const nanoIndexes = Cars.flatMap((car, i) => car === 'Nano' ? i : []);

"R cannot be resolved to a variable"?

I got similar problem and solution I found out was in resources any of the file aka background, sound etc must not contain capital letters or any special symbol other than _

How can I get the average (mean) of selected columns

Try using rowMeans:

z$mean=rowMeans(z[,c("x", "y")], na.rm=TRUE)

  w x  y mean
1 5 1  1    1
2 6 2  2    2
3 7 3  3    3
4 8 4 NA    4

state provider and route provider in angularJS

You shouldn't use both ngRoute and UI-router. Here's a sample code for UI-router:

_x000D_
_x000D_
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
  _x000D_
  $stateProvider_x000D_
    .state('state1', {_x000D_
      url: "/state1",_x000D_
      templateUrl: "partials/state1.html",_x000D_
      controller: 'YourCtrl'_x000D_
    })_x000D_
    _x000D_
    .state('state2', {_x000D_
      url: "/state2",_x000D_
      templateUrl: "partials/state2.html",_x000D_
      controller: 'YourOtherCtrl'_x000D_
    });_x000D_
    $urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
_x000D_
_x000D_

You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?

You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router

Manually map column names with class properties

Before you open the connection to your database, execute this piece of code for each of your poco classes:

// Section
SqlMapper.SetTypeMap(typeof(Section), new CustomPropertyTypeMap(
    typeof(Section), (type, columnName) => type.GetProperties().FirstOrDefault(prop =>
    prop.GetCustomAttributes(false).OfType<ColumnAttribute>().Any(attr => attr.Name == columnName))));

Then add the data annotations to your poco classes like this:

public class Section
{
    [Column("db_column_name1")] // Side note: if you create aliases, then they would match this.
    public int Id { get; set; }
    [Column("db_column_name2")]
    public string Title { get; set; }
}

After that, you are all set. Just make a query call, something like:

using (var sqlConnection = new SqlConnection("your_connection_string"))
{
    var sqlStatement = "SELECT " +
                "db_column_name1, " +
                "db_column_name2 " +
                "FROM your_table";

    return sqlConnection.Query<Section>(sqlStatement).AsList();
}

How do I make bootstrap table rows clickable?

There is a javascript plugin that adds this feature to bootstrap.

When rowlink.js is included you can do:

<table data-link="row">
  <tr><td><a href="foo.html">Foo</a></td><td>This is Foo</td></tr>
  <tr><td><a href="bar.html">Bar</a></td><td>Bar is good</td></tr>
</table>

The table will be converted so that the whole row can be clicked instead of only the first column.

OSError: [WinError 193] %1 is not a valid Win32 application

All above solution are logical and I think covers the root cause, but for me, none of the above worked. Hence putting it here as may be helpful for others.

My environment was messed up. As you can see from the traceback, there are two python environments involved here:

  1. C:\Users\example\AppData\Roaming\Python\Python37
  2. C:\Users\example\Anaconda3

I cleaned up the path and just deleted all the files from C:\Users\example\AppData\Roaming\Python\Python37.

Then it worked like the charm.

I hope others may find this helpful.

This link helped me to found the solution.

@ViewChild in *ngIf

Angular 8+

You should add { static: false } as a second option for @ViewChild. This causes the query results to be resolved after change detection runs, allowing your @ViewChild to be updated after the value changes.

Example:

export class AppComponent {
    @ViewChild('contentPlaceholder', { static: false }) contentPlaceholder: ElementRef;

    display = false;

    constructor(private changeDetectorRef: ChangeDetectorRef) {
    }

    show() {
        this.display = true;
        this.changeDetectorRef.detectChanges(); // not required
        console.log(this.contentPlaceholder);
    }
}

Stackblitz example: https://stackblitz.com/edit/angular-d8ezsn

When should you use 'friend' in C++?

When implementing tree algorithms for class, the framework code the prof gave us had the tree class as a friend of the node class.

It doesn't really do any good, other than let you access a member variable without using a setting function.

How to tell whether a point is to the right or left side of a line

I implemented this in java and ran a unit test (source below). None of the above solutions work. This code passes the unit test. If anyone finds a unit test that does not pass, please let me know.

Code: NOTE: nearlyEqual(double,double) returns true if the two numbers are very close.

/*
 * @return integer code for which side of the line ab c is on.  1 means
 * left turn, -1 means right turn.  Returns
 * 0 if all three are on a line
 */
public static int findSide(
        double ax, double ay, 
        double bx, double by,
        double cx, double cy) {
    if (nearlyEqual(bx-ax,0)) { // vertical line
        if (cx < bx) {
            return by > ay ? 1 : -1;
        }
        if (cx > bx) {
            return by > ay ? -1 : 1;
        } 
        return 0;
    }
    if (nearlyEqual(by-ay,0)) { // horizontal line
        if (cy < by) {
            return bx > ax ? -1 : 1;
        }
        if (cy > by) {
            return bx > ax ? 1 : -1;
        } 
        return 0;
    }
    double slope = (by - ay) / (bx - ax);
    double yIntercept = ay - ax * slope;
    double cSolution = (slope*cx) + yIntercept;
    if (slope != 0) {
        if (cy > cSolution) {
            return bx > ax ? 1 : -1;
        }
        if (cy < cSolution) {
            return bx > ax ? -1 : 1;
        }
        return 0;
    }
    return 0;
}

Here's the unit test:

@Test public void testFindSide() {
    assertTrue("1", 1 == Utility.findSide(1, 0, 0, 0, -1, -1));
    assertTrue("1.1", 1 == Utility.findSide(25, 0, 0, 0, -1, -14));
    assertTrue("1.2", 1 == Utility.findSide(25, 20, 0, 20, -1, 6));
    assertTrue("1.3", 1 == Utility.findSide(24, 20, -1, 20, -2, 6));

    assertTrue("-1", -1 == Utility.findSide(1, 0, 0, 0, 1, 1));
    assertTrue("-1.1", -1 == Utility.findSide(12, 0, 0, 0, 2, 1));
    assertTrue("-1.2", -1 == Utility.findSide(-25, 0, 0, 0, -1, -14));
    assertTrue("-1.3", -1 == Utility.findSide(1, 0.5, 0, 0, 1, 1));

    assertTrue("2.1", -1 == Utility.findSide(0,5, 1,10, 10,20));
    assertTrue("2.2", 1 == Utility.findSide(0,9.1, 1,10, 10,20));
    assertTrue("2.3", -1 == Utility.findSide(0,5, 1,10, 20,10));
    assertTrue("2.4", -1 == Utility.findSide(0,9.1, 1,10, 20,10));

    assertTrue("vertical 1", 1 == Utility.findSide(1,1, 1,10, 0,0));
    assertTrue("vertical 2", -1 == Utility.findSide(1,10, 1,1, 0,0));
    assertTrue("vertical 3", -1 == Utility.findSide(1,1, 1,10, 5,0));
    assertTrue("vertical 3", 1 == Utility.findSide(1,10, 1,1, 5,0));

    assertTrue("horizontal 1", 1 == Utility.findSide(1,-1, 10,-1, 0,0));
    assertTrue("horizontal 2", -1 == Utility.findSide(10,-1, 1,-1, 0,0));
    assertTrue("horizontal 3", -1 == Utility.findSide(1,-1, 10,-1, 0,-9));
    assertTrue("horizontal 4", 1 == Utility.findSide(10,-1, 1,-1, 0,-9));

    assertTrue("positive slope 1", 1 == Utility.findSide(0,0, 10,10, 1,2));
    assertTrue("positive slope 2", -1 == Utility.findSide(10,10, 0,0, 1,2));
    assertTrue("positive slope 3", -1 == Utility.findSide(0,0, 10,10, 1,0));
    assertTrue("positive slope 4", 1 == Utility.findSide(10,10, 0,0, 1,0));

    assertTrue("negative slope 1", -1 == Utility.findSide(0,0, -10,10, 1,2));
    assertTrue("negative slope 2", -1 == Utility.findSide(0,0, -10,10, 1,2));
    assertTrue("negative slope 3", 1 == Utility.findSide(0,0, -10,10, -1,-2));
    assertTrue("negative slope 4", -1 == Utility.findSide(-10,10, 0,0, -1,-2));

    assertTrue("0", 0 == Utility.findSide(1, 0, 0, 0, -1, 0));
    assertTrue("1", 0 == Utility.findSide(0,0, 0, 0, 0, 0));
    assertTrue("2", 0 == Utility.findSide(0,0, 0,1, 0,2));
    assertTrue("3", 0 == Utility.findSide(0,0, 2,0, 1,0));
    assertTrue("4", 0 == Utility.findSide(1, -2, 0, 0, -1, 2));
}

How can I query a value in SQL Server XML column

declare @T table(Roles xml)

insert into @T values
('<root>
   <role>Alpha</role>
   <role>Beta</role>
   <role>Gamma</role>
</root>')

declare @Role varchar(10)

set @Role = 'Beta'

select Roles
from @T
where Roles.exist('/root/role/text()[. = sql:variable("@Role")]') = 1

If you want the query to work as where col like '%Beta%' you can use contains

declare @T table(Roles xml)

insert into @T values
('<root>
   <role>Alpha</role>
   <role>Beta</role>
   <role>Gamma</role>
</root>')

declare @Role varchar(10)

set @Role = 'et'

select Roles
from @T
where Roles.exist('/root/role/text()[contains(., sql:variable("@Role"))]') = 1

How to stop/shut down an elasticsearch node?

The Head plugin for Elasticsearch provides a great web based front end for Elasticsearch administration, including shutting down nodes. It can run any Elasticsearch commands as well.

Remove all elements contained in another array

If you're using Typescript and want to match on a single property value, this should work based on Craciun Ciprian's answer above.

You could also make this more generic by allowing non-object matching and / or multi-property value matching.

/**
 *
 * @param arr1 The initial array
 * @param arr2 The array to remove
 * @param propertyName the key of the object to match on
 */
function differenceByPropVal<T>(arr1: T[], arr2: T[], propertyName: string): T[] {
  return arr1.filter(
    (a: T): boolean =>
      !arr2.find((b: T): boolean => b[propertyName] === a[propertyName])
  );
}

Get installed applications in a system

You can take a look at this article. It makes use of registry to read the list of installed applications.

public void GetInstalledApps()
{
    string uninstallKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
    using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(uninstallKey))
    {
        foreach (string skName in rk.GetSubKeyNames())
        {
            using (RegistryKey sk = rk.OpenSubKey(skName))
            {
                try
                {
                    lstInstalled.Items.Add(sk.GetValue("DisplayName"));
                }
                catch (Exception ex)
                { }
            }
        }
    }
}

How to make a new List in Java

With Java 9, you are able to do the following to create an immutable List:

List<Integer> immutableList = List.of(1, 2, 3, 4, 5);

List<Integer> mutableList = new ArrayList<>(immutableList);

Show/hide 'div' using JavaScript

How to show or hide an element:

In order to show or hide an element, manipulate the element's style property. In most cases, you probably just want to change the element's display property:

element.style.display = 'none';           // Hide
element.style.display = 'block';          // Show
element.style.display = 'inline';         // Show
element.style.display = 'inline-block';   // Show

Alternatively, if you would still like the element to occupy space (like if you were to hide a table cell), you could change the element's visibility property instead:

element.style.visibility = 'hidden';      // Hide
element.style.visibility = 'visible';     // Show

Hiding a collection of elements:

If you want to hide a collection of elements, just iterate over each element and change the element's display to none:

function hide (elements) {
  elements = elements.length ? elements : [elements];
  for (var index = 0; index < elements.length; index++) {
    elements[index].style.display = 'none';
  }
}
// Usage:
hide(document.querySelectorAll('.target'));
hide(document.querySelector('.target'));
hide(document.getElementById('target'));

_x000D_
_x000D_
hide(document.querySelectorAll('.target'));_x000D_
_x000D_
function hide (elements) {_x000D_
  elements = elements.length ? elements : [elements];_x000D_
  for (var index = 0; index < elements.length; index++) {_x000D_
    elements[index].style.display = 'none';_x000D_
  }_x000D_
}
_x000D_
<div class="target">This div will be hidden.</div>_x000D_
_x000D_
<span class="target">This span will be hidden as well.</span>
_x000D_
_x000D_
_x000D_

Showing a collection of elements:

Most of the time, you will probably just be toggling between display: none and display: block, which means that the following may be sufficient when showing a collection of elements.

You can optionally specify the desired display as the second argument if you don't want it to default to block.

function show (elements, specifiedDisplay) {
  elements = elements.length ? elements : [elements];
  for (var index = 0; index < elements.length; index++) {
    elements[index].style.display = specifiedDisplay || 'block';
  }
}
// Usage:
var elements = document.querySelectorAll('.target');
show(elements);

show(elements, 'inline-block'); // The second param allows you to specify a display value

_x000D_
_x000D_
var elements = document.querySelectorAll('.target');_x000D_
_x000D_
show(elements, 'inline-block'); // The second param allows you to specify a display value_x000D_
_x000D_
show(document.getElementById('hidden-input'));_x000D_
_x000D_
function show (elements, specifiedDisplay) {_x000D_
  elements = elements.length ? elements : [elements];_x000D_
  for (var index = 0; index < elements.length; index++) {_x000D_
    elements[index].style.display = specifiedDisplay || 'block';_x000D_
  }_x000D_
}
_x000D_
<div class="target" style="display: none">This hidden div should have a display of 'inline-block' when it is shown.</div>_x000D_
_x000D_
<span>Inline span..</span>_x000D_
_x000D_
<input id="hidden-input" />
_x000D_
_x000D_
_x000D_

Alternatively, a better approach for showing the element(s) would be to merely remove the inline display styling in order to revert it back to its initial state. Then check the computed display style of the element in order to determine whether it is being hidden by a cascaded rule. If so, then show the element.

function show (elements, specifiedDisplay) {
  var computedDisplay, element, index;

  elements = elements.length ? elements : [elements];
  for (index = 0; index < elements.length; index++) {
    element = elements[index];

    // Remove the element's inline display styling
    element.style.display = '';
    computedDisplay = window.getComputedStyle(element, null).getPropertyValue('display');

    if (computedDisplay === 'none') {
        element.style.display = specifiedDisplay || 'block';
    }
  }
}

_x000D_
_x000D_
show(document.querySelectorAll('.target'));_x000D_
_x000D_
function show (elements, specifiedDisplay) {_x000D_
  var computedDisplay, element, index;_x000D_
_x000D_
  elements = elements.length ? elements : [elements];_x000D_
  for (index = 0; index < elements.length; index++) {_x000D_
    element = elements[index];_x000D_
_x000D_
    // Remove the element's inline display styling_x000D_
    element.style.display = '';_x000D_
    computedDisplay = window.getComputedStyle(element, null).getPropertyValue('display');_x000D_
_x000D_
    if (computedDisplay === 'none') {_x000D_
        element.style.display = specifiedDisplay || 'block';_x000D_
    }_x000D_
  }_x000D_
}
_x000D_
<span class="target" style="display: none">Should revert back to being inline.</span>_x000D_
_x000D_
<span class="target" style="display: none">Inline as well.</span>_x000D_
_x000D_
<div class="target" style="display: none">Should revert back to being block level.</div>_x000D_
_x000D_
<span class="target" style="display: none">Should revert back to being inline.</span>
_x000D_
_x000D_
_x000D_

(If you want to take it a step further, you could even mimic what jQuery does and determine the element's default browser styling by appending the element to a blank iframe (without a conflicting stylesheet) and then retrieve the computed styling. In doing so, you will know the true initial display property value of the element and you won't have to hardcode a value in order to get the desired results.)

Toggling the display:

Similarly, if you would like to toggle the display of an element or collection of elements, you could simply iterate over each element and determine whether it is visible by checking the computed value of the display property. If it's visible, set the display to none, otherwise remove the inline display styling, and if it's still hidden, set the display to the specified value or the hardcoded default, block.

function toggle (elements, specifiedDisplay) {
  var element, index;

  elements = elements.length ? elements : [elements];
  for (index = 0; index < elements.length; index++) {
    element = elements[index];

    if (isElementHidden(element)) {
      element.style.display = '';

      // If the element is still hidden after removing the inline display
      if (isElementHidden(element)) {
        element.style.display = specifiedDisplay || 'block';
      }
    } else {
      element.style.display = 'none';
    }
  }
  function isElementHidden (element) {
    return window.getComputedStyle(element, null).getPropertyValue('display') === 'none';
  }
}
// Usage:
document.getElementById('toggle-button').addEventListener('click', function () {
  toggle(document.querySelectorAll('.target'));
});

_x000D_
_x000D_
document.getElementById('toggle-button').addEventListener('click', function () {_x000D_
    toggle(document.querySelectorAll('.target'));_x000D_
});_x000D_
_x000D_
function toggle (elements, specifiedDisplay) {_x000D_
  var element, index;_x000D_
_x000D_
  elements = elements.length ? elements : [elements];_x000D_
  for (index = 0; index < elements.length; index++) {_x000D_
    element = elements[index];_x000D_
_x000D_
    if (isElementHidden(element)) {_x000D_
      element.style.display = '';_x000D_
_x000D_
      // If the element is still hidden after removing the inline display_x000D_
      if (isElementHidden(element)) {_x000D_
        element.style.display = specifiedDisplay || 'block';_x000D_
      }_x000D_
    } else {_x000D_
      element.style.display = 'none';_x000D_
    }_x000D_
  }_x000D_
  function isElementHidden (element) {_x000D_
    return window.getComputedStyle(element, null).getPropertyValue('display') === 'none';_x000D_
  }_x000D_
}
_x000D_
.target { display: none; }
_x000D_
<button id="toggle-button">Toggle display</button>_x000D_
_x000D_
<span class="target">Toggle the span.</span>_x000D_
_x000D_
<div class="target">Toggle the div.</div>
_x000D_
_x000D_
_x000D_

How does tuple comparison work in Python?

Tuples are compared position by position: the first item of the first tuple is compared to the first item of the second tuple; if they are not equal (i.e. the first is greater or smaller than the second) then that's the result of the comparison, else the second item is considered, then the third and so on.

See Common Sequence Operations:

Sequences of the same type also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length.

Also Value Comparisons for further details:

Lexicographical comparison between built-in collections works as follows:

  • For two collections to compare equal, they must be of the same type, have the same length, and each pair of corresponding elements must compare equal (for example, [1,2] == (1,2) is false because the type is not the same).
  • Collections that support order comparison are ordered the same as their first unequal elements (for example, [1,2,x] <= [1,2,y] has the same value as x <= y). If a corresponding element does not exist, the shorter collection is ordered first (for example, [1,2] < [1,2,3] is true).

If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is considered smaller (for example, [1,2] < [1,2,3] returns True).

Note 1: < and > do not mean "smaller than" and "greater than" but "is before" and "is after": so (0, 1) "is before" (1, 0).

Note 2: tuples must not be considered as vectors in a n-dimensional space, compared according to their length.

Note 3: referring to question https://stackoverflow.com/questions/36911617/python-2-tuple-comparison: do not think that a tuple is "greater" than another only if any element of the first is greater than the corresponding one in the second.

How to properly use the "choices" field option in Django

The cleanest solution is to use the django-model-utils library:

from model_utils import Choices

class Article(models.Model):
    STATUS = Choices('draft', 'published')
    status = models.CharField(choices=STATUS, default=STATUS.draft, max_length=20)

https://django-model-utils.readthedocs.io/en/latest/utilities.html#choices

How to avoid using Select in Excel VBA

The main reason never to use Select or Activesheet is because most people will have at least another couple of workbooks open (sometimes dozens) when they run your macro, and if they click away from your sheet while your macro is running and click on some other book they have open, then the "Activesheet" changes, and the target workbook for an unqualified "Select" command changes as well.

At best, your macro will crash, at worst you might end up writing values or changing cells in the wrong workbook with no way to "Undo" them.

I have a simple golden rule that I follow: Add variables named "wb" and "ws" for a Workbook object and a Worksheet object and always use those to refer to my macro book. If I need to refer to more than one book, or more than one sheet, I add more variables.

For example,

Dim wb as Workbook
Dim ws as Worksheet
Set wb = ThisWorkBook
Set ws = wb.sheets("Output")

The "Set wb = ThisWorkbook" command is absolutely key. "ThisWorkbook" is a special value in Excel, and it means the workbook that your VBA code is currently running from. A very helpful shortcut to set your Workbook variable with.

After you've done that at the top of your Sub, using them could not be simpler, just use them wherever you would use "Selection":

So to change the value of cell "A1" in "Output" to "Hello", instead of:

Sheets("Output").Activate
ActiveSheet.Range("A1").Select
Selection.Value = "Hello"

We can now do this:

ws.Range("A1").Value = "Hello"

Which is not only much more reliable and less likely to crash if the user is working with multiple spreadsheets; it's also much shorter, quicker and easier to write.

As an added bonus, if you always name your variables "wb" and "ws", you can copy and paste code from one book to another and it will usually work with minimal changes needed, if any.

Float a div in top right corner without overlapping sibling header

Get rid from your <Button> wrap div using display:block and float:left in both <Button> and <h1> and specifying their width with a position:relative to your Section. This approach has the advantage of not needing another div only to position your <Button>

html

<section>  
    <h1>some long long long long header, a whole line, 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6</h1>     
    <button>button</button>
</section>

? css

section {
    position: relative;
    width: 50%;
    border: 1px solid;
    float:left;
}
h1 {
    display: block;
    width:70%;
    float:left;
}
button
{
    position:relative;
    top:0;
    left:0;
    float:left;
}

?

Check if string doesn't contain another string

Use this as your WHERE condition

WHERE CHARINDEX('Apples', column) = 0 

Add button to navigationbar programmatically

In ViewDidLoad method of ViewController.m

UIBarButtonItem *cancel = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(back)];

[self.navigationItem setLeftBarButtonItem:cancel];

"(back)" selector is a method to dissmiss the current ViewController

Add shadow to custom shape on Android

Old question, but Elevation, available with Material Design now provides a shadow to any views.

<TextView
android:id="@+id/myview"
...
android:elevation="2dp"
android:background="@drawable/myrect" />

See the docs at https://developer.android.com/training/material/shadows-clipping.html

.war vs .ear file

To make the project transport, deployment made easy. need to compressed into one file. JAR (java archive) group of .class files

WAR (web archive) - each war represents one web application - use only web related technologies like servlet, jsps can be used. - can run on Tomcat server - web app developed by web related technologies only jsp servlet html js - info representation only no transactions.

EAR (enterprise archive) - each ear represents one enterprise application - we can use anything from j2ee like ejb, jms can happily be used. - can run on Glassfish like server not on Tomcat server. - enterprise app devloped by any technology anything from j2ee like all web app plus ejbs jms etc. - does transactions with info representation. eg. Bank app, Telecom app

How do I concatenate or merge arrays in Swift?

My favorite method since Swift 2.0 is flatten

var a:[CGFloat] = [1, 2, 3]
var b:[CGFloat] = [4, 5, 6]

let c = [a, b].flatten()

This will return FlattenBidirectionalCollection so if you just want a CollectionType this will be enough and you will have lazy evaluation for free. If you need exactly the Array you can do this:

let c = Array([a, b].flatten())

Deserialize a JSON array in C#

[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("Age")]
public int required { get; set; }
[JsonProperty("Location")]
public string type { get; set; }

and Remove a "{"..,

strFieldString = strFieldString.Remove(0, strFieldString.IndexOf('{'));

DeserializeObject..,

   optionsItem objActualField = JsonConvert.DeserializeObject<optionsItem(strFieldString);

HTML Drag And Drop On Mobile Devices

The beta version of Sencha Touch has drag and drop support.

You can refer to their DnD Example. This only works on webkit browsers by the way.

Retrofitting that logic into a web page is probably going to be difficult. As I understand it they disable all browser panning and implement panning events entirely in javascript, allowing correct interpretation of drag and drop.

Update: the original example link is dead, but I found this alternative:
https://github.com/kostysh/Drag-Drop-example-for-Sencha-Touch

how to inherit Constructor from super class to sub class

Constructors are not inherited, you must create a new, identically prototyped constructor in the subclass that maps to its matching constructor in the superclass.

Here is an example of how this works:

class Foo {
    Foo(String str) { }
}

class Bar extends Foo {
    Bar(String str) {
        // Here I am explicitly calling the superclass 
        // constructor - since constructors are not inherited
        // you must chain them like this.
        super(str);
    }
}

The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)

We use the Url Rewrite extension for IIS for redirecting all HTTP requests to HTTPS. When trying to call a service not using transport security on an http://... address, this is the error that appeared.

So it might be worth checking if you can hit both the http and https addresses of the service via a browser and that it doesn't auto forward you with a 303 status code.

Where do I download JDBC drivers for DB2 that are compatible with JDK 1.5?

I know its late but i recently ran into this situation. After wasting entire day I finally found the solution. I am suprised that I got this info on oracle's website whereas this seems nowhere to be found on IBM's website.

If you want to use JDBC drivers for DB2 that are compatible with JDK 1.5 or 1.4 , you need to use the jar db2jcc.jar, which is available in SQLLIB/java/ folder of your db2 installation.

Run as java application option disabled in eclipse

Run As > Java Application wont show up if the class that you want to run does not contain the main method. Make sure that the class you trying to run has main defined in it.

Using JQuery hover with HTML image map

Although jQuery Maphilight plugin does the job, it relies on the outdated verbose imagemap in your html. I would prefer to keep the mapcoordinates external. This could be as JS with the jquery imagemap plugin but it lacks hover states. A nice solution is googles geomap visualisation in flash and JS. But the opensource future for this kind of vectordata however is svg, considering svg support accross all modern browsers, and googles svgweb for a flash convert for IE, why not a jquery plugin to add links and hoverstates to a svg map, like the JS demo here? That way you also avoid the complex step of transforming a vectormap to a imagemap coordinates.

Git - fatal: Unable to create '/path/my_project/.git/index.lock': File exists

I think there's a better solution than removing the file (and god knows what will happen next when removing/creating a file with sudo):

git gc

How to compile for Windows on Linux with gcc/g++?

Install a cross compiler, like mingw64 from your package manager. Then compile in the following way: instead of simply calling gcc call i686-w64-mingw32-gcc for 32-bit Windows or x86_64-w64-mingw32-gcc" for 64-bit Windows. I would also use the --static option, as the target system may not have all the libraries.

If you want to compile other language, like Fortran, replace -gcc with -gfortran in the previous commands.

How to get ° character in a string in python?

just use \xb0 (in a string); python will convert it automatically

Redraw datatables after using ajax to refresh the table content?

For users of modern DataTables (1.10 and above), all the answers and examples on this page are for the old api, not the new. I had a very hard time finding a newer example but finally did find this DT forum post (TL;DR for most folks) which led me to this concise example.

The example code worked for me after I finally noticed the $() selector syntax immediately surrounding the html string. You have to add a node not a string.

That example really is worth looking at but, in the spirit of SO, if you just want to see a snippet of code that works:

var table = $('#example').DataTable();
  table.rows.add( $(
          '<tr>'+
          '  <td>Tiger Nixon</td>'+
          '  <td>System Architect</td>'+
          '  <td>Edinburgh</td>'+
          '  <td>61</td>'+
          '  <td>2011/04/25</td>'+
          '  <td>$3,120</td>'+
          '</tr>'
  ) ).draw();

The careful reader might note that, since we are adding only one row of data, that table.row.add(...) should work as well and did for me.

Command line: search and replace in all filenames matched by grep

Do you mean search and replace a string in all files matched by grep?

perl -p -i -e 's/oldstring/newstring/g' `grep -ril searchpattern *`

Edit

Since this seems to be a fairly popular question thought I'd update.

Nowadays I mostly use ack-grep as it's more user-friendly. So the above command would be:

perl -p -i -e 's/old/new/g' `ack -l searchpattern`

To handle whitespace in file names you can run:

ack --print0 -l searchpattern | xargs -0 perl -p -i -e 's/old/new/g'

you can do more with ack-grep. Say you want to restrict the search to HTML files only:

ack --print0 --html -l searchpattern | xargs -0 perl -p -i -e 's/old/new/g'

And if white space is not an issue it's even shorter:

perl -p -i -e 's/old/new/g' `ack -l --html searchpattern`
perl -p -i -e 's/old/new/g' `ack -f --html` # will match all html files

Find records with a date field in the last 24 hours

SELECT * from new WHERE date < DATE_ADD(now(),interval -1 day);

undefined reference to 'vtable for class' constructor

You're declaring a virtual function and not defining it:

virtual void calculateCredits();

Either define it or declare it as:

virtual void calculateCredits() = 0;

Or simply:

virtual void calculateCredits() { };

Read more about vftable: http://en.wikipedia.org/wiki/Virtual_method_table

Error in MySQL when setting default value for DATE or DATETIME

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

MySQL Documentation 5.7 says:

Strict mode affects whether the server permits '0000-00-00' as a valid date: If strict mode is not enabled, '0000-00-00' is permitted and inserts produce no warning. If strict mode is enabled, '0000-00-00' is not permitted and inserts produce an error, unless IGNORE is given as well. For INSERT IGNORE and UPDATE IGNORE, '0000-00-00' is permitted and inserts produce a warning.

To Check MYSQL mode

SELECT @@GLOBAL.sql_mode global, @@SESSION.sql_mode session

Disabling STRICT_TRANS_TABLES mode

However to allow the format 0000-00-00 00:00:00you have to disable STRICT_TRANS_TABLES mode in mysql config file or by command

By command

SET sql_mode = '';

or

SET GLOBAL sql_mode = '';

Using the keyword GLOBAL requires super previliges and it affects the operations all clients connect from that time on

if above is not working than go to /etc/mysql/my.cnf (as per ubuntu) and comment out STRICT_TRANS_TABLES

Also, if you want to permanently set the sql mode at server startup then include SET sql_mode='' in my.cnf on Linux or MacOS. For windows this has to be done in my.ini file.

Note

However strict mode is not enabled by default in MYSQL 5.6. Hence it does not produce the error as per MYSQL 6 documentation which says

MySQL permits you to store a “zero” value of '0000-00-00' as a “dummy date.” This is in some cases more convenient than using NULL values, and uses less data and index space. To disallow '0000-00-00', enable the NO_ZERO_DATE SQL mode.

UPDATE

Regarding the bug matter as said by @Dylan-Su:

I don't think this is the bug it the way MYSQL is evolved over the time due to which some things are changed based on further improvement of the product.

However I have another related bug report regarding the NOW() function

Datetime field does not accept default NOW()

Another Useful note [see Automatic Initialization and Updating for TIMESTAMP and DATETIME]

As of MySQL 5.6.5, TIMESTAMP and DATETIME columns can be automatically initializated and updated to the current date and time (that is, the current timestamp). Before 5.6.5, this is true only for TIMESTAMP, and for at most one TIMESTAMP column per table. The following notes first describe automatic initialization and updating for MySQL 5.6.5 and up, then the differences for versions preceding 5.6.5.

Update Regarding NO_ZERO_DATE

As of MySQL as of 5.7.4 this mode is deprecated. For previous version you must comment out the respective line in the config file. Refer MySQL 5.7 documentation on NO_ZERO_DATE

Invisible characters - ASCII

There is actually a truly invisible character: U+FEFF. This character is called the Byte Order Mark and is related to the Unicode 8 system. It is a really confusing concept that can be explained HERE The Byte Order Mark or BOM for short is an invisible character that doesn't take up any space. You can copy the character bellow between the > and <.

Here is the character:

> <

How to catch this character in action:

  • Copy the character between the > and <,
  • Write a line of text, then randomly put your caret in the line of text
  • Paste the character in the line.
  • Go to the beginning of the line and press and hold the right arrow key.

You will notice that when your caret gets to the place you pasted the character, it will briefly stop for around half a second. This is becuase the caret is passing over the invisible character. Even though you can't see it doesn't mean it isn't there. The caret still sees that there is a character in that area that you pasted the BOM and will pass through it. Since the BOM is invisble, the caret will look like it has paused for a brief moment. You can past the BOM multiple times in an area and redo the steps above to really show the affect. Good luck!

EDIT: Sadly, Stackoverflow doesn't like the character. Here is an example from w3.org: https://www.w3.org/International/questions/examples/phpbomtest.php

How to customise file type to syntax associations in Sublime Text?

There is a quick method to set the syntax: Ctrl+Shift+P,then type in the input box

ss + (which type you want set)

eg: ss html +Enter

and ss means "set syntax"

it is really quicker than check in the menu's checkbox.

A good Sorted List for Java

What about using a HashMap? Insertion, deletion, and retrieval are all O(1) operations. If you wanted to sort everything, you could grab a List of the values in the Map and run them through an O(n log n) sorting algorithm.

edit

A quick search has found LinkedHashMap, which maintains insertion order of your keys. It's not an exact solution, but it's pretty close.

Get Context in a Service

  1. Service extends ContextWrapper
  2. ContextWrapper extends Context

So....

Context context = this;

(in Service or Activity Class)

Disable Chrome strict MIME type checking

For Windows Users :

If this issue occurs on your self hosted server (eg: your custom CDN) and the browser (Chrome) says something like ... ('text/plain') is not executable ... when trying to load your javascript file ...

Here is what you need to do :

  1. Open the Registry Editor i.e Win + R > regedit
  2. Head over to HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.js
  3. Check to if the Content Type is application/javascript or not
  4. If not, then change it to application/javascript and try again

Mocking a class: Mock() or patch()?

Key points which explain difference and provide guidance upon working with unittest.mock

  1. Use Mock if you want to replace some interface elements(passing args) of the object under test
  2. Use patch if you want to replace internal call to some objects and imported modules of the object under test
  3. Always provide spec from the object you are mocking
    • With patch you can always provide autospec
    • With Mock you can provide spec
    • Instead of Mock, you can use create_autospec, which intended to create Mock objects with specification.

In the question above the right answer would be to use Mock, or to be more precise create_autospec (because it will add spec to the mock methods of the class you are mocking), the defined spec on the mock will be helpful in case of an attempt to call method of the class which doesn't exists ( regardless signature), please see some

from unittest import TestCase
from unittest.mock import Mock, create_autospec, patch


class MyClass:
    
    @staticmethod
    def method(foo, bar):
        print(foo)


def something(some_class: MyClass):
    arg = 1
    # Would fail becuase of wrong parameters passed to methd.
    return some_class.method(arg)


def second(some_class: MyClass):
    arg = 1
    return some_class.unexisted_method(arg)


class TestSomethingTestCase(TestCase):
    def test_something_with_autospec(self):
        mock = create_autospec(MyClass)
        mock.method.return_value = True
        # Fails because of signature misuse.
        result = something(mock)
        self.assertTrue(result)
        self.assertTrue(mock.method.called)
    
    def test_something(self):
        mock = Mock()  # Note that Mock(spec=MyClass) will also pass, because signatures of mock don't have spec.
        mock.method.return_value = True
        
        result = something(mock)
        
        self.assertTrue(result)
        self.assertTrue(mock.method.called)
        
    def test_second_with_patch_autospec(self):
        with patch(f'{__name__}.MyClass', autospec=True) as mock:
            # Fails because of signature misuse.
            result = second(mock)
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)


class TestSecondTestCase(TestCase):
    def test_second_with_autospec(self):
        mock = Mock(spec=MyClass)
        # Fails because of signature misuse.
        result = second(mock)
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)
    
    def test_second_with_patch_autospec(self):
        with patch(f'{__name__}.MyClass', autospec=True) as mock:
            # Fails because of signature misuse.
            result = second(mock)
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)
    
    def test_second(self):
        mock = Mock()
        mock.unexisted_method.return_value = True
        
        result = second(mock)
        
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)

The test cases with defined spec used fail because methods called from something and second functions aren't complaint with MyClass, which means - they catch bugs, whereas default Mock will display.

As a side note there is one more option: use patch.object to mock just the class method which is called with.

The good use cases for patch would be the case when the class is used as inner part of function:

def something():
    arg = 1
    return MyClass.method(arg)

Then you will want to use patch as a decorator to mock the MyClass.

CSS Auto hide elements after 5 seconds

YES!

But you can't do it in the way you may immediately think, because you cant animate or create a transition around the properties you'd otherwise rely on (e.g. display, or changing dimensions and setting to overflow:hidden) in order to correctly hide the element and prevent it from taking up visible space.

Therefore, create an animation for the elements in question, and simply toggle visibility:hidden; after 5 seconds, whilst also setting height and width to zero to prevent the element from still occupying space in the DOM flow.

FIDDLE

CSS

html, body {
    height:100%;
    width:100%;
    margin:0;
    padding:0;
}
#hideMe {
    -moz-animation: cssAnimation 0s ease-in 5s forwards;
    /* Firefox */
    -webkit-animation: cssAnimation 0s ease-in 5s forwards;
    /* Safari and Chrome */
    -o-animation: cssAnimation 0s ease-in 5s forwards;
    /* Opera */
    animation: cssAnimation 0s ease-in 5s forwards;
    -webkit-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
}
@keyframes cssAnimation {
    to {
        width:0;
        height:0;
        overflow:hidden;
    }
}
@-webkit-keyframes cssAnimation {
    to {
        width:0;
        height:0;
        visibility:hidden;
    }
}

HTML

<div id='hideMe'>Wait for it...</div>

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its dependencies could not be resolved

I solved it now. However it only is solved in Netbeans. Not sure why eclipse still won't take the settings.xml that is changed. The solution is however to remove/comment the User/Password param in settings.xml

Before:

<proxies>
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>proxyuser</username>
      <password>proxypass</password>
      <host>proxyserver.company.com</host>
      <port>8080</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
  </proxies> 

After:

<proxies>
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <host>proxyserver.company.com</host>
      <port>8080</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
  </proxies> 

How do I get video durations with YouTube API version 3?

Youtube data 3 API , duration string to seconds conversion in Python

Example:

convert_YouTube_duration_to_seconds('P2DT1S')
172801

convert_YouTube_duration_to_seconds('PT2H12M51S')
7971

def convert_YouTube_duration_to_seconds(duration):
   day_time = duration.split('T')
   day_duration = day_time[0].replace('P', '')
   day_list = day_duration.split('D')
   if len(day_list) == 2:
      day = int(day_list[0]) * 60 * 60 * 24
      day_list = day_list[1]
   else:
      day = 0
      day_list = day_list[0]
   hour_list = day_time[1].split('H')
   if len(hour_list) == 2:
      hour = int(hour_list[0]) * 60 * 60
      hour_list = hour_list[1]
   else:
      hour = 0
      hour_list = hour_list[0]
   minute_list = hour_list.split('M')
   if len(minute_list) == 2:
      minute = int(minute_list[0]) * 60
      minute_list = minute_list[1]
   else:
      minute = 0
      minute_list = minute_list[0]
   second_list = minute_list.split('S')
   if len(second_list) == 2:
      second = int(second_list[0])
   else:
      second = 0
   return day + hour + minute + second

How to trigger click event on href element

I do not have factual evidence to prove this but I already ran into this issue. It seems that triggering a click() event on an <a> tag doesn't seem to behave the same way you would expect with say, a input button.

The workaround I employed was to set the location.href property on the window which causes the browser to load the request resource like so:

$(document).ready(function()
{
      var href = $('.cssbuttongo').attr('href');
      window.location.href = href; //causes the browser to refresh and load the requested url
   });
});

Edit:

I would make a js fiddle but the nature of the question intermixed with how jsfiddle uses an iframe to render code makes that a no go.

Check if XML Element exists

Just came across the same problem and the null-coalescing operator with SelectSingleNode worked a treat, assigning null with string.Empty

 foreach (XmlNode txElement in txElements)
 {
     var txStatus = txElement.SelectSingleNode(".//ns:TxSts", nsmgr).InnerText ?? string.Empty;
     var endToEndId = txElement.SelectSingleNode(".//ns:OrgnlEndToEndId", nsmgr).InnerText ?? string.Empty;
     var paymentAmount = txElement.SelectSingleNode(".//ns:InstdAmt", nsmgr).InnerText ?? string.Empty;
     var paymentAmountCcy = txElement.SelectSingleNode(".//ns:InstdAmt", nsmgr).Attributes["Ccy"].Value ?? string.Empty;
     var clientId = txElement.SelectSingleNode(".//ns:OrgnlEndToEndId", nsmgr).InnerText ?? string.Empty;
     var bankSortCode = txElement.SelectSingleNode(".//ns:OrgnlEndToEndId", nsmgr).InnerText ?? string.Empty; 

     //TODO finish Object creation and Upsert DB
  }

source of historical stock data

We have purchased 12 years of intraday data from Kibot.com and are pretty satisfied with the quality.

As for storage requirements: 12 years of 1-minute data for all USA equities (more than 8000 symbols) is about 100GB.

With tick-by-tick data situation is little different. If you record time and sales only, that would be about 30GB of data per month for all USA equities. If you want to store bid / ask changes together with transactions, you can expect about 150GB per month.

I hope this helps. Please let me know if there is anything else I can assist you with.

How to change Elasticsearch max memory size

In elasticsearch 2.x :

vi /etc/sysconfig/elasticsearch 

Go to the block of code

# Heap size defaults to 256m min, 1g max
# Set ES_HEAP_SIZE to 50% of available RAM, but no more than 31g
#ES_HEAP_SIZE=2g

Uncomment last line like

ES_HEAP_SIZE=2g

What does -save-dev mean in npm install grunt --save-dev

--save-dev: Package will appear in your devDependencies.

According to the npm install docs.

If someone is planning on downloading and using your module in their program, then they probably don't want or need to download and build the external test or documentation framework that you use.

In other words, when you run npm install, your project's devDependencies will be installed, but the devDependencies for any packages that your app depends on will not be installed; further, other apps having your app as a dependency need not install your devDependencies. Such modules should only be needed when developing the app (eg grunt, mocha etc).

According to the package.json docs

Edit: Attempt at visualising what npm install does:

  • yourproject
    • dependency installed
      • dependency installed
        • dependency installed
        • devDependency NOT installed
      • devDependency NOT installed
    • devDependency installed
      • dependency installed
      • devDependency NOT installed

CSS Background image not loading

I'd like to share my debugging process because I was stuck on this issue for at least an hour. Image could not be found when running local host. To add some context, I am styling within a rails app in the following directory:

apps/assets/stylesheets/main.scss

I wanted to render background image in header tag. The following was my original implementation.

header {
    text-align: center;
    background: linear-gradient(90deg, #d4eece, #d4eece, #d4eece),
              url('../images/header.jpg') no-repeat;
              background-blend-mode: multiply;
              background-size: cover;
}

...as a result I was getting the following error in rails server and the console in Chrome dev tools, respectively:

ActionController::RoutingError (No route matches [GET] "/images/header.jpg")
GET http://localhost:3000/images/header.jpg 404 (Not Found)

I tried different variations of the url:

url('../images/header.jpg') # DID NOT WORK
url('/../images/header.jpg') # DID NOT WORK
url('./../images/header.jpg') # DID NOT WORK

and it still did not work. At that point, I was very confused...I decided to move the image folder from the assets directory (which is the default) to within the stylesheets directory, and tried the following variations of the url:

url('/images/header.jpg') # DID NOT WORK
url('./images/header.jpg') # WORKED
url('images/header.jpg') # WORKED

I no longer got the console and rails server error. But the image still was not showing for some reason. After temporarily giving up, I found out the solution to this was to add a height property in order for the image to be shown...

header {
    text-align: center;
    height: 390px;
    background: linear-gradient(90deg, #d4eece, #d4eece, #d4eece),
              url('images/header.jpg') no-repeat;
              background-blend-mode: multiply;
              background-size: cover;
}

Unfortunately, I am still not sure why the 3 initial url attempts with "../images/header.jpg" did not work on localhost, or when I should or shouldn't be adding a period at the beginning of the url.

It might have something to do with how the default link tag is setup in application.html.erb, or maybe it's a .scss vs .css thing. Or, maybe that's just how the background property with url() works (the image needs to be within same directory as the css file)? Anyhow, this is how I solved the issue with CSS background image not loading on localhost.

Clear text in EditText when entered

Your code should be:

    public class Project extends Activity implements OnClickListener {
            /** Called when the activity is first created. */
            EditText editText;
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);            

                setContentView(R.layout.main);
                editText = (EditText)findViewById(R.id.editText1);
                editText.setOnClickListener(this);            
            }

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                if(v == editText) {
                    editText.setText("");
                }
            }
        }

How to link HTML5 form action to Controller ActionResult method in ASP.NET MVC 4

you make the use of the HTML Helper and have

    @using(Html.BeginForm())
    {
        Username: <input type="text" name="username" /> <br />
        Password: <input type="text" name="password" /> <br />
        <input type="submit" value="Login">
        <input type="submit" value="Create Account"/>
    }

or use the Url helper

<form method="post" action="@Url.Action("MyAction", "MyController")" >

Html.BeginForm has several (13) overrides where you can specify more information, for example, a normal use when uploading files is using:

@using(Html.BeginForm("myaction", "mycontroller", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
    < ... >
}

If you don't specify any arguments, the Html.BeginForm() will create a POST form that points to your current controller and current action. As an example, let's say you have a controller called Posts and an action called Delete

public ActionResult Delete(int id)
{
   var model = db.GetPostById(id);
   return View(model);
}

[HttpPost]
public ActionResult Delete(int id)
{
    var model = db.GetPostById(id);
    if(model != null) 
        db.DeletePost(id);

    return RedirectToView("Index");
}

and your html page would be something like:

<h2>Are you sure you want to delete?</h2>
<p>The Post named <strong>@Model.Title</strong> will be deleted.</p>

@using(Html.BeginForm())
{
    <input type="submit" class="btn btn-danger" value="Delete Post"/>
    <text>or</text>
    @Url.ActionLink("go to list", "Index")
}

Rounding a number to the nearest 5 or 10 or X

I cannot add comment so I will use this

in a vbs run that and have fun figuring out why the 2 give a result of 2

you can't trust round

 msgbox round(1.5) 'result to 2
 msgbox round(2.5) 'yes, result to 2 too

Adding text to a cell in Excel using VBA

You could do

[A1].Value = "'O1/01/13 00:00"

if you really mean to add it as text (note the apostrophe as the first character).

The [A1].Value is VBA shorthand for Range("A1").Value.

If you want to enter a date, you could instead do (edited order with thanks to @SiddharthRout):

[A1].NumberFormat = "mm/dd/yyyy hh:mm;@"
[A1].Value = DateValue("01/01/2013 00:00")

How can I replace every occurrence of a String in a file with PowerShell?

You could try something like this:

$path = "C:\testFile.txt"
$word = "searchword"
$replacement = "ReplacementText"
$text = get-content $path 
$newText = $text -replace $word,$replacement
$newText > $path

SQL ORDER BY multiple columns

Yes, the sorting is different.

Items in the ORDER BY list are applied in order.
Later items only order peers left from the preceding step.

Why don't you just try?

Angularjs - Pass argument to directive

<button my-directive="push">Push to Go</button>

app.directive("myDirective", function() {
    return {
        restrict : "A",
         link: function(scope, elm, attrs) {
                elm.bind('click', function(event) {

                    alert("You pressed button: " + event.target.getAttribute('my-directive'));
                });
        }
    };
});

here is what I did

I'm using directive as html attribute and I passed parameter as following in my HTML file. my-directive="push" And from the directive I retrieved it from the Mouse-click event object. event.target.getAttribute('my-directive').

Opposite of %in%: exclude rows with values specified in a vector

Here is a version using filter in dplyr that applies the same technique as the accepted answer by negating the logical with !:

D2 <- D1 %>% dplyr::filter(!V1 %in% c('B','N','T'))

Making a Windows shortcut start relative to where the folder is?

The method that proposed by 'leoj' does not allow passing parameters with spaces. Us it:

    cmd.exe /v /c %CD:~0,2%"%CD:~2%\bat\bat\run.bat" "Par1-1 Par1-2" Par2

Which will be similar double quote written as in path

    C:"\Program Files\anyProgram.exe" "Par1-1 Par1-2" Par2

Why is String immutable in Java?

Most important reason according to this article on DZone:

String Constant Pool ... If string is mutable, changing the string with one reference will lead to the wrong value for the other references.

Security

String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Were String not immutable, a connection or file would be changed and lead to serious security threat. ...

Hope it will help you.

How to include route handlers in multiple files in Express?

If you want to put the routes in a separate file, for example routes.js, you can create the routes.js file in this way:

module.exports = function(app){

    app.get('/login', function(req, res){
        res.render('login', {
            title: 'Express Login'
        });
    });

    //other routes..
}

And then you can require it from app.js passing the app object in this way:

require('./routes')(app);

Have also a look at these examples

https://github.com/visionmedia/express/tree/master/examples/route-separation

Change header background color of modal of twitter bootstrap

The corners are actually in .modal-content

So you may try this:

.modal-content {
  background-color: #0480be;
}
.modal-body {
  background-color: #fff;
}

If you change the color of the header or footer, the rounded corners will be drawn over.

Could not load file or assembly '' or one of its dependencies

Open IIS Manager

Select Application Pools

then select the pool you are using

go to advanced settings (at right side)

Change the flag of Enable 32-bit application false to true.

Do you have to include <link rel="icon" href="favicon.ico" type="image/x-icon" />?

Many people set their cookie path to /. That will cause every favicon request to send a copy of the sites cookies, at least in chrome. Addressing your favicon to your cookieless domain should correct this.

<link rel="icon" href="https://cookieless.MySite.com/favicon.ico" type="image/x-icon" />

Depending on how much traffic you get, this may be the most practical reason for adding the link.

Info on setting up a cookieless domain:

http://www.ravelrumba.com/blog/static-cookieless-domain/

Add an object to a python list

You need to create a copy of the list before you modify its contents. A quick shortcut to duplicate a list is this:

mylist[:]

Example:

>>> first = [1,2,3]
>>> second = first[:]
>>> second.append(4)
>>> first
[1, 2, 3]
>>> second
[1, 2, 3, 4]

And to show the default behavior that would modify the orignal list (since a name in Python is just a reference to the underlying object):

>>> first = [1,2,3]
>>> second = first
>>> second.append(4)
>>> first
[1, 2, 3, 4]
>>> second
[1, 2, 3, 4]

Note that this only works for lists. If you need to duplicate the contents of a dictionary, you must use copy.deepcopy() as suggested by others.

How to display all elements in an arraylist?

Arraylist uses Iterator interface to traverse the elements Use this

public void display(ArrayList<Integer> v) {
        Iterator vEnum = v.iterator();
        System.out.println("\nElements in vector:");
        while (vEnum.hasNext()) {
            System.out.print(vEnum.next() + " ");
        }
    }

How do I print a datetime in the local timezone?

I believe the best way to do this is to use the LocalTimezone class defined in the datetime.tzinfo documentation (goto http://docs.python.org/library/datetime.html#tzinfo-objects and scroll down to the "Example tzinfo classes" section):

Assuming Local is an instance of LocalTimezone

t = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=utc)
local_t = t.astimezone(Local)

then str(local_t) gives:

'2009-07-11 04:44:59.193982+10:00'

which is what you want.

(Note: this may look weird to you because I'm in New South Wales, Australia which is 10 or 11 hours ahead of UTC)

VB.Net Properties - Public Get, Private Set

I find marking the property as readonly cleaner than the above answers. I believe vb14 is required.

Private _Name As String

Public ReadOnly Property Name() As String
    Get
        Return _Name
    End Get
End Property

This can be condensed to

Public ReadOnly Property Name As String

https://msdn.microsoft.com/en-us/library/dd293589.aspx?f=255&MSPPError=-2147217396

What's the difference between struct and class in .NET?

Instances of classes are stored on the managed heap. All variables 'containing' an instance are simply a reference to the instance on the heap. Passing an object to a method results in a copy of the reference being passed, not the object itself.

Structures (technically, value types) are stored wherever they are used, much like a primitive type. The contents may be copied by the runtime at any time and without invoking a customised copy-constructor. Passing a value type to a method involves copying the entire value, again without invoking any customisable code.

The distinction is made better by the C++/CLI names: "ref class" is a class as described first, "value class" is a class as described second. The keywords "class" and "struct" as used by C# are simply something that must be learned.

Delete element in a slice

In golang's wiki it show some tricks for slice, including delete an element from slice.

Link: enter link description here

For example a is the slice which you want to delete the number i element.

a = append(a[:i], a[i+1:]...)

OR

a = a[:i+copy(a[i:], a[i+1:])]

Not able to launch IE browser using Selenium2 (Webdriver) with Java

Rather than using Absolute path for IEDriverServer.exe, its better to use relative path in accordance to the project.

        DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
        capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
        File fil = new File("iDrivers\\IEDriverServer.exe");
        System.setProperty("webdriver.ie.driver", fil.getAbsolutePath());
        WebDriver driver = new InternetExplorerDriver(capabilities);        
        driver.get("https://www.irctc.co.in");          

White space at top of page

Old question, but I just ran into this. Sometimes your files are UTF-8 with a BOM at the start, and your template engine doesn't like that. So when you include your template, you get another (invisible) BOM inserted into your page...

<body>{INVISIBLE BOM HERE}...</body>

This causes a gap at the start of your page, where the browser renders the BOM, but it looks invisible to you (and in the inspector, just shows up as whitespace/quotes.

Save your template files as UTF-8 without BOM, or change your template engine to correctly handle UTF8/BOM documents.

Can two Java methods have same name with different return types?

If it's in the same class with the equal number of parameters with the same types and order, then it is not possible for example:

int methoda(String a,int b) {
        return b;
}
String methoda(String b,int c) {
        return b;    
}

if the number of parameters and their types is same but order is different then it is possible since it results in method overloading. It means if the method signature is same which includes method name with number of parameters and their types and the order they are defined.

Invalid http_host header

The error log is straightforward. As it suggested,You need to add 198.211.99.20 to your ALLOWED_HOSTS setting.

In your project settings.py file,set ALLOWED_HOSTS like this :

ALLOWED_HOSTS = ['198.211.99.20', 'localhost', '127.0.0.1']

For further reading read from here.

MassAssignmentException in Laravel

if you have table and fields on database you can simply use this command :

php artisan db:seed --class=UsersTableSeeder --database=YOURDATABSE

How do I correct this Illegal String Offset?

I get the same error in WP when I use php ver 7.1.6 - just take your php version back to 7.0.20 and the error will disappear.

Convert Current date to integer

On my Java 7, the output is different:

Integer : 1293732698
Long : 1345618496346
Long date : Wed Aug 22 10:54:56 MSK 2012
Int Date : Fri Jan 16 02:22:12 MSK 1970

which is an expected behavior.

It is impossible to display the current date in milliseconds as an integer (10 digit number), because the latest possible date is Sun Apr 26 20:46:39 MSK 1970:

Date d = new Date(9999_9999_99L);
System.out.println("Date: " + d);

Date: Sun Apr 26 20:46:39 MSK 1970

You might want to consider displaying it in seconds/minutes.

RSA: Get exponent and modulus given a public key

Beware the leading 00 that can appear in the modulus when using:

openssl rsa -pubin -inform PEM -text -noout < public.key

The example modulus contains 257 bytes rather than 256 bytes because of that 00, which is included because the 9 in 98 looks like a negative signed number.

Switch/toggle div (jQuery)

I used this way to do that for multiple blocks without conjuring new JavaScript code:

<a href="#" data-toggle="thatblock">Show/Hide Content</a>

<div id="thatblock" style="display: none">
  Here is some description that will appear when we click on the button
</div>

Then a JavaScript portion for all such cases:

$(function() {
  $('*[data-toggle]').click(function() {
    $('#'+$(this).attr('data-toggle')).toggle();
    return false;
  });
});

Bootstrap 3 navbar active li not changing background-color

Did you include "bootstrap-theme.css" files on your code?

In "bootstrap-theme.min.css" files, background-image about ".active" is existed for "navbar" (check this screenshot: http://i.imgur.com/1etLIyY.png).

It will re-declare your style code, and then it will be effected on your code.

So after you delete or re-declare them (background-image), you can use your background color style about the ".active" tag.

Android Studio: Default project directory

I have Android Studio version 3.1.2, it shows project full path when you click Build tab in bottom-left location of the studio.

enter image description here

Execute Python script via crontab

Just use crontab -e and follow the tutorial here.

Look at point 3 for a guide on how to specify the frequency.

Based on your requirement, it should effectively be:

*/10 * * * * /usr/bin/python script.py

"Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"

After a sequence of attempts I came into a facile solution. You can try Reinstalling ActiveX plugin for Adobe flashplayer.

Entity Framework - Generating Classes

1) First you need to generate EDMX model using your database. To do that you should add new item to your project:

  • Select ADO.NET Entity Data Model from the Templates list.
  • On the Choose Model Contents page, select the Generate from Database option and click Next.
  • Choose your database.
  • On the Choose Your Database Objects page, check the Tables. Choose Views or Stored Procedures if you need.

So now you have Model1.edmx file in your project.

2) To generate classes using your model:

  • Open your EDMX model designer.
  • On the design surface Right Click –> Add Code Generation Item…
  • Select Online templates.
  • Select EF 4.x DbContext Generator for C#.
  • Click ‘Add’.

Notice that two items are added to your project:

  • Model1.tt (This template generates very simple POCO classes for each entity in your model)
  • Model1.Context.tt (This template generates a derived DbContext to use for querying and persisting data)

3) Read/Write Data example:

 var dbContext = new YourModelClass(); //class derived from DbContext
 var contacts = from c in dbContext.Contacts select c; //read data
 contacts.FirstOrDefault().FirstName = "Alex"; //edit data
 dbContext.SaveChanges(); //save data to DB

Don't forget that you need 4.x version of EntityFramework. You can download EF 4.1 here: Entity Framework 4.1.

Python: convert string to byte array

This work in both Python 2 and 3:

>>> bytearray(b'ABCD')
bytearray(b'ABCD')

Note string started with b.

To get individual chars:

>>> print("DEC HEX ASC")
... for b in bytearray(b'ABCD'):
...     print(b, hex(b), chr(b))
DEC HEX ASC
65 0x41 A
66 0x42 B
67 0x43 C
68 0x44 D

Hope this helps

How to import module when module name has a '-' dash or hyphen in it?

Starting from Python 3.1, you can use importlib :

import importlib  
foobar = importlib.import_module("foo-bar")

( https://docs.python.org/3/library/importlib.html )

Max length for client ip address

People are talking about characters when one can compress an IP address into raw data.

So in principle, since we only use IPv4 (32bit) or IPv6 (128bit), that means you need at most 128 bits of space, or 128/8 = 16 bytes!

Which is much less than the suggested 39 bytes (assuming charset is ascii).

That said, you will have to decode and encode the IP address into/from the raw data, which in itself is a trivial thing to do (I've done it before, see PHP's ip2long() for 32-bit IPs).

Edit: inet_pton (and its opposite, inet_ntop()) does what you need, and works with both address types. But beware, on Windows it's available since PHP 5.3.

How do you uninstall a python package that was installed using distutils?

If this is for testing and/or development purposes, setuptools has a develop command that updates every time you make a change (so you don't have to uninstall and reinstall every time you make a change). And you can uninstall the package using this command as well.

If you do use this, anything that you declare as a script will be left behind as a lingering file.

How to open a new window on form submit

I generally use a small jQuery snippet globally to open any external links in a new tab / window. I've added the selector for a form for my own site and it works fine so far:

// URL target
    $('a[href*="//"]:not([href*="'+ location.hostname +'"]),form[action*="//"]:not([href*="'+ location.hostname +'"]').attr('target','_blank');

curl posting with header application/x-www-form-urlencoded

Try something like:

$post_data="dispnumber=567567567&extension=6";
$url="http://xxxxxxxx.xxx/xx/xx";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));   
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$result = curl_exec($ch);

echo $result;

Dealing with nginx 400 "The plain HTTP request was sent to HTTPS port" error

According to wikipedia article on status codes. Nginx has a custom error code when http traffic is sent to https port(error code 497)

And according to nginx docs on error_page, you can define a URI that will be shown for a specific error.
Thus we can create a uri that clients will be sent to when error code 497 is raised.

nginx.conf

#lets assume your IP address is 89.89.89.89 and also 
#that you want nginx to listen on port 7000 and your app is running on port 3000

server {
    listen 7000 ssl;
 
    ssl_certificate /path/to/ssl_certificate.cer;
    ssl_certificate_key /path/to/ssl_certificate_key.key;
    ssl_client_certificate /path/to/ssl_client_certificate.cer;

    error_page 497 301 =307 https://89.89.89.89:7000$request_uri;

    location / {
        proxy_pass http://89.89.89.89:3000/;

        proxy_pass_header Server;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Protocol $scheme;
    }
}

However if a client makes a request via any other method except a GET, that request will be turned into a GET. Thus to preserve the request method that the client came in via; we use error processing redirects as shown in nginx docs on error_page

And thats why we use the 301 =307 redirect.

Using the nginx.conf file shown here, we are able to have http and https listen in on the same port

Calling class staticmethod within the class body?

This is due to staticmethod being a descriptor and requires a class-level attribute fetch to exercise the descriptor protocol and get the true callable.

From the source code:

It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()); the instance is ignored except for its class.

But not directly from inside the class while it is being defined.

But as one commenter mentioned, this is not really a "Pythonic" design at all. Just use a module level function instead.

Store text file content line by line into array

You need to do something like this for your case:-

int i = 0;
while((str = in.readLine()) != null){
    arr[i] = str;
    i++;
}

But note that the arr should be declared properly, according to the number of entries in your file.

Suggestion:- Use a List instead(Look at @Kevin Bowersox post for that)

Better way to represent array in java properties file

I highly recommend using Apache Commons (http://commons.apache.org/configuration/). It has the ability to use an XML file as a configuration file. Using an XML structure makes it easy to represent arrays as lists of values rather than specially numbered properties.

How do I include inline JavaScript in Haml?

You can actually do what Chris Chalmers does in his answer, but you must make sure that HAML doesn't parse the JavaScript. This approach is actually useful when you need to use a different type than text/javascript, which is was I needed to do for MathJax.

You can use the plain filter to keep HAML from parsing the script and throwing an illegal nesting error:

%script{type: "text/x-mathjax-config"}
  :plain
    MathJax.Hub.Config({
      tex2jax: {
        inlineMath: [["$","$"],["\\(","\\)"]]
      }
    });

How do I use the JAVA_OPTS environment variable?

Just figured it out in Oracle Java the environmental variable is called: JAVA_TOOL_OPTIONS rather than JAVA_OPTS

Check if an array is empty or exists

in ts

 isArray(obj: any) 
{
    return Array.isArray(obj)
  }

in html

(photos == undefined || !(isArray(photos) && photos.length > 0) )

Cross-Origin Request Blocked

You have to placed this code in application.rb

config.action_dispatch.default_headers = {
        'Access-Control-Allow-Origin' => '*',
        'Access-Control-Request-Method' => %w{GET POST OPTIONS}.join(",")
}

How do you make a LinearLayout scrollable?

You need to place ScrollView as the first child of Layout file and now put your linearlayout inside it. Now, android will decide on the basis of content and device size available whether to show a scrollable or not.

Make sure linearlayout has no sibling because ScrollView can not have more than one child.

Angular CLI - Please add a @NgModule annotation when using latest

The problem is the import of ProjectsListComponent in your ProjectsModule. You should not import that, but add it to the export array, if you want to use it outside of your ProjectsModule.

Other issues are your project routes. You should add these to an exportable variable, otherwise it's not AOT compatible. And you should -never- import the BrowserModule anywhere else but in your AppModule. Use the CommonModule to get access to the *ngIf, *ngFor...etc directives:

@NgModule({
  declarations: [
     ProjectsListComponent
  ],
  imports: [
    CommonModule,
    RouterModule.forChild(ProjectRoutes)
  ],
  exports: [
     ProjectsListComponent
  ]
})

export class ProjectsModule {}

project.routes.ts

export const ProjectRoutes: Routes = [
      { path: 'projects', component: ProjectsListComponent }
]

Convert a bitmap into a byte array

Try the following:

MemoryStream stream = new MemoryStream();
Bitmap bitmap = new Bitmap();
bitmap.Save(stream, ImageFormat.Jpeg);

byte[] byteArray = stream.GetBuffer();

Make sure you are using:

System.Drawing & using System.Drawing.Imaging;

How can I round down a number in Javascript?

Rounding a number towards 0 can be done by subtracting its signed fractional part number % 1:

rounded = number - number % 1;

Like Math.floor (rounds towards -Infinity) this method is perfectly accurate.

There are differences in the handling of -0, +Infinity and -Infinity though:

Math.floor(-0) => -0
-0 - -0 % 1    => +0

Math.floor(Infinity)    => Infinity
Infinity - Infinity % 1 => NaN

Math.floor(-Infinity)     => -Infinity
-Infinity - -Infinity % 1 => NaN

"Default Activity Not Found" on Android Studio upgrade

Hope this answer helps somebody.

If you already have the <intent-filter> tag, just be sure that you are closing all tags correctly.

My error was that I close the <activity> tag just with a </> instead of </activity>.

Show current assembly instruction in GDB

Setting the following option:

set  disassemble-next-line on
show disassemble-next-line

Will give you results that look like this:

(gdb) stepi
0x000002ce in ResetISR () at startup_gcc.c:245
245 {
   0x000002cc <ResetISR+0>: 80 b5   push    {r7, lr}
=> 0x000002ce <ResetISR+2>: 82 b0   sub sp, #8
   0x000002d0 <ResetISR+4>: 00 af   add r7, sp, #0
(gdb) stepi
0x000002d0  245 {
   0x000002cc <ResetISR+0>: 80 b5   push    {r7, lr}
   0x000002ce <ResetISR+2>: 82 b0   sub sp, #8
=> 0x000002d0 <ResetISR+4>: 00 af   add r7, sp, #0