Programs & Examples On #Uibuilder

How to type a new line character in SQL Server Management Studio

You can prepare the text in notepad, and paste it into SSMS. SSMS will not display the newlines, but they are there, as you can verify with a select:

select *
from YourTable
where Col1 like '%' + char(10) + '%'

Get top 1 row of each group

I believe this can be done just like this. This might need some tweaking but you can just select the max from the group.

These answers are overkill..

SELECT
  d.DocumentID,
  MAX(d.Status),
  MAX(d1.DateCreated)
FROM DocumentStatusLogs d, DocumentStatusLogs d1
USING(DocumentID)
GROUP BY d.DocumentID
ORDER BY DateCreated DESC

How do you disable viewport zooming on Mobile Safari?

For the people looking for an iOS 10 solution, user-scaleable=no is disabled in Safari for iOS 10. The reason is that Apple is trying to improve accessibility by allowing people to zoom on web pages.

From release notes:

To improve accessibility on websites in Safari, users can now pinch-to-zoom even when a website sets user-scalable=no in the viewport.

So as far as I understand, we are sh** out of luck.

How do I check whether input string contains any spaces?

You can use this code to check whether the input string contains any spaces?

public static void main(String[]args)
{
    Scanner sc=new Scanner(System.in);
    System.out.println("enter the string...");
    String s1=sc.nextLine();
    int l=s1.length();
    int count=0;
    for(int i=0;i<l;i++)
    {
        char c=s1.charAt(i);
        if(c==' ')
        {
        System.out.println("spaces are in the position of "+i);
        System.out.println(count++);
        }
        else
        {
        System.out.println("no spaces are there");
    }
}

jQuery UI DatePicker - Change Date Format

Here complete code for date picker with date format (yy/mm/dd).

Copy link below and paste in head tag :

   <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>  
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>  
   <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script> 

   <script type="text/javascript">
       $(function() {
               $("#datepicker").datepicker({ dateFormat: "yy-mm-dd" }).val()
       });
   </script>

Copy below code and paste between body tag :

      Date: <input type="text" id="datepicker" size="30"/>    

If you would like two(2) input type text like Start Date and End Date then use this script and change date format.

   <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>  
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>  
   <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script> 

   <script type="text/javascript">
       $(function() {
               $("#startdate").datepicker({ dateFormat: "dd-mm-yy" }).val()
               $("#enddate").datepicker({ dateFormat: "dd-mm-yy" }).val()
       });

   </script>  

Two input text like :

      Start Date: <input type="text" id="startdate" size="30"/>    
      End Date: <input type="text" id="enddate" size="30"/>

What is the difference between Views and Materialized Views in Oracle?

A view uses a query to pull data from the underlying tables.

A materialized view is a table on disk that contains the result set of a query.

Materialized views are primarily used to increase application performance when it isn't feasible or desirable to use a standard view with indexes applied to it. Materialized views can be updated on a regular basis either through triggers or by using the ON COMMIT REFRESH option. This does require a few extra permissions, but it's nothing complex. ON COMMIT REFRESH has been in place since at least Oracle 10.

Hibernate Delete query

instead of using

session.delete(object)

use

getHibernateTemplate().delete(object)

In both place for select query and also for delete use getHibernateTemplate()

In select query you have to use DetachedCriteria or Criteria

Example for select query

List<foo> fooList = new ArrayList<foo>();
DetachedCriteria queryCriteria = DetachedCriteria.forClass(foo.class);
queryCriteria.add(Restrictions.eq("Column_name",restriction));
fooList = getHibernateTemplate().findByCriteria(queryCriteria);

In hibernate avoid use of session,here I am not sure but problem occurs just because of session use

Is there a command to undo git init?

You can just delete .git. Typically:

rm -rf .git

Then, recreate as the right user.

C++ getters/setters coding style

It tends to be a bad idea to make non-const fields public because it then becomes hard to force error checking constraints and/or add side-effects to value changes in the future.

In your case, you have a const field, so the above issues are not a problem. The main downside of making it a public field is that you're locking down the underlying implementation. For example, if in the future you wanted to change the internal representation to a C-string or a Unicode string, or something else, then you'd break all the client code. With a getter, you could convert to the legacy representation for existing clients while providing the newer functionality to new users via a new getter.

I'd still suggest having a getter method like the one you have placed above. This will maximize your future flexibility.

Regular vs Context Free Grammars

Basically regular grammar is a subset of context free grammar,but we can not say Every Context free grammar is a regular grammar. Mainly context free grammar is ambiguous and regular grammar may be ambiguous.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error

Near the top of the code with the Public Workshop(), I am assumeing this bit,

suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);


suitButton = new JCheckBox("Denim Jeans");
suitButton.setMnemonic(KeyEvent.VK_U);

should maybe be,

suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);


denimjeansButton = new JCheckBox("Denim Jeans");
denimjeansButton.setMnemonic(KeyEvent.VK_U);

How do I remove documents using Node.js Mongoose?

This worked for me, just try this:

const id = req.params.id;
      YourSchema
      .remove({_id: id})
      .exec()
      .then(result => {
        res.status(200).json({
          message: 'deleted',
          request: {
            type: 'POST',
            url: 'http://localhost:3000/yourroutes/'
          }
        })
      })
      .catch(err => {
        res.status(500).json({
          error: err
        })
      });

AWS S3 CLI - Could not connect to the endpoint URL

  1. Check the .aws directory under home directory. Windows: C:\Users<home-name>.aws Linux: ~/.aws

  2. Under this directory, you will find the config as well as credentials file. It will have the information from the aws configure that you may have run before. IF not, then

  3. Run aws configure Enter the access key - secret key - enter secret key region - (ap-southeast-1 or us-east-1 or any other regions) format - (json or leave it blank, it will pick up default values you may simply hit enter)

  4. From the Step 2, you should see the config file, open it, it should have the region. Please ensure there is region specified.

  5. You may now run the following command to list the buckets aws s3 ls It should work fine.

How do I generate sourcemaps when using babel and webpack?

Even same issue I faced, in browser it was showing compiled code. I have made below changes in webpack config file and it is working fine now.

 devtool: '#inline-source-map',
 debug: true,

and in loaders I kept babel-loader as first option

loaders: [
  {
    loader: "babel-loader",
    include: [path.resolve(__dirname, "src")]
  },
  { test: /\.js$/, exclude: [/app\/lib/, /node_modules/], loader: 'ng-annotate!babel' },
  { test: /\.html$/, loader: 'raw' },
  {
    test: /\.(jpe?g|png|gif|svg)$/i,
    loaders: [
      'file?hash=sha512&digest=hex&name=[hash].[ext]',
      'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
    ]
  },
  {test: /\.less$/, loader: "style!css!less"},
  { test: /\.styl$/, loader: 'style!css!stylus' },
  { test: /\.css$/, loader: 'style!css' }
]

How to set shape's opacity?

use this code below as progress.xml:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@android:id/background">
        <shape>
            <corners android:radius="5dip" />
            <gradient
                    android:startColor="#ff9d9e9d"
                    android:centerColor="#ff5a5d5a"
                    android:centerY="0.75"
                    android:endColor="#ff747674"
                    android:angle="270"
            />
        </shape>
    </item>

    <item android:id="@android:id/secondaryProgress">
        <clip>
            <shape>
                <solid android:color="#00000000" />
            </shape>
        </clip>
    </item>

    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <solid android:color="#00000000" />
            </shape>
        </clip>
    </item>

</layer-list>

where:

  • "progress" is current progress before the thumb and "secondaryProgress" is the progress after thumb.
  • color="#00000000" is a perfect transparency
  • NOTE: the file above is from default android res and is for 2.3.7, it is available on android sources at: frameworks/base/core/res/res/drawable/progress_horizontal.xml. For newer versions you must find the default drawable file for the seekbar corresponding to your android version.

after that use it in the layout containing the xml:

<SeekBar
    android:id="@+id/myseekbar"
    ...
    android:progressDrawable="@drawable/progress"
    />

you can also customize the thumb by using a custom icon seek_thumb.png:

android:thumb="@drawable/seek_thumb"

Angular.js directive dynamic templateURL

I had the same problem and I solved in a slightly different way from the others. I am using angular 1.4.4.

In my case, I have a shell template that creates a CSS Bootstrap panel:

<div class="class-container panel panel-info">
    <div class="panel-heading">
        <h3 class="panel-title">{{title}} </h3>
    </div>
    <div class="panel-body">
        <sp-panel-body panelbodytpl="{{panelbodytpl}}"></sp-panel-body>
    </div>
</div>

I want to include panel body templates depending on the route.

    angular.module('MyApp')
    .directive('spPanelBody', ['$compile', function($compile){
        return {
            restrict        : 'E',
            scope : true,
            link: function (scope, element, attrs) {
                scope.data = angular.fromJson(scope.data);
                element.append($compile('<ng-include src="\'' + scope.panelbodytpl + '\'"></ng-include>')(scope));
            }
        }
    }]);

I then have the following template included when the route is #/students:

<div class="students-wrapper">
    <div ng-controller="StudentsIndexController as studentCtrl" class="row">
        <div ng-repeat="student in studentCtrl.students" class="col-sm-6 col-md-4 col-lg-3">
            <sp-panel 
            title="{{student.firstName}} {{student.middleName}} {{student.lastName}}"
            panelbodytpl="{{'/student/panel-body.html'}}"
            data="{{student}}"
            ></sp-panel>
        </div>
    </div>
</div>

The panel-body.html template as follows:

Date of Birth: {{data.dob * 1000 | date : 'dd MMM yyyy'}}

Sample data in the case someone wants to have a go:

var student = {
    'id'            : 1,
    'firstName'     : 'John',
    'middleName'    : '',
    'lastName'      : 'Smith',
    'dob'           : 1130799600,
    'current-class' : 5
}

ls command: how can I get a recursive full-path listing, one line per file?

Use find:

find .
find /home/dreftymac

If you want files only (omit directories, devices, etc):

find . -type f
find /home/dreftymac -type f

Can anybody tell me details about hs_err_pid.log file generated when Tomcat crashes?

A very very good document regarding this topic is Troubleshooting Guide for Java from (originally) Sun. See the chapter "Troubleshooting System Crashes" for information about hs_err_pid* Files.

See Appendix C - Fatal Error Log

Per the guide, by default the file will be created in the working directory of the process if possible, or in the system temporary directory otherwise. A specific location can be chosen by passing in the -XX:ErrorFile product flag. It says:

If the -XX:ErrorFile= file flag is not specified, the system attempts to create the file in the working directory of the process. In the event that the file cannot be created in the working directory (insufficient space, permission problem, or other issue), the file is created in the temporary directory for the operating system.

AlertDialog styling - how to change style (color) of title, message, etc

Remove the panel background

 <item name="android:windowBackground">@color/transparent_color</item> 
 <color name="transparent_color">#00000000</color>

This is Mystyle:

 <style name="ThemeDialogCustom">
    <item name="android:windowFrame">@null</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
    <item name="android:windowBackground">@color/transparent_color</item>
    <item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
    <item name="android:colorBackgroundCacheHint">@null</item>
</style>

Which i have added to the constructor.

Add textColor :

<item name="android:textColor">#ff0000</item>

Java Read Large Text File With 70million line of text

This article is a great way to start.

Also, you need to create test cases in which you read first 10k(or something else, but shouldn't be too small) lines and calculate the reading times accordingly.

Threading might be a good way to go, but it's important that we know what you will be doing with the data.

Another thing to be considered is, how you will store that size of data.

PHP Constants Containing Arrays?

I know it's a bit old question, but here is my solution:

<?php
class Constant {

    private $data = [];

    public function define($constant, $value) {
        if (!isset($this->data[$constant])) {
            $this->data[$constant] = $value;
        } else {
            trigger_error("Cannot redefine constant $constant", E_USER_WARNING);
        }
    }

    public function __get($constant) {
        if (isset($this->data[$constant])) {
            return $this->data[$constant];
        } else {
            trigger_error("Use of undefined constant $constant - assumed '$constant'", E_USER_NOTICE);
            return $constant;
        }
    }

    public function __set($constant,$value) {
        $this->define($constant, $value);
    }

}
$const = new Constant;

I defined it because I needed to store objects and arrays in constants so I installed also runkit to php so I could make the $const variable superglobal.

You can use it as $const->define("my_constant",array("my","values")); or just $const->my_constant = array("my","values");

To get the value just simply call $const->my_constant;

what is the differences between sql server authentication and windows authentication..?

Authentication is the process of confirming a user or computer’s identity. The process normally consists of four steps: The user makes a claim of identity, usually by providing a username. For example, I might make this claim by telling a database that my username is “mchapple”. The system challenges the user to prove his or her identity. The most common challenge is a request for a password. The user responds to the challenge by providing the requested proof. In this example, I would provide the database with my password The system verifies that the user has provided acceptable proof by, for example, checking the password against a local password database or using a centralized authentication server

\n or \n in php echo not print

Better use PHP_EOL ("End Of Line") instead. It's cross-platform.

E.g.:

$unit1 = 'paragrahp1';
$unit2 = 'paragrahp2';
echo '<p>' . $unit1 . '</p>' . PHP_EOL;
echo '<p>' . $unit2 . '</p>';

Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable

Another clue: I was using JSF, and added mvn dependencies: com.sun.faces jsf-api 2.2.11

    <dependency>
        <groupId>com.sun.faces</groupId>
        <artifactId>jsf-impl</artifactId>
        <version>2.2.11</version>
    </dependency>

Then, I tried to change to Primefaces, and add primefaces dependency:

<dependency>
    <groupId>org.primefaces</groupId>
    <artifactId>primefaces</artifactId>
    <version>6.0</version>
</dependency>

I changed my xhtml from h: to p:, adding xmlns:p="http://primefaces.org/ui to the template. Only with JSF the proyect was running ok, and the managedbean was reached ok. When I add Primefaces I was getting the unreachable object (javax.el.propertynotfoundexception). The problem was that JSF was generating the ManagedBean, not Primefaces, and I was asking primefaces for the object. I had to delete jsf-impl from my .pom, clean and install the proyect. All went ok from this point. Hope that helps.

Converting pfx to pem using openssl

Another perspective for doing it on Linux... here is how to do it so that the resulting single file contains the decrypted private key so that something like HAProxy can use it without prompting you for passphrase.

openssl pkcs12 -in file.pfx -out file.pem -nodes

Then you can configure HAProxy to use the file.pem file.


This is an EDIT from previous version where I had these multiple steps until I realized the -nodes option just simply bypasses the private key encryption. But I'm leaving it here as it may just help with teaching.

openssl pkcs12 -in file.pfx -out file.nokey.pem -nokeys
openssl pkcs12 -in file.pfx -out file.withkey.pem
openssl rsa -in file.withkey.pem -out file.key
cat file.nokey.pem file.key > file.combo.pem
  1. The 1st step prompts you for the password to open the PFX.
  2. The 2nd step prompts you for that plus also to make up a passphrase for the key.
  3. The 3rd step prompts you to enter the passphrase you just made up to store decrypted.
  4. The 4th puts it all together into 1 file.

Then you can configure HAProxy to use the file.combo.pem file.

The reason why you need 2 separate steps where you indicate a file with the key and another without the key, is because if you have a file which has both the encrypted and decrypted key, something like HAProxy still prompts you to type in the passphrase when it uses it.

replace special characters in a string python

str.replace is the wrong function for what you want to do (apart from it being used incorrectly). You want to replace any character of a set with a space, not the whole set with a single space (the latter is what replace does). You can use translate like this:

removeSpecialChars = z.translate ({ord(c): " " for c in "!@#$%^&*()[]{};:,./<>?\|`~-=_+"})

This creates a mapping which maps every character in your list of special characters to a space, then calls translate() on the string, replacing every single character in the set of special characters with a space.

Slide up/down effect with ng-show and ng-animate

This can actually be done in CSS and very minimal JS just by adding a CSS class (don't set styles directly in JS!) with e.g. a ng-clickevent. The principle is that one can't animate height: 0; to height: auto; but this can be tricked by animating the max-height property. The container will expand to it's "auto-height" value when .foo-open is set - no need for fixed height or positioning.

.foo {
    max-height: 0;
}

.foo--open {
    max-height: 1000px; /* some arbitrary big value */
    transition: ...
}

see this fiddle by the excellent Lea Verou

As a concern raised in the comments, note that while this animation works perfectly with linear easing, any exponential easing will produce a behaviour different from what could be expected - due to the fact that the animated property is max-height and not height itself; specifically, only the height fraction of the easing curve of max-height will be displayed.

TypeError: Can't convert 'int' object to str implicitly

You cannot concatenate a string with an int. You would need to convert your int to a string using the str function, or use formatting to format your output.

Change: -

print("Ok. Your balance is now at " + balanceAfterStrength + " skill points.")

to: -

print("Ok. Your balance is now at {} skill points.".format(balanceAfterStrength))

or: -

print("Ok. Your balance is now at " + str(balanceAfterStrength) + " skill points.")

or as per the comment, use , to pass different strings to your print function, rather than concatenating using +: -

print("Ok. Your balance is now at ", balanceAfterStrength, " skill points.")

Trigger back-button functionality on button click in Android

With this code i solved my problem.For back button paste these two line code.Hope this will help you.

Only paste this code on button click

super.onBackPressed();

Example:-

Button backButton = (Button)this.findViewById(R.id.back);
backButton.setOnClickListener(new OnClickListener() {
  @Override
  public void onClick(View v) {
    super.onBackPressed();
  }
});

How to fill Dataset with multiple tables?

protected void Page_Load(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection("data source=.;uid=sa;pwd=123;database=shop");
    //SqlCommand cmd = new SqlCommand("select * from tblemployees", con);
    //SqlCommand cmd1 = new SqlCommand("select * from tblproducts", con);
    //SqlDataAdapter da = new SqlDataAdapter();

    //DataSet ds = new DataSet();
    //ds.Tables.Add("emp");
    //ds.Tables.Add("products");
    //da.SelectCommand = cmd;
    //da.Fill(ds.Tables["emp"]);
    //da.SelectCommand = cmd1;

    //da.Fill(ds.Tables["products"]);
    SqlDataAdapter da = new SqlDataAdapter("select * from tblemployees", con);
    DataSet ds = new DataSet();
    da.Fill(ds, "em");
    da = new SqlDataAdapter("select * from tblproducts", con);
    da.Fill(ds, "prod");

    GridView1.DataSource = ds.Tables["em"];
    GridView1.DataBind();
    GridView2.DataSource = ds.Tables["prod"];
    GridView2.DataBind();
}

Moving items around in an ArrayList

To move up, remove and then add.

To remove - ArrayList.remove and assign the returned object to a variable
Then add this object back at the required index -ArrayList.add(int index, E element)

http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html#add(int, E)

How to check if DST (Daylight Saving Time) is in effect, and if so, the offset?

Your're close but a little off. You never need to calculate your own time as it is a result of your own clock. It can detect if you are using daylight saving time in your location but not for a remote location produced by the offset:

newDateWithOffset = new Date(utc + (3600000*(offset)));

This will still be wrong and off an hour if they are in DST. You need for a remote time account if they are currently inside their DST or not and adjust accordingly. try calculating this and change your clock to - lets say 2/1/2015 and reset the clock back an hour as if outside DST. Then calculate for an offset for a place that should still be 2 hours behind. It will show an hour ahead of the two hour window. You would still need to account for the hour and adjust. I did it for NY and Denver and always go the incorrect (hour ahead) in Denver.

Split string to equal length substrings in Java

I asked @Alan Moore in a comment to the accepted solution how strings with newlines could be handled. He suggested using DOTALL.

Using his suggestion I created a small sample of how that works:

public void regexDotAllExample() throws UnsupportedEncodingException {
    final String input = "The\nquick\nbrown\r\nfox\rjumps";
    final String regex = "(?<=\\G.{4})";

    Pattern splitByLengthPattern;
    String[] split;

    splitByLengthPattern = Pattern.compile(regex);
    split = splitByLengthPattern.split(input);
    System.out.println("---- Without DOTALL ----");
    for (int i = 0; i < split.length; i++) {
        byte[] s = split[i].getBytes("utf-8");
        System.out.println("[Idx: "+i+", length: "+s.length+"] - " + s);
    }
    /* Output is a single entry longer than the desired split size:
    ---- Without DOTALL ----
    [Idx: 0, length: 26] - [B@17cdc4a5
     */


    //DOTALL suggested in Alan Moores comment on SO: https://stackoverflow.com/a/3761521/1237974
    splitByLengthPattern = Pattern.compile(regex, Pattern.DOTALL);
    split = splitByLengthPattern.split(input);
    System.out.println("---- With DOTALL ----");
    for (int i = 0; i < split.length; i++) {
        byte[] s = split[i].getBytes("utf-8");
        System.out.println("[Idx: "+i+", length: "+s.length+"] - " + s);
    }
    /* Output is as desired 7 entries with each entry having a max length of 4:
    ---- With DOTALL ----
    [Idx: 0, length: 4] - [B@77b22abc
    [Idx: 1, length: 4] - [B@5213da08
    [Idx: 2, length: 4] - [B@154f6d51
    [Idx: 3, length: 4] - [B@1191ebc5
    [Idx: 4, length: 4] - [B@30ddb86
    [Idx: 5, length: 4] - [B@2c73bfb
    [Idx: 6, length: 2] - [B@6632dd29
     */

}

But I like @Jon Skeets solution in https://stackoverflow.com/a/3760193/1237974 also. For maintainability in larger projects where not everyone are equally experienced in Regular expressions I would probably use Jons solution.

Delayed rendering of React components

render the child components not at once but after some delay .

The question says delay render but if it is ok to render but hide...

You can render the components from a map straight away but use css animation to delay them being shown.

@keyframes Jumpin {
 0% { opacity: 0; }
 50% { opacity: 0; }
 100% { opacity: 1; }
}
// Sass loop code
@for $i from 2 through 10 {
 .div .div:nth-child(#{$i}) {
  animation: Jumpin #{$i * 0.35}s cubic-bezier(.9,.03,.69,.22);
 }
}

The child divs now follow each other with a slight delay.

jQuery or JavaScript auto click

$(document).ready(function(){ 
  $('#some-id').trigger('click'); 
});

did the trick.

Adding three months to a date in PHP

Tchoupi's answer can be made a tad less verbose by concatenating the argument for strtotime() as follows:

$effectiveDate = date('Y-m-d', strtotime($effectiveDate . "+3 months") );

(This relies on magic implementation details, but you can always go have a look at them if you're rightly mistrustful.)

CodeIgniter: Unable to connect to your database server using the provided settings Error Message

In your configurations, specify the port number your database is on. You can find the port number at the top left corner of phpMyAdmin. It would look something like this

const DB_HOST = 'localhost:3308';

What is cardinality in Databases?

Definition: We have tables in database. In relational database, we have relations among the tables. These relations can be one-to-one, one-to-many or many-to-many. These relations are called 'cardinality'.

Significant of cardinality:

Many relational databases have been designed following stick business rules.When you design the database we define the cardinality based on the business rules. But every objects has its own nature as well.

When you define cardinality among object you have to consider all these things to define the correct cardinality.

How to append data to a json file?

json might not be the best choice for on-disk formats; The trouble it has with appending data is a good example of why this might be. Specifically, json objects have a syntax that means the whole object must be read and parsed in order to understand any part of it.

Fortunately, there are lots of other options. A particularly simple one is CSV; which is supported well by python's standard library. The biggest downside is that it only works well for text; it requires additional action on the part of the programmer to convert the values to numbers or other formats, if needed.

Another option which does not have this limitation is to use a sqlite database, which also has built-in support in python. This would probably be a bigger departure from the code you already have, but it more naturally supports the 'modify a little bit' model you are apparently trying to build.

How to verify if $_GET exists?

Please try it:

if(isset($_GET['id']) && !empty($_GET['id'])){
   echo $_GET["id"];
 }

Get Root Directory Path of a PHP project

For PHP >= 5.3.0 try

PHP magic constants.

__DIR__

And make your path relative.

For PHP < 5.3.0 try

dirname(__FILE__)

Node.js request CERT_HAS_EXPIRED

Try to temporarily modify request.js and harcode everywhere rejectUnauthorized = true, but it would be better to get the certificate extended as a long-term solution.

How to parse XML using vba

Add reference Project->References Microsoft XML, 6.0 and you can use example code:

    Dim xml As String

    xml = "<root><person><name>Me </name> </person> <person> <name>No Name </name></person></root> "
    Dim oXml As MSXML2.DOMDocument60
    Set oXml = New MSXML2.DOMDocument60
    oXml.loadXML xml
    Dim oSeqNodes, oSeqNode As IXMLDOMNode

    Set oSeqNodes = oXml.selectNodes("//root/person")
    If oSeqNodes.length = 0 Then
       'show some message
    Else
        For Each oSeqNode In oSeqNodes
             Debug.Print oSeqNode.selectSingleNode("name").Text
        Next
    End If 

be careful with xml node //Root/Person is not same with //root/person, also selectSingleNode("Name").text is not same with selectSingleNode("name").text

Export tables to an excel spreadsheet in same directory

For people who find this via search engines, you do not need VBA. You can just:

1.) select the query or table with your mouse
2.) click export data from the ribbon
3.) click excel from the export subgroup
4.) follow the wizard to select the output file and location.

Understanding [TCP ACKed unseen segment] [TCP Previous segment not captured]

Another cause of "TCP ACKed Unseen" is the number of packets that may get dropped in a capture. If I run an unfiltered capture for all traffic on a busy interface, I will sometimes see a large number of 'dropped' packets after stopping tshark.

On the last capture I did when I saw this, I had 2893204 packets captured, but once I hit Ctrl-C, I got a 87581 packets dropped message. Thats a 3% loss, so when wireshark opens the capture, its likely to be missing packets and report "unseen" packets.

As I mentioned, I captured a really busy interface with no capture filter, so tshark had to sort all packets, when I use a capture filter to remove some of the noise, I no longer get the error.

How to handle a lost KeyStore password in Android?

Fortunately, I found my lost password along with the keystore path and alias name from my Android studio logs.

if you are running linux / Unix based machines.

Navigate to Library Logs directory

cd ~/Library/Logs/

in there if you remember your android studio version which you used to build the last release APK. Navigate to that Directory

ex : cd AndroidStudio1.5/

In there you will find the log files. in any of the log files (idea.log) you will find your keystore credentials

example

-Pandroid.injected.signing.store.file=/Users/myuserid/AndroidStudioProjects/keystore/keystore.jks, 
-Pandroid.injected.signing.store.password=mystorepassword, 
-Pandroid.injected.signing.key.alias=myandroidkey, 
-Pandroid.injected.signing.key.password=mykeypassword,

I hope this helps for Android Studio users

How do you count the lines of code in a Visual Studio solution?

You can use the Visual Studio Code Metrics PowerTool 10.0. It's a command-line utility that calculates a few metrics on managed code for you (including lines of code). You can get a VS 2010 plugin that brings the tool into Visual Studio, and makes it as quick as selecting the menu item and clicking "Analyze Solution."

Curl : connection refused

127.0.0.1 restricts access on every interface on port 8000 except development computer. change it to 0.0.0.0:8000 this will allow connection from curl.

How to capture the browser window close event?

Try this also

window.onbeforeunload = function ()
{       
    if (pasteEditorChange) {
        var btn = confirm('Do You Want to Save the Changess?');
           if(btn === true ){
               SavetoEdit();//your function call
           }
           else{
                windowClose();//your function call
           }
    }  else { 
        windowClose();//your function call
    }
};

Select rows having 2 columns equal value

select t.* from table t
    join (
        select C2, C3, C4
        from table
        group by C2, C3, C4
        having count(*) > 1
    ) t2
    using (C2, C3, C4);

Groovy - How to compare the string?

This should be an answer

str2.equals( str )

If you want to ignore case

str2.equalsIgnoreCase( str )

How to make a button redirect to another page using jQuery or just Javascript

In your html, you can add data attribute to your button:

<button type="submit" class="mybtn" data-target="/search.html">Search</button>

Then you can use jQuery to change the url:

$('.mybtn').on('click', function(event) {
    event.preventDefault(); 
    var url = $(this).data('target');
    location.replace(url);
});

Hope this helps

Can I simultaneously declare and assign a variable in VBA?

There is no shorthand in VBA unfortunately, The closest you will get is a purely visual thing using the : continuation character if you want it on one line for readability;

Dim clientToTest As String:  clientToTest = clientsToTest(i)
Dim clientString As Variant: clientString = Split(clientToTest)

Hint (summary of other answers/comments): Works with objects too (Excel 2010):

Dim ws  As Worksheet: Set ws = ActiveWorkbook.Worksheets("Sheet1")
Dim ws2 As New Worksheet: ws2.Name = "test"

Get the size of a 2D array

In Java, 2D arrays are really arrays of arrays with possibly different lengths (there are no guarantees that in 2D arrays that the 2nd dimension arrays all be the same length)

You can get the length of any 2nd dimension array as z[n].length where 0 <= n < z.length.

If you're treating your 2D array as a matrix, you can simply get z.length and z[0].length, but note that you might be making an assumption that for each array in the 2nd dimension that the length is the same (for some programs this might be a reasonable assumption).

How to install crontab on Centos

As seen in Install crontab on CentOS, the crontab package in CentOS is vixie-cron. Hence, do install it with:

yum install vixie-cron

And then start it with:

service crond start

To make it persistent, so that it starts on boot, use:

chkconfig crond on

On CentOS 7 you need to use cronie:

yum install cronie

On CentOS 6 you can install vixie-cron, but the real package is cronie:

yum install vixie-cron

and

yum install cronie

In both cases you get the same output:

.../...
==================================================================
 Package         Arch       Version         Repository      Size
==================================================================
Installing:
 cronie          x86_64     1.4.4-12.el6    base             73 k
Installing for dependencies:
 cronie-anacron  x86_64     1.4.4-12.el6    base             30 k
 crontabs        noarch     1.10-33.el6     base             10 k
 exim            x86_64     4.72-6.el6      epel            1.2 M

Transaction Summary
==================================================================
Install       4 Package(s)

CSS to make table 100% of max-width

You need to use:

    table{
        width:100%;
        table-layout: fixed;
        overflow-wrap: break-word;
    }

Demo

3-dimensional array in numpy

As much as people like to say "order doesn't matter its just convention" this breaks down when entering cross domain interfaces, IE transfer from C ordering to Fortran ordering or some other ordering scheme. There, precisely how your data is layed out and how shape is represented in numpy is very important.

By default, numpy uses C ordering, which means contiguous elements in memory are the elements stored in rows. You can also do FORTRAN ordering ("F"), this instead orders elements based on columns, indexing contiguous elements.

Numpy's shape further has its own order in which it displays the shape. In numpy, shape is largest stride first, ie, in a 3d vector, it would be the least contiguous dimension, Z, or pages, 3rd dim etc... So when executing:

np.zeros((2,3,4)).shape

you will get

(2,3,4)

which is actually (frames, rows, columns). doing np.zeros((2,2,3,4)).shape instead would mean (metaframs, frames, rows, columns). This makes more sense when you think of creating multidimensional arrays in C like langauges. For C++, creating a non contiguously defined 4D array results in an array [ of arrays [ of arrays [ of elements ]]]. This forces you to de reference the first array that holds all the other arrays (4th dimension) then the same all the way down (3rd, 2nd, 1st) resulting in syntax like:

double element = array4d[w][z][y][x];

In fortran, this indexed ordering is reversed (x is instead first array4d[x][y][z][w]), most contiguous to least contiguous and in matlab, it gets all weird.

Matlab tried to preserve both mathematical default ordering (row, column) but also use column major internally for libraries, and not follow C convention of dimensional ordering. In matlab, you order this way:

double element = array4d[y][x][z][w];

which deifies all convention and creates weird situations where you are sometimes indexing as if row ordered and sometimes column ordered (such as with matrix creation).

In reality, Matlab is the unintuitive one, not Numpy.

Checking password match while typing

$(function() {
    $("#txtConfirmPassword").keyup(function() {
        var password = $("#txtNewPassword").val();
        $("#divCheckPasswordMatch").html(password == $(this).val()
            ? "Passwords match."
            : "Passwords do not match!"
        );
    });
});?

Demo here

Where is android_sdk_root? and how do I set it.?

For macOS with zshrc:

ANDROID_HOME is depreciated, use ANDROID_SDK_ROOT instead

  1. Ensure that Android Build Tools is installed. Check if it exists in your File Directory
  2. Get the path to your SDK. Usually it is /Users/<USER>/Library/Android/sdk
  3. Add ANDROID_SDK_ROOT as a path to your Environment variables: echo 'export ANDROID_SDK_ROOT=/Users/<USER>/Library/Android/sdk' >> ~/.zshenv
  4. Apply the changes with source ~/.zshrc
  5. Check if it was saved by ...
    • ... checking the specific environment variable echo $ANDROID_SDK_ROOT
    • ... checking the complete list of environment variables on your system env

You can apply this process to every environment variable beeing installed on your macOS system. It took me a while to comprehend it for myself

Javascript change date into format of (dd/mm/yyyy)

This will ensure you get a two-digit day and month.

function formattedDate(d = new Date) {
  let month = String(d.getMonth() + 1);
  let day = String(d.getDate());
  const year = String(d.getFullYear());

  if (month.length < 2) month = '0' + month;
  if (day.length < 2) day = '0' + day;

  return `${day}/${month}/${year}`;
}

Or terser:

function formattedDate(d = new Date) {
  return [d.getDate(), d.getMonth()+1, d.getFullYear()]
      .map(n => n < 10 ? `0${n}` : `${n}`).join('/');
}

Entity Framework Core: A second operation started on this context before a previous operation completed

I faced the same issue but the reason was none of the ones listed above. I created a task, created a scope inside the task and asked the container to obtain a service. That worked fine but then I used a second service inside the task and I forgot to also asked for it to the new scope. Because of that, the 2nd service was using a DbContext that was already disposed.

Task task = Task.Run(() =>
    {
        using (var scope = serviceScopeFactory.CreateScope())
        {
            var otherOfferService = scope.ServiceProvider.GetService<IOfferService>();
            // everything was ok here. then I did: 
            productService.DoSomething(); // (from the main scope) and this failed because the db context associated to that service was already disposed.
            ...
        }
    }

I should have done this:

var otherProductService = scope.ServiceProvider.GetService<IProductService>();
otherProductService.DoSomething();

Converting data frame column from character to numeric

If we need only one column to be numeric

yyz$b <- as.numeric(as.character(yyz$b))

But, if all the columns needs to changed to numeric, use lapply to loop over the columns and convert to numeric by first converting it to character class as the columns were factor.

yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))

Both the columns in the OP's post are factor because of the string "n/a". This could be easily avoided while reading the file using na.strings = "n/a" in the read.table/read.csv or if we are using data.frame, we can have character columns with stringsAsFactors=FALSE (the default is stringsAsFactors=TRUE)


Regarding the usage of apply, it converts the dataset to matrix and matrix can hold only a single class. To check the class, we need

lapply(yyz, class)

Or

sapply(yyz, class)

Or check

str(yyz)

How to get first and last day of previous month (with timestamp) in SQL Server

I have used the following logic in SSRS reports.

BUS_DATE = 17-09-2013

X=DATEADD(MONTH,-1,BUS_DATE) = 17-08-2013

Y=DAY(BUS_DATE)=17

first_date = DATEADD(DAY,-Y+1,X)=01-08-2013

last_date  = DATEADD(DAY,-Y,BUS_DATE)=31-08-2013

What does "export" do in shell programming?

Exported variables such as $HOME and $PATH are available to (inherited by) other programs run by the shell that exports them (and the programs run by those other programs, and so on) as environment variables. Regular (non-exported) variables are not available to other programs.

$ env | grep '^variable='
$                                 # No environment variable called variable
$ variable=Hello                  # Create local (non-exported) variable with value
$ env | grep '^variable='
$                                 # Still no environment variable called variable
$ export variable                 # Mark variable for export to child processes
$ env | grep '^variable='
variable=Hello
$
$ export other_variable=Goodbye   # create and initialize exported variable
$ env | grep '^other_variable='
other_variable=Goodbye
$

For more information, see the entry for the export builtin in the GNU Bash manual, and also the sections on command execution environment and environment.

Note that non-exported variables will be available to subshells run via ( ... ) and similar notations because those subshells are direct clones of the main shell:

$ othervar=present
$ (echo $othervar; echo $variable; variable=elephant; echo $variable)
present
Hello
elephant
$ echo $variable
Hello
$

The subshell can change its own copy of any variable, exported or not, and may affect the values seen by the processes it runs, but the subshell's changes cannot affect the variable in the parent shell, of course.

Some information about subshells can be found under command grouping and command execution environment in the Bash manual.

docker cannot start on windows

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

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

2) Go to settings > Reset

3) Reset to factory defaults

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

How do I use setsockopt(SO_REUSEADDR)?

After :

sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) 
    error("ERROR opening socket");

You can add (with standard C99 compound literal support) :

if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int)) < 0)
    error("setsockopt(SO_REUSEADDR) failed");

Or :

int enable = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0)
    error("setsockopt(SO_REUSEADDR) failed");

How to see JavaDoc in IntelliJ IDEA?

Go to Settings -> Editor -> General then enable Show quick documentation on mouse move

Multidimensional arrays in Swift

Your problem may have been due to a deficiency in an earlier version of Swift or of the Xcode Beta. Working with Xcode Version 6.0 (6A279r) on August 21, 2014, your code works as expected with this output:

column: 0 row: 0 value:1.0
column: 0 row: 1 value:4.0
column: 0 row: 2 value:7.0
column: 1 row: 0 value:2.0
column: 1 row: 1 value:5.0
column: 1 row: 2 value:8.0
column: 2 row: 0 value:3.0
column: 2 row: 1 value:6.0
column: 2 row: 2 value:9.0

I just copied and pasted your code into a Swift playground and defined two constants:

let NumColumns = 3, NumRows = 3

How to get a cross-origin resource sharing (CORS) post request working

This is a summary of what worked for me:

Define a new function (wrapped $.ajax to simplify):

jQuery.postCORS = function(url, data, func) {
  if(func == undefined) func = function(){};
  return $.ajax({
    type: 'POST', 
    url: url, 
    data: data, 
    dataType: 'json', 
    contentType: 'application/x-www-form-urlencoded', 
    xhrFields: { withCredentials: true }, 
    success: function(res) { func(res) }, 
    error: function() { 
            func({}) 
    }
  });
}

Usage:

$.postCORS("https://example.com/service.json",{ x : 1 },function(obj){
      if(obj.ok) {
           ...
      }
});

Also works with .done,.fail,etc:

$.postCORS("https://example.com/service.json",{ x : 1 }).done(function(obj){
      if(obj.ok) {
           ...
      }
}).fail(function(){
    alert("Error!");
});

Server side (in this case where example.com is hosted), set these headers (added some sample code in PHP):

header('Access-Control-Allow-Origin: https://not-example.com');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 604800');
header("Content-type: application/json");
$array = array("ok" => $_POST["x"]);
echo json_encode($array);

This is the only way I know to truly POST cross-domain from JS.

JSONP converts the POST into GET which may display sensitive information at server logs.

Bootstrap modal: close current, open new

Using click function:

$('.btn-editUser').on('click', function(){
    $('#viewUser').modal('hide'); // hides modal with id viewUser 
    $('#editUser').modal('show'); // display modal with id editUser
});

Heads up:

Make sure that the one you want to show is an independent modal.

List of Java class file format major version numbers?

I found a list of Java class file versions on the Wikipedia page that describes the class file format:

http://en.wikipedia.org/wiki/Java_class_file#General_layout

Under byte offset 6 & 7, the versions are listed with which Java VM they correspond to.

How can I print the contents of an array horizontally?

foreach(var item in array)
Console.Write(item.ToString() + "\t");

Positioning background image, adding padding

this is actually pretty easily done. You're almost there, doing what you've done with background-position: right center;. What is actually needed in this case is something very much like that. Let's convert these to percentages. We know that center=50%, so that's easy enough. Now, in order to get the padding you wanted, you need to position the background like so: background-position: 99% 50%.

The second, and more effective way of going about this, is to use the same background-position idea, and just use background-position: 400px (width of parent) 50%;. Of course, this method requires a static width, but will give you the same thing every time.

Method 1 (99% 50%)
Method 2 (400px 50%)

How to redirect 404 errors to a page in ExpressJS?

You can put a middleware at the last position that throws a NotFound error,
or even renders the 404 page directly:

app.use(function(req,res){
    res.status(404).render('404.jade');
});

Conda uninstall one package and one package only

You can use conda remove --force.

The documentation says:

--force               Forces removal of a package without removing packages
                      that depend on it. Using this option will usually
                      leave your environment in a broken and inconsistent
                      state

How to check if a view controller is presented modally or pushed on a navigation stack?

In Swift:

Add a flag to test if it's a modal by the class type:

// MARK: - UIViewController implementation

extension UIViewController {

    var isModal: Bool {

        let presentingIsModal = presentingViewController != nil
        let presentingIsNavigation = navigationController?.presentingViewController?.presentedViewController == navigationController
        let presentingIsTabBar = tabBarController?.presentingViewController is UITabBarController

        return presentingIsModal || presentingIsNavigation || presentingIsTabBar
    }
}

get name of a variable or parameter

Pre C# 6.0 solution

You can use this to get a name of any provided member:

public static class MemberInfoGetting
{
    public static string GetMemberName<T>(Expression<Func<T>> memberExpression)
    {
        MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
        return expressionBody.Member.Name;
    }
}

To get name of a variable:

string testVariable = "value";
string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => testVariable);

To get name of a parameter:

public class TestClass
{
    public void TestMethod(string param1, string param2)
    {
        string nameOfParam1 = MemberInfoGetting.GetMemberName(() => param1);
    }
}

C# 6.0 and higher solution

You can use the nameof operator for parameters, variables and properties alike:

string testVariable = "value";
string nameOfTestVariable = nameof(testVariable);

Using ffmpeg to encode a high quality video

You need to specify the -vb option to increase the video bitrate, otherwise you get the default which produces smaller videos but with more artifacts.

Try something like this:

ffmpeg -r 25 -i %4d.png -vb 20M myvideo.mpg

How to pass values arguments to modal.show() function in Bootstrap

You could do it like this:

<a class="btn btn-primary announce" data-toggle="modal" data-id="107" >Announce</a>

Then use jQuery to bind the click and send the Announce data-id as the value in the modals #cafeId:

$(document).ready(function(){
   $(".announce").click(function(){ // Click to only happen on announce links
     $("#cafeId").val($(this).data('id'));
     $('#createFormId').modal('show');
   });
});

Difference between [routerLink] and routerLink

You'll see this in all the directives:

When you use brackets, it means you're passing a bindable property (a variable).

  <a [routerLink]="routerLinkVariable"></a>

So this variable (routerLinkVariable) could be defined inside your class and it should have a value like below:

export class myComponent {

    public routerLinkVariable = "/home"; // the value of the variable is string!

But with variables, you have the opportunity to make it dynamic right?

export class myComponent {

    public routerLinkVariable = "/home"; // the value of the variable is string!


    updateRouterLinkVariable(){

        this.routerLinkVariable = '/about';
    }

Where as without brackets you're passing string only and you can't change it, it's hard coded and it'll be like that throughout your app.

<a routerLink="/home"></a>

UPDATE :

The other speciality about using brackets specifically for routerLink is that you can pass dynamic parameters to the link you're navigating to:

So adding a new variable

export class myComponent {
        private dynamicParameter = '129';
        public routerLinkVariable = "/home"; 

Updating the [routerLink]

  <a [routerLink]="[routerLinkVariable,dynamicParameter]"></a>

When you want to click on this link, it would become:

  <a href="/home/129"></a>

Deck of cards JAVA

There is a lot of error in your program.

  1. Calculation of index. I think it should be Math.random()%deck.length

  2. In the display of card. According to me, you should make a class of card which has rank suit and make the array of that class type

If you want I can give you the Complete structure of that but it is better if u make it by yourself

Download multiple files with a single action

To solve this, I created a JS library to stream multiple files directly into a zip on the client-side. The main unique feature is that it has no size limits from memory (everything is streamed) nor zip format (it uses zip64 if the contents are more than 4GB).

Since it doesn't do compression, it is also very performant.

Find "downzip" it on npm or github!

Change the jquery show()/hide() animation?

Use slidedown():

$("test").slideDown("slow");

New line in Sql Query

You could do Char(13) and Char(10). Cr and Lf.

Char() works in SQL Server, I don't know about other databases.

How to divide two columns?

Presumably, those columns are integer columns - which will be the reason as the result of the calculation will be of the same type.

e.g. if you do this:

SELECT 1 / 2

you will get 0, which is obviously not the real answer. So, convert the values to e.g. decimal and do the calculation based on that datatype instead.

e.g.

SELECT CAST(1 AS DECIMAL) / 2

gives 0.500000

How to add a custom right-click menu to a webpage?

<script language="javascript" type="text/javascript">
  document.oncontextmenu = RightMouseDown; 
  document.onmousedown = mouseDown; 

  function mouseDown(e) {
    if (e.which==3) {//righClick
      alert("Right-click menu goes here");
    } 
  }

  function RightMouseDown() { 
    return false; 
  }
</script>
</body> 
</html>

Laravel 5.2 not reading env file

In my case laravel 5.7 env('APP_URL') not work but config('app.url') works. If I add new variable to env and to config - it not works - but after php artisan config:cache it start works.

Session variables in ASP.NET MVC

I would think you'll want to think about if things really belong in a session state. This is something I find myself doing every now and then and it's a nice strongly typed approach to the whole thing but you should be careful when putting things in the session context. Not everything should be there just because it belongs to some user.

in global.asax hook the OnSessionStart event

void OnSessionStart(...)
{
    HttpContext.Current.Session.Add("__MySessionObject", new MySessionObject());
}

From anywhere in code where the HttpContext.Current property != null you can retrive that object. I do this with an extension method.

public static MySessionObject GetMySessionObject(this HttpContext current)
{
    return current != null ? (MySessionObject)current.Session["__MySessionObject"] : null;
}

This way you can in code

void OnLoad(...)
{
    var sessionObj = HttpContext.Current.GetMySessionObject();
    // do something with 'sessionObj'
}

Maximum request length exceeded.

It bothered me for days too. I modified the Web.config file but it didn't work. It turned out that there are two Web.config file in my project, and I should modified the one in the ROOT directory, not the others. Hope this would be helpful.

Can clearInterval() be called inside setInterval()?

Yes you can. You can even test it:

_x000D_
_x000D_
var i = 0;_x000D_
var timer = setInterval(function() {_x000D_
  console.log(++i);_x000D_
  if (i === 5) clearInterval(timer);_x000D_
  console.log('post-interval'); //this will still run after clearing_x000D_
}, 200);
_x000D_
_x000D_
_x000D_

In this example, this timer clears when i reaches 5.

Best Free Text Editor Supporting *More Than* 4GB Files?

glogg could also be considered, for a different usage:

glogg screenshot

Caveat (reported by Simon Tewsi in the comments, Feb. 2013)

One caveat - has two search functions, Main Search and Quick Find.
The lower one, which I assume is Quick Find, is at least an order of magnitude slower than the upper one, which is fast.

Resize on div element

For a google maps integration I was looking for a way to detect when a div has changed in size. Since google maps always require proper dimensions e.g. width and height in order to render properly.

The solution I came up with is a delegation of an event, in my case a tab click. This could be a window resize of course, the idea remains the same:

if (parent.is(':visible')) {
    w = parent.outerWidth(false);
    h = w * mapRatio /*9/16*/;
    this.map.css({ width: w, height: h });
} else {
    this.map.closest('.tab').one('click', function() {
        this.activate();
    }.bind(this));
}

this.map in this case is my map div. Since my parent is invisible on load, the computed width and height are 0 or don't match. By using .bind(this) I can delegate the script execution (this.activate) to an event (click).

Now I'm confident the same applies for resize events.

$(window).one('resize', function() {
    this.div.css({ /*whatever*/ });
}.bind(this));

Hope it helps anyone!

jQuery set checkbox checked

Worked for me:

$checkbok.prop({checked: true});

Rails create or update magic?

Add this to your model:

def self.update_or_create_by(args, attributes)
  obj = self.find_or_create_by(args)
  obj.update(attributes)
  return obj
end

With that, you can:

User.update_or_create_by({name: 'Joe'}, attributes)

Changing the size of a column referenced by a schema-bound view in SQL Server

ALTER TABLE [table_name] ALTER COLUMN [column_name] varchar(150)

Javascript - Get Image height

It's worth noting that in Firefox 3 and Safari, resizing an image by just changing the height and width doesn't look too bad. In other browsers it can look very noisy because it's using nearest-neighbor resampling. Of course, you're paying to serve a larger image, but that might not matter.

PHP function ssh2_connect is not working

Honestly, I'd recommend using phpseclib, a pure PHP SSH2 implementation. Example:

<?php
include('Net/SSH2.php');

$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}

echo $ssh->exec('pwd');
echo $ssh->exec('ls -la');
?>

It's a ton more portable, easier to use and more feature packed too.

How can I change the app display name build with Flutter?

First Rename your AndroidManifest.xml file

android:label="Your App Name"

Second Rename Your Application Name in Pubspec.yaml file name: Your Application Name

Third Change Your Application logo

flutter_icons:
   android: "launcher_icon"
   ios: true
   image_path: "assets/path/your Application logo.formate"

Fourth Run

flutter pub pub run flutter_launcher_icons:main

SMTP server response: 530 5.7.0 Must issue a STARTTLS command first

First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()).

You can set the following settings in your PHP.ini:

ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");

How to avoid soft keyboard pushing up my layout?

To solve this simply add android:windowSoftInputMode="stateVisible|adjustPan to that activity in android manifest file. for example

<activity 
    android:name="com.comapny.applicationname.activityname"
    android:screenOrientation="portrait"
    android:windowSoftInputMode="stateVisible|adjustPan"/>

How to get summary statistics by group

The psych package has a great option for grouped summary stats:

library(psych)
    
describeBy(dt, group="grp")

produces lots of useful stats including mean, median, range, sd, se.

Correct way to integrate jQuery plugins in AngularJS

i have alreay 2 situations where directives and services/factories didnt play well.

the scenario is that i have (had) a directive that has dependency injection of a service, and from the directive i ask the service to make an ajax call (with $http).

in the end, in both cases the ng-Repeat did not file at all, even when i gave the array an initial value.

i even tried to make a directive with a controller and an isolated-scope

only when i moved everything to a controller and it worked like magic.

example about this here Initialising jQuery plugin (RoyalSlider) in Angular JS

Error when checking Java version: could not find java.dll

Reinstall JDK and set system variable JAVA_HOME on your JDK. (e.g. C:\tools\jdk7)
And add JAVA_HOME variable to your PATH system variable

Type in command line

echo %JAVA_HOME%

and

java -version

To verify whether your installation was done successfully.


This problem generally occurs in Windows when your "Java Runtime Environment" registry entry is missing or mismatched with the installed JDK. The mismatch can be due to multiple JDKs.

Steps to resolve:

  1. Open the Run window:

    Press windows+R

  2. Open registry window:

    Type regedit and enter.

  3. Go to: \HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\

  4. If Java Runtime Environment is not present inside JavaSoft, then create a new Key and give the name Java Runtime Environment.

  5. For Java Runtime Environment create "CurrentVersion" String Key and give appropriate version as value:

JRE regedit entry

  1. Create a new subkey of 1.8.

  2. For 1.8 create a String Key with name JavaHome with the value of JRE home:

    JRE regedit entry 2

Ref: https://mybindirectory.blogspot.com/2019/05/error-could-not-find-javadll.html

How to change the color of winform DataGridview header?

If you want to change a color to single column try this:

 dataGridView1.EnableHeadersVisualStyles = false;
 dataGridView1.Columns[0].HeaderCell.Style.BackColor = Color.Magenta;
 dataGridView1.Columns[1].HeaderCell.Style.BackColor = Color.Yellow;

Reversing a linked list in Java, recursively

void reverse(node1,node2){
if(node1.next!=null)
      reverse(node1.next,node1);
   node1.next=node2;
}
call this method as reverse(start,null);

Sending mail from Python using SMTP

The script I use is quite similar; I post it here as an example of how to use the email.* modules to generate MIME messages; so this script can be easily modified to attach pictures, etc.

I rely on my ISP to add the date time header.

My ISP requires me to use a secure smtp connection to send mail, I rely on the smtplib module (downloadable at http://www1.cs.columbia.edu/~db2501/ssmtplib.py)

As in your script, the username and password, (given dummy values below), used to authenticate on the SMTP server, are in plain text in the source. This is a security weakness; but the best alternative depends on how careful you need (want?) to be about protecting these.

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

#! /usr/local/bin/python


SMTPserver = 'smtp.att.yahoo.com'
sender =     'me@my_email_domain.net'
destination = ['recipient@her_email_domain.com']

USERNAME = "USER_NAME_FOR_INTERNET_SERVICE_PROVIDER"
PASSWORD = "PASSWORD_INTERNET_SERVICE_PROVIDER"

# typical values for text_subtype are plain, html, xml
text_subtype = 'plain'


content="""\
Test message
"""

subject="Sent from Python"

import sys
import os
import re

from smtplib import SMTP_SSL as SMTP       # this invokes the secure SMTP protocol (port 465, uses SSL)
# from smtplib import SMTP                  # use this for standard SMTP protocol   (port 25, no encryption)

# old version
# from email.MIMEText import MIMEText
from email.mime.text import MIMEText

try:
    msg = MIMEText(content, text_subtype)
    msg['Subject']=       subject
    msg['From']   = sender # some SMTP servers will do this automatically, not all

    conn = SMTP(SMTPserver)
    conn.set_debuglevel(False)
    conn.login(USERNAME, PASSWORD)
    try:
        conn.sendmail(sender, destination, msg.as_string())
    finally:
        conn.quit()

except:
    sys.exit( "mail failed; %s" % "CUSTOM_ERROR" ) # give an error message

Check if program is running with bash shell script?

You can achieve almost everything in PROCESS_NUM with this one-liner:

[ `pgrep $1` ] && return 1 || return 0

if you're looking for a partial match, i.e. program is named foobar and you want your $1 to be just foo you can add the -f switch to pgrep:

[[ `pgrep -f $1` ]] && return 1 || return 0

Putting it all together your script could be reworked like this:

#!/bin/bash

check_process() {
  echo "$ts: checking $1"
  [ "$1" = "" ]  && return 0
  [ `pgrep -n $1` ] && return 1 || return 0
}

while [ 1 ]; do 
  # timestamp
  ts=`date +%T`

  echo "$ts: begin checking..."
  check_process "dropbox"
  [ $? -eq 0 ] && echo "$ts: not running, restarting..." && `dropbox start -i > /dev/null`
  sleep 5
done

Running it would look like this:

# SHELL #1
22:07:26: begin checking...
22:07:26: checking dropbox
22:07:31: begin checking...
22:07:31: checking dropbox

# SHELL #2
$ dropbox stop
Dropbox daemon stopped.

# SHELL #1
22:07:36: begin checking...
22:07:36: checking dropbox
22:07:36: not running, restarting...
22:07:42: begin checking...
22:07:42: checking dropbox

Hope this helps!

How do I create a Python function with optional arguments?

Just use the *args parameter, which allows you to pass as many arguments as you want after your a,b,c. You would have to add some logic to map args->c,d,e,f but its a "way" of overloading.

def myfunc(a,b, *args, **kwargs):
   for ar in args:
      print ar
myfunc(a,b,c,d,e,f)

And it will print values of c,d,e,f


Similarly you could use the kwargs argument and then you could name your parameters.

def myfunc(a,b, *args, **kwargs):
      c = kwargs.get('c', None)
      d = kwargs.get('d', None)
      #etc
myfunc(a,b, c='nick', d='dog', ...)

And then kwargs would have a dictionary of all the parameters that are key valued after a,b

SQL Format as of Round off removing decimals

check the round function and how does the length argument works. It controls the behaviour of the precision of the result

Can't import database through phpmyadmin file size too large

For Upload large size data in using phpmyadmin Do following steps.

  1. Open php.ini file from C:\wamp\bin\apache\Apache2.4.4\bin Update following lines
    max_execution_time = 259200
    max_input_time = 259200
    memory_limit = 1000M
    upload_max_filesize = 750M
    post_max_size = 750M
    than after restart wamp server or restart all services Now Upload data using import function in phymyadmin. Apply second step if till not upload data.
  2. open config.default.php file in c:\wamp\apps\phpmyadmin4.0.4\libraries (Open this file accoring to phpmyadmin version)
    Find $cfg['ExecTimeLimit'] = 300;Replace to $cfg['ExecTimeLimit'] = 0;
    Now you can upload data.

You can also upload large size database using MySQL Console as below.

  1. Click on WampServer Icon -> MySQL -> MySQL Consol
  2. Enter your database password like root in popup
  3. Select database name for insert data by writing command USE DATABASENAME
  4. Then load source sql file as SOURCE C:\FOLDER\database.sql
  5. Press enter for insert data.

Note: You can't load a compressed database file e.g. database.sql.zip or database.sql.gz, you have to extract it first. Otherwise the console will just crash.

urllib and "SSL: CERTIFICATE_VERIFY_FAILED" Error

Python 2.7.12 (default, Jul 29 2016, 15:26:22) fixed the mentioned issue. This information might help someone else.

Fragments onResume from back stack

I've changed the suggested solution a little bit. Works better for me like that:

private OnBackStackChangedListener getListener() {
    OnBackStackChangedListener result = new OnBackStackChangedListener() {
        public void onBackStackChanged() {
            FragmentManager manager = getSupportFragmentManager();
            if (manager != null) {
                int backStackEntryCount = manager.getBackStackEntryCount();
                if (backStackEntryCount == 0) {
                    finish();
                }
                Fragment fragment = manager.getFragments()
                                           .get(backStackEntryCount - 1);
                fragment.onResume();
            }
        }
    };
    return result;
}

Get list of filenames in folder with Javascript

I made a different route for every file in a particular directory. Therefore, going to that path meant opening that file.

function getroutes(list){
list.forEach(function(element) {
  app.get("/"+ element,  function(req, res) {
    res.sendFile(__dirname + "/public/extracted/" + element);
  });
});

I called this function passing the list of filename in the directory __dirname/public/extracted and it created a different route for each filename which I was able to render on server side.

clientHeight/clientWidth returning different values on different browsers

i had a similar problem - firefox returned the correct value of obj.clientHeight but ie did not- it returned 0. I changed it to obj.offsetHeight and it worked. Seems there is some state that ie has for clientheight - that makes it iffy...

PHP decoding and encoding json with unicode characters

To encode an array that contains special characters, ISO 8859-1 to UTF8. (If utf8_encode & utf8_decode is not what is working for you, this might be an option)

Everything that is in ISO-8859-1 should be converted to UTF8:

$utf8 = utf8_encode('? ??? ??? ????!'); //contains UTF8 & ISO 8859-1 characters;    
$iso88591 = mb_convert_encoding($utf8, 'ISO-8859-1', 'UTF-8');
$data = $iso88591;

Encode should work after this:

$encoded_data = json_encode($data);

Convert UTF-8 to & from ISO 8859-1

"No resource identifier found for attribute 'showAsAction' in package 'android'"

The problem is related to AppCompat library. With it, you have

xmlns:appname="http://schemas.android.com/apk/res-auto"

and possibly:

appname:showAsAction="never"

in menu.xml file.

Without the lib, you can only have:

android:showAsAction="never"

and my app works with menu both on Android 4.3 and 2.3.3.

How can I find the version of the Fedora I use?

These commands worked for Artik 10 :

  • cat /etc/fedora-release
  • cat /etc/issue
  • hostnamectl

and these others didn't :

  • lsb_release -a
  • uname -a

Running Bash commands in Python

The pythonic way of doing this is using subprocess.Popen

subprocess.Popen takes a list where the first element is the command to be run followed by any command line arguments.

As an example:

import subprocess

args = ['echo', 'Hello!']
subprocess.Popen(args) // same as running `echo Hello!` on cmd line

args2 = ['echo', '-v', '"Hello Again"']
subprocess.Popen(args2) // same as running 'echo -v "Hello Again!"` on cmd line

Saving to CSV in Excel loses regional date format

You need to do a lot more work than 1. click export 2. Open file.

I think that when the Excel CSV documentation talks about OS and regional settings being interpreted, that means that Excel will do that when it opens the file (which is in their "special" csv format). See this article, "Excel formatting and features are not transferred to other file formats"

Also, Excel is actually storing a number, and converting to a date string only for display. When it exports to CSV, it is converting it to a different date string. If you want that date string to be non-default, you will need to convert your Excel cells to strings before performing your export.

Alternately, you could convert your dates to the number value that Excel is saving. Since that is a time code, it actually will obey OS and regional settings, assuming you import it properly. Notepad will only show you the 10-digit number, though.

How do I find duplicate values in a table in Oracle?

You don't need to even have the count in the returned columns if you don't need to know the actual number of duplicates. e.g.

SELECT column_name
FROM table
GROUP BY column_name
HAVING COUNT(*) > 1

XSL xsl:template match="/"

The match attribute indicates on which parts the template transformation is going to be applied. In that particular case the "/" means the root of the xml document. The value you have to provide into the match attribute should be XPath expression. XPath is the language you have to use to refer specific parts of the target xml file.

To gain a meaningful understanding of what else you can put into match attribute you need to understand what xpath is and how to use it. I suggest yo look at links I've provided for youat the bottom of the answer.

Could I write "table" or any other html tag instead of "/" ?

Yes you can. But this depends what exactly you are trying to do. if your target xml file contains HMTL elements and you are triyng to apply this xsl:template on them it makes sense to use table, div or anithing else.

Here a few links:

HTML/Javascript Button Click Counter

Use var instead of int for your clicks variable generation and onClick instead of click as your function name:

_x000D_
_x000D_
var clicks = 0;

function onClick() {
  clicks += 1;
  document.getElementById("clicks").innerHTML = clicks;
};
_x000D_
<button type="button" onClick="onClick()">Click me</button>
<p>Clicks: <a id="clicks">0</a></p>
_x000D_
_x000D_
_x000D_

In JavaScript variables are declared with the var keyword. There are no tags like int, bool, string... to declare variables. You can get the type of a variable with 'typeof(yourvariable)', more support about this you find on Google.

And the name 'click' is reserved by JavaScript for function names so you have to use something else.

Check if a key is down?

I know this is very old question, however there is a very lightweight (~.5Kb) JavaScript library that effectively "patches" the inconsistent firing of keyboard event handlers when using the DOM API.

The library is Keydrown.

Here's the operative code sample that has worked well for my purposes by just changing the key on which to set the listener:

kd.P.down(function () {
  console.log('The "P" key is being held down!');
});

kd.P.up(function () {
  console.clear();
});

// This update loop is the heartbeat of Keydrown
kd.run(function () {
  kd.tick();
});

I've incorporated Keydrown into my client-side JavaScript for a proper pause animation in a Red Light Green Light game I'm writing. You can view the entire game here. (Note: If you're reading this in the future, the game should be code complete and playable :-D!)

I hope this helps.

Difference between socket and websocket?

Websockets use sockets in their implementation. Websockets are based on a standard protocol (now in final call, but not yet final) that defines a connection "handshake" and message "frame." The two sides go through the handshake procedure to mutually accept a connection and then use the standard message format ("frame") to pass messages back and forth.

I'm developing a framework that will allow you to communicate directly machine to machine with installed software. It might suit your purpose. You can follow my blog if you wish: http://highlevellogic.blogspot.com/2011/09/websocket-server-demonstration_26.html

Java Hashmap: How to get key from value?

You can use the below:

public class HashmapKeyExist {
    public static void main(String[] args) {
        HashMap<String, String> hmap = new HashMap<String, String>();
        hmap.put("1", "Bala");
        hmap.put("2", "Test");

        Boolean cantain = hmap.containsValue("Bala");
        if(hmap.containsKey("2") && hmap.containsValue("Test"))
        {
            System.out.println("Yes");
        }
        if(cantain == true)
        {
            System.out.println("Yes"); 
        }

        Set setkeys = hmap.keySet();
        Iterator it = setkeys.iterator();

        while(it.hasNext())
        {
            String key = (String) it.next();
            if (hmap.get(key).equals("Bala"))
            {
                System.out.println(key);
            }
        }
    }
}

How to open this .DB file?

I don't think there is a way to tell which program to use from just the .db extension. It could even be an encrypted database which can't be opened. You can MS Access, or a sqlite manager.

Edit: Try to rename the file to .txt and open it with a text editor. The first couple of words in the file could tell you the DB Type.

If it is a SQLite database, it will start with "SQLite format 3"

Can the Android layout folder contain subfolders?

I think the most elegant solution to this problem (given that subfolders are not allowed) is to prepend the file names with the name of the folder you would have placed it inside of. For example, if you have a bunch of layouts for an Activity, Fragment, or just general view called "places" then you should just prepend it with places_my_layout_name. At least this solves the problem of organizing them in a way that they are easier to find within the IDE. It's not the most awesome solution, but it's better than nothing.

Should ol/ul be inside <p> or outside?

<p>tetxetextex</p>
<ol><li>first element</li></ol>
<p>other textetxeettx</p>

Because both <p> and <ol> are element rendered as block.

Using jQuery To Get Size of Viewport

You can try viewport units (CSS3):

div { 
  height: 95vh; 
  width: 95vw; 
}

Browser support

What's the difference between text/xml vs application/xml for webservice response

This is an old question, but one that is frequently visited and clear recommendations are now available from RFC 7303 which obsoletes RFC3023. In a nutshell (section 9.2):

The registration information for text/xml is in all respects the same
as that given for application/xml above (Section 9.1), except that
the "Type name" is "text".

Run ssh and immediately execute command

This isn't quite what you're looking for, but I've found it useful in similar circumstances.

I recently added the following to my $HOME/.bashrc (something similar should be possible with shells other than bash):

if [ -f $HOME/.add-screen-to-history ] ; then
    history -s 'screen -dr'
fi

I keep a screen session running on one particular machine, and I've had problems with ssh connections to that machine being dropped, requiring me to re-run screen -dr every time I reconnect.

With that addition, and after creating that (empty) file in my home directory, I automatically have the screen -dr command in my history when my shell starts. After reconnecting, I can just type Control-P Enter and I'm back in my screen session -- or I can ignore it. It's flexible, but not quite automatic, and in your case it's easier than typing tmux list-sessions.

You might want to make the history -s command unconditional.

This does require updating your $HOME/.bashrc on each of the target systems, which might or might not make it unsuitable for your purposes.

How do I download code using SVN/Tortoise from Google Code?

After you install Tortoise (separate SVN client not required), create a new empty folder for the project somewhere and right click it in Windows. There should be an option for SVN Checkout. Choosing that option will open a dialog box. Paste the URL you posted above in the first textbox of that dialog box and click "OK".

How to run a cron job on every Monday, Wednesday and Friday?

Use this command to add job

crontab -e

In this format:

0 19 * * 1,3,5 /path to your file/file.php

multiple classes on single element html

Short Answer

Yes.


Explanation

It is a good practice since an element can be a part of different groups, and you may want specific elements to be a part of more than one group. The element can hold an infinite number of classes in HTML5, while in HTML4 you are limited by a specific length.

The following example will show you the use of multiple classes.

The first class makes the text color red.

The second class makes the background-color blue.

See how the DOM Element with multiple classes will behave, it will wear both CSS statements at the same time.

Result: multiple CSS statements in different classes will stack up.

You can read more about CSS Specificity.


CSS

.class1 {
    color:red;
}

.class2 {
    background-color:blue;
}

HTML

<div class="class1">text 1</div>
<div class="class2">text 2</div>
<div class="class1 class2">text 3</div>

Live demo

Create a string and append text to it

Use the string concatenation operator:

Dim str As String = New String("") & "some other string"

Strings in .NET are immutable and thus there exist no concept of appending strings. All string modifications causes a new string to be created and returned.

This obviously cause a terrible performance. In common everyday code this isn't an issue, but if you're doing intensive string operations in which time is of the essence then you will benefit from looking into the StringBuilder class. It allow you to queue appends. Once you're done appending you can ask it to actually perform all the queued operations.

See "How to: Concatenate Multiple Strings" for more information on both methods.

What is output buffering?

As name suggest here memory buffer used to manage how the output of script appears.

Here is one very good tutorial for the topic

Create or update mapping in elasticsearch

Please note that there is a mistake in the url provided in this answer:

For a PUT mapping request: the url should be as follows:

http://localhost:9200/name_of_index/_mappings/document_type

and NOT

http://localhost:9200/name_of_index/document_type/_mappings

How to git commit a single file/directory

Use the -o option.

git commit -o path/to/myfile -m "the message"

-o, --only commit only specified files

Parallel foreach with asynchronous lambda

In the accepted answer the ConcurrentBag is not required. Here's an implementation without it:

var tasks = myCollection.Select(GetData).ToList();
await Task.WhenAll(tasks);
var results = tasks.Select(t => t.Result);

Any of the "// some pre stuff" and "// some post stuff" can go into the GetData implementation (or another method that calls GetData)

Aside from being shorter, there's no use of an "async void" lambda, which is an anti pattern.

Class Not Found: Empty Test Suite in IntelliJ

Had the same message. I had to remove the Run/Debug configuration.

In my case, I ran the unit test as a local test before. After that I moved my test to the androidTest package and tried to run it again. Android Studio remembered the last run configuration so it tried to run it again as a local unit test which produced the same error.

After removing the config and running the test again it generated a new configuration and worked.

enter image description here

Spring: How to inject a value to static field?

This is my sample code for load static variable

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class OnelinkConfig {
    public static int MODULE_CODE;
    public static int DEFAULT_PAGE;
    public static int DEFAULT_SIZE;

    @Autowired
    public void loadOnelinkConfig(@Value("${onelink.config.exception.module.code}") int code,
            @Value("${onelink.config.default.page}") int page, @Value("${onelink.config.default.size}") int size) {
        MODULE_CODE = code;
        DEFAULT_PAGE = page;
        DEFAULT_SIZE = size;
    }
}

Calling a JavaScript function named in a variable

I'd avoid eval.

To solve this problem, you should know these things about JavaScript.

  1. Functions are first-class objects, so they can be properties of an object (in which case they are called methods) or even elements of arrays.
  2. If you aren't choosing the object a function belongs to, it belongs to the global scope. In the browser, that means you're hanging it on the object named "window," which is where globals live.
  3. Arrays and objects are intimately related. (Rumor is they might even be the result of incest!) You can often substitute using a dot . rather than square brackets [], or vice versa.

Your problem is a result of considering the dot manner of reference rather than the square bracket manner.

So, why not something like,

window["functionName"]();

That's assuming your function lives in the global space. If you've namespaced, then:

myNameSpace["functionName"]();

Avoid eval, and avoid passing a string in to setTimeout and setInterval. I write a lot of JS, and I NEVER need eval. "Needing" eval comes from not knowing the language deeply enough. You need to learn about scoping, context, and syntax. If you're ever stuck with an eval, just ask--you'll learn quickly.

Why do you have to link the math library in C?

Because of ridiculous historical practice that nobody is willing to fix. Consolidating all of the functions required by C and POSIX into a single library file would not only avoid this question getting asked over and over, but would also save a significant amount of time and memory when dynamic linking, since each .so file linked requires the filesystem operations to locate and find it, and a few pages for its static variables, relocations, etc.

An implementation where all functions are in one library and the -lm, -lpthread, -lrt, etc. options are all no-ops (or link to empty .a files) is perfectly POSIX conformant and certainly preferable.

Note: I'm talking about POSIX because C itself does not specify anything about how the compiler is invoked. Thus you can just treat gcc -std=c99 -lm as the implementation-specific way the compiler must be invoked for conformant behavior.

HTML5 - mp4 video does not play in IE9

Internet Explorer 9 support MPEG4 using H.264 codec. But it also required that the file can start to play as soon as it starts downloading.

Here are the very basic steps on how to make a MPEG file that works in IE9 (using avconv on Ubuntu). I spent many hours to figure that out, so I hope that it can help someone else.

  1. Convert the video to MPEG4 using H.264 codec. You don't need anything fancy, just let avconv do the job for you:

    avconv -i video.mp4 -vcodec libx264 pre_out.mp4
    
  2. This video will works on all browsers that support MPEG4, except IE9. To add support for IE9, you have to move the file info to the file header, so the browser can start playing it as soon as it starts to download it. THIS IS THE KEY FOR IE9!!!

    qt-faststart pre_out.mp4 out.mp4
    

qt-faststart is a Quicktime utilities that also support H.264/ACC file format. It is part of libav-tools package.

Swap two items in List<T>

List<T> has a Reverse() method, however it only reverses the order of two (or more) consecutive items.

your_list.Reverse(index, 2);

Where the second parameter 2 indicates we are reversing the order of 2 items, starting with the item at the given index.

Source: https://msdn.microsoft.com/en-us/library/hf2ay11y(v=vs.110).aspx

How to convert enum names to string in c

An simpler alternative to Hokyo's "Non-Sequential enums" answer, based on using designators to instantiate the string array:

#define NAMES C(RED, 10)C(GREEN, 20)C(BLUE, 30)
#define C(k, v) k = v,
enum color { NAMES };
#undef C

#define C(k, v) [v] = #k,    
const char * const color_name[] = { NAMES };

Removing special characters VBA Excel

Here is how removed special characters.

I simply applied regex

Dim strPattern As String: strPattern = "[^a-zA-Z0-9]" 'The regex pattern to find special characters
Dim strReplace As String: strReplace = "" 'The replacement for the special characters
Set regEx = CreateObject("vbscript.regexp") 'Initialize the regex object    
Dim GCID As String: GCID = "Text #N/A" 'The text to be stripped of special characters

' Configure the regex object
With regEx
    .Global = True
    .MultiLine = True
    .IgnoreCase = False
    .Pattern = strPattern
End With

' Perform the regex replacement
GCID = regEx.Replace(GCID, strReplace)

Form Submit Execute JavaScript Best Practice?

Attach an event handler to the submit event of the form. Make sure it cancels the default action.

Quirks Mode has a guide to event handlers, but you would probably be better off using a library to simplify the code and iron out the differences between browsers. All the major ones (such as YUI and jQuery) include event handling features, and there is a large collection of tiny event libraries.

Here is how you would do it in YUI 3:

<script src="http://yui.yahooapis.com/3.4.1/build/yui/yui-min.js"></script>
<script>
    YUI().use('event', function (Y) {
        Y.one('form').on('submit', function (e) {
            // Whatever else you want to do goes here
            e.preventDefault();
        });
    });
</script>

Make sure that the server will pick up the slack if the JavaScript fails for any reason.

set up device for development (???????????? no permissions)

In Archlinux this can happen occasionally. The fix:

$ sudo -s
# adb kill-server
# adb start-server

How do I find a list of Homebrew's installable packages?

From the man page:

search, -S text|/text/
Perform a substring search of formula names for text. If text is surrounded with slashes,
then it is interpreted as a regular expression. If no search term is given,
all available formula are displayed.

For your purposes, brew search will suffice.

How to identify whether a grammar is LL(1), LR(0) or SLR(1)?

Simple answer:A grammar is said to be an LL(1),if the associated LL(1) parsing table has atmost one production in each table entry.

Take the simple grammar A -->Aa|b.[A is non-terminal & a,b are terminals]
   then find the First and follow sets A.
    First{A}={b}.
    Follow{A}={$,a}.

    Parsing table for Our grammar.Terminals as columns and Nonterminal S as a row element.

        a            b                   $
    --------------------------------------------
 S  |               A-->a                      |
    |               A-->Aa.                    |
    -------------------------------------------- 

As [S,b] contains two Productions there is a confusion as to which rule to choose.So it is not LL(1).

Some simple checks to see whether a grammar is LL(1) or not. Check 1: The Grammar should not be left Recursive. Example: E --> E+T. is not LL(1) because it is Left recursive. Check 2: The Grammar should be Left Factored.

Left factoring is required when two or more grammar rule choices share a common prefix string. Example: S-->A+int|A.

Check 3:The Grammar should not be ambiguous.

These are some simple checks.

How to determine programmatically the current active profile using Spring boot

It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment to your bean.

@Autowired
private Environment environment;
....

this.environment.getActiveProfiles();

Concatenate two JSON objects

One solution is to use a list/array:

var first_json = {"name":"joe", "age":27};
var second_json = {"name":"james", "age":32};

var jsons = new Array();
jsons.push(first_json);
jsons.push(second_json);

Result

jsons = [
    {"name":"joe", "age":27},
    {"name":"james", "age":32}
]

What is an "index out of range" exception, and how do I fix it?

Why does this error occur?

Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.

The first element in a collection is generally located at index 0. The last element is at index n-1, where n is the Size of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1, you're going to get an error.

How indexing arrays works

When you declare an array like this:

var array = new int[6]

The first and last elements in the array are

var firstElement = array[0];
var lastElement = array[5];

So when you write:

var element = array[5];

you are retrieving the sixth element in the array, not the fifth one.

Typically, you would loop over an array like this:

for (int index = 0; index < array.Length; index++)
{
    Console.WriteLine(array[index]);
}

This works, because the loop starts at zero, and ends at Length-1 because index is no longer less than Length.

This, however, will throw an exception:

for (int index = 0; index <= array.Length; index++)
{
    Console.WriteLine(array[index]);
}

Notice the <= there? index will now be out of range in the last loop iteration, because the loop thinks that Length is a valid index, but it is not.

How other collections work

Lists work the same way, except that you generally use Count instead of Length. They still start at zero, and end at Count - 1.

for (int index = 0; i < list.Count; index++)
{
    Console.WriteLine(list[index]);
} 

However, you can also iterate through a list using foreach, avoiding the whole problem of indexing entirely:

foreach (var element in list)
{
    Console.WriteLine(element.ToString());
}

You cannot index an element that hasn't been added to a collection yet.

var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]);  // Throws exception.

How do I read input character-by-character in Java?

Wrap your reader in a BufferedReader, which maintains a buffer allowing for much faster reads overall. You can then use read() to read a single character (which you'll need to cast). You can also use readLine() to fetch an entire line and then break that into individual characters. The BufferedReader also supports marking and returning, so if you need to, you can read a line multiple times.

Generally speaking, you want to use a BufferedReader or BufferedInputStream on top of whatever stream you are actually using since the buffer they maintain will make multiple reads much faster.

Is there an exponent operator in C#?

I'm surprised no one has mentioned this, but for the simple (and probably most encountered) case of squaring, you just multiply by itself.

float someNumber;

float result = someNumber * someNumber;

How to change the new TabLayout indicator color and height

Since I can't post a follow-up to android developer's comment, here's an updated answer for anyone else who needs to programmatically set the selected tab indicator color:

tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#FFFFFF"));

Similarly, for height:

tabLayout.setSelectedTabIndicatorHeight((int) (2 * getResources().getDisplayMetrics().density));

These methods were only recently added to revision 23.0.0 of the Support Library, which is why Soheil Setayeshi's answer uses reflection.

How can I have linebreaks in my long LaTeX equations?

I think I usually used eqnarray or something. It lets you say

\begin{eqnarray*}
    x &=& blah blah blah \\ 
      & & more blah blah blah \\
      & & even more blah blah
\end{eqnarray*}

and it will be aligned by the & &... As pkaeding mentioned, it's hard to read, but when you've got an equation thats that long, it's gonna be hard to read no matter what... (The * makes it not have an equation number, IIRC)

Refresh an asp.net page on button click

On button click you can try the following.

protected void button1_Click(object sender, EventArgs e)
{
     Response.Redirect("~/Admin/Admin.aspx");
}

And on PageLoad you can check whether the loading is coming from that button then increase the count.

       protected void Page_Load(object sender, EventArgs e)
         {
            StackTrace stackTrace = new StackTrace();
            string eventName = stackTrace.GetFrame(1).GetMethod().Name; // this will the event name.
            if (eventName == "button1_Click")
              {
                // code to increase the count;
              }
          }

Thanks

How to create a file on Android Internal Storage?

You should use ContextWrapper like this:

ContextWrapper cw = new ContextWrapper(context);
File directory = cw.getDir("media", Context.MODE_PRIVATE);

As always, refer to documentation, ContextWrapper has a lot to offer.

How to get the current directory of the cmdlet being executed

To expand on @Cradle 's answer: you could also write a multi-purpose function that will get you the same result per the OP's question:

Function Get-AbsolutePath {

    [CmdletBinding()]
    Param(
        [parameter(
            Mandatory=$false,
            ValueFromPipeline=$true
        )]
        [String]$relativePath=".\"
    )

    if (Test-Path -Path $relativePath) {
        return (Get-Item -Path $relativePath).FullName -replace "\\$", ""
    } else {
        Write-Error -Message "'$relativePath' is not a valid path" -ErrorId 1 -ErrorAction Stop
    }

}

Python and JSON - TypeError list indices must be integers not str

First of all, you should be using json.loads, not json.dumps. loads converts JSON source text to a Python value, while dumps goes the other way.

After you fix that, based on the JSON snippet at the top of your question, readable_json will be a list, and so readable_json['firstName'] is meaningless. The correct way to get the 'firstName' field of every element of a list is to eliminate the playerstuff = readable_json['firstName'] line and change for i in playerstuff: to for i in readable_json:.

SQL query to select dates between two dates

Check below Examples: Both working and Non-Working.

select * from tblUser Where    
convert(varchar(10),CreatedDate,111) between '2015/04/01' and '2016/04/01' //--**Working**

OR

select * from tblUser Where
(CAST(CreatedDate AS DATETIME) between CAST('2015/04/01' AS DATETIME) And CAST('2016/4/30'AS DATETIME)) //--**Working**

OR

select * from tblUser Where
(YEAR(CreatedDate) between YEAR('2015/04/01') And YEAR('2016/4/30')) 
//--**Working**

AND below is not working:

select * from tblUser Where
Convert(Varchar(10),CreatedDate,111) >=  Convert(Varchar(10),'01-01-2015',111) and  Convert(Varchar(10),CreatedDate,111) <= Convert(Varchar(10),'31-12-2015',111) //--**Not Working**


select * from tblUser Where
(Convert(Varchar(10),CreatedDate,111) between Convert(Varchar(10),'01-01-2015',111) And Convert(Varchar(10),'31-12-2015',111)) //--**Not Working**

pull access denied repository does not exist or may require docker login

If the repository is private you have to assign permissions to download it. You have two options, with the docker login command, or put in ~/.docker/docker.config the file generated once you login.

Android - how to make a scrollable constraintlayout?

TO make a scrollable layout, the layout is correct. It will not be scrollable until there is reason to scroll(just like in any other layout). So add enough content and it will be scrollable, just like with any layout(Linear, Relative, etc). However, you cannot scroll properly in Blueprint or design-mode when designing with ConstraintLayout and ScrollView.

Meaning:

You can make a scrollable ConstraintLayout, but it will not scroll properly in the editor due to a bug/scenario that wasn't considered. But even though scrolling doesn't work in the editor, it works on devices. (I have made several scrolling COnstraintLayouts, so I have tested it)

Note

Regarding your code. The ScrollView is missing a closing tag, I don't know if it is the case in the file or if it is a copy-paste miss, but you may want to look at it.

What is the correct Performance Counter to get CPU and Memory Usage of a Process?

Pelo Hyper-V:

private PerformanceCounter theMemCounter = new PerformanceCounter(
    "Hyper-v Dynamic Memory VM",
    "Physical Memory",
    Process.GetCurrentProcess().ProcessName); 

Open a workbook using FileDialog and manipulate it in Excel VBA

Thankyou Frank.i got the idea. Here is the working code.

Option Explicit
Private Sub CommandButton1_Click()

  Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
  Dim fd As Office.FileDialog

  Set fd = Application.FileDialog(msoFileDialogFilePicker)

  With fd
    .AllowMultiSelect = False
    .Title = "Please select the file."
    .Filters.Clear
    .Filters.Add "Excel 2003", "*.xls?"

    If .Show = True Then
      fileName = Dir(.SelectedItems(1))

    End If
  End With

  Application.ScreenUpdating = False
  Application.DisplayAlerts = False

  Workbooks.Open (fileName)

  For Each sheet In Workbooks(fileName).Worksheets
    total = Workbooks("import-sheets.xlsm").Worksheets.Count
    Workbooks(fileName).Worksheets(sheet.Name).Copy _
        after:=Workbooks("import-sheets.xlsm").Worksheets(total)
  Next sheet

  Workbooks(fileName).Close

  Application.ScreenUpdating = True
  Application.DisplayAlerts = True

End Sub

How can I reload .emacs after changing it?

Keyboard shortcut:

(defun reload-init-file ()
  (interactive)
  (load-file user-init-file))

(global-set-key (kbd "C-c C-l") 'reload-init-file)    ; Reload .emacs file

jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

Interesting. How are you generating your JSON on the server end? Are you using a library function (such as json_encode in PHP), or are you building the JSON string by hand?

The only thing that grabs my attention is the escape apostrophe (\'). Seeing as you're using double quotes, as you indeed should, there is no need to escape single quotes. I can't check if that is indeed the cause for your jQuery error, as I haven't updated to version 1.4.1 myself yet.

How to use System.Net.HttpClient to post a complex type?

If you want the types of convenience methods mentioned in other answers but need portability (or even if you don't), you might want to check out Flurl [disclosure: I'm the author]. It (thinly) wraps HttpClient and Json.NET and adds some fluent sugar and other goodies, including some baked-in testing helpers.

Post as JSON:

var resp = await "http://localhost:44268/api/test".PostJsonAsync(widget);

or URL-encoded:

var resp = await "http://localhost:44268/api/test".PostUrlEncodedAsync(widget);

Both examples above return an HttpResponseMessage, but Flurl includes extension methods for returning other things if you just want to cut to the chase:

T poco = await url.PostJsonAsync(data).ReceiveJson<T>();
dynamic d = await url.PostUrlEncodedAsync(data).ReceiveJson();
string s = await url.PostUrlEncodedAsync(data).ReceiveString();

Flurl is available on NuGet:

PM> Install-Package Flurl.Http

How to fetch JSON file in Angular 2

I needed to load the settings file synchronously, and this was my solution:

export function InitConfig(config: AppConfig) { return () => config.load(); }

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

@Injectable()
export class AppConfig {
    Settings: ISettings;

    constructor() { }

    load() {
        return new Promise((resolve) => {
            this.Settings = this.httpGet('assets/clientsettings.json');
            resolve(true);
        });
    }

    httpGet(theUrl): ISettings {
        const xmlHttp = new XMLHttpRequest();
        xmlHttp.open( 'GET', theUrl, false ); // false for synchronous request
        xmlHttp.send( null );
        return JSON.parse(xmlHttp.responseText);
    }
}

This is then provided as a app_initializer which is loaded before the rest of the application.

app.module.ts

{
      provide: APP_INITIALIZER,
      useFactory: InitConfig,
      deps: [AppConfig],
      multi: true
    },

Where do you include the jQuery library from? Google JSAPI? CDN?

I will add this as a reason to locally host these files.

Recently a node in Southern California on TWC has not been able to resolve the ajax.googleapis.com domain (for users with IPv4) only so we are not getting the external files. This has been intermittant up until yesterday (now it is persistant.) Because it was intermittant, I was having tons of problems troubleshooting SaaS user issues. Spent countless hours trying to track why some users were having no issues with the software, and others were tanking. In my usual debugging process I'm not in the habit of asking a user if they have IPv6 turned off.

I stumbled on the issue because I myself was using this particular "route" to the file and also am using only IPV4. I discovered the issue with developers tools telling me jquery wasn't loading, then started doing traceroutes etc... to find the real issue.

After this, I will most likely never go back to externally hosted files because: google doesn't have to go down for this to become a problem, and... any one of these nodes can be compromised with DNS hijacking and deliver malicious js instead of the actual file. Always thought I was safe in that a google domain would never go down, now I know any node in between a user and the host can be a fail point.

Java Long primitive type maximum limit

Exceding the maximum value of a long doesnt throw an exception, instead it cicles back. If you do this:

Long.MAX_VALUE + 1

you will notice that the result is the equivalent to Long.MIN_VALUE.

From here: java number exceeds long.max_value - how to detect?

Python integer division yields float

The accepted answer already mentions PEP 238. I just want to add a quick look behind the scenes for those interested in what's going on without reading the whole PEP.

Python maps operators like +, -, * and / to special functions, such that e.g. a + b is equivalent to

a.__add__(b)

Regarding division in Python 2, there is by default only / which maps to __div__ and the result is dependent on the input types (e.g. int, float).

Python 2.2 introduced the __future__ feature division, which changed the division semantics the following way (TL;DR of PEP 238):

  • / maps to __truediv__ which must "return a reasonable approximation of the mathematical result of the division" (quote from PEP 238)
  • // maps to __floordiv__, which should return the floored result of /

With Python 3.0, the changes of PEP 238 became the default behaviour and there is no more special method __div__ in Python's object model.

If you want to use the same code in Python 2 and Python 3 use

from __future__ import division

and stick to the PEP 238 semantics of / and //.

Use of for_each on map elements

From what I remembered, C++ map can return you an iterator of keys using map.begin(), you can use that iterator to loop over all the keys until it reach map.end(), and get the corresponding value: C++ map

How to bind 'touchstart' and 'click' events but not respond to both?

Taking advantage of the fact that a click will always follow a touch event, here is what I did to get rid of the "ghost click" without having to use timeouts or global flags.

$('#buttonId').on('touchstart click', function(event){
    if ($(this).data("already")) {
        $(this).data("already", false);
        return false;
    } else if (event.type == "touchstart") {
        $(this).data("already", true);
    }
    //your code here
});

Basically whenever an ontouchstart event fires on the element, a flag a set and then subsequently removed (and ignored), when the click comes.

How to implement drop down list in flutter?

When I ran into this issue of wanting a less generic DropdownStringButton, I just created it:

dropdown_string_button.dart

import 'package:flutter/material.dart';
// Subclass of DropdownButton based on String only values.
// Yes, I know Flutter discourages subclassing, but this seems to be
// a reasonable exception where a commonly used specialization can be
// made more easily usable.
//
// Usage: 
// DropdownStringButton(items: ['A', 'B', 'C'], value: 'A', onChanged: (string) {})
//
class DropdownStringButton extends DropdownButton<String> {
  DropdownStringButton({
    Key key, @required List<String> items, value, hint, disabledHint,
    @required onChanged, elevation = 8, style, iconSize = 24.0, isDense = false,
    isExpanded = false, }) : 
    assert(items == null || value == null || items.where((String item) => item == value).length == 1),
        super(
          key: key,
          items: items.map((String item) {
            return DropdownMenuItem<String>(child: Text(item), value: item);
          }).toList(),
        value: value, hint: hint, disabledHint: disabledHint, onChanged: onChanged,
        elevation: elevation, style: style, iconSize: iconSize, isDense: isDense,
        isExpanded: isExpanded,
        );
    }

String concatenation in Ruby

For your particular case you could also use Array#join when constructing file path type of string:

string = [ROOT_DIR, project, 'App.config'].join('/')]

This has a pleasant side effect of automatically converting different types to string:

['foo', :bar, 1].join('/')
=>"foo/bar/1"

Bootstrap dropdown sub menu missing

Shprink's code helped me the most, but to avoid the dropdown to go off-screen i updated it to:

JS:

$('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {
    // Avoid following the href location when clicking
    event.preventDefault(); 
    // Avoid having the menu to close when clicking
    event.stopPropagation(); 
    // If a menu is already open we close it
    $('ul.dropdown-menu [data-toggle=dropdown]').parent().removeClass('open');
    // opening the one you clicked on
    $(this).parent().addClass('open');

    var menu = $(this).parent().find("ul");
    var menupos = $(menu).offset();

    if (menupos.left + menu.width() > $(window).width()) {
        var newpos = -$(menu).width();
        menu.css({ left: newpos });    
    } else {
        var newpos = $(this).parent().width();
        menu.css({ left: newpos });
    }

});

CSS: FROM background-color: #eeeeee TO background-color: #c5c5c5 - white font & light background wasn't looking good.

.nav .open > a,
.nav .open > a:hover,
.nav .open > a:focus {
  background-color: #c5c5c5;
  border-color: #428bca;
}

I hope this helps people as much as it did for me!

But i hope Bootstrap add the subs feature back ASAP.

How to import a bak file into SQL Server Express

Restoring a Database from Backup

sql-server-->connect to instance-->Databases-->right-click on databases-->Restore
            DataBase..-->Device-->Add-->choose the path_filename(.bak)-->click OK

Passing arguments to "make run"

for standard make you can pass arguments by defining macros like this

make run arg1=asdf

then use them like this

run: ./prog $(arg1)
   etc

References for make Microsoft's NMake

How to do a https request with bad certificate?

All of these answers are wrong! Do not use InsecureSkipVerify to deal with a CN that doesn't match the hostname. The Go developers unwisely were adamant about not disabling hostname checks (which has legitimate uses - tunnels, nats, shared cluster certs, etc), while also having something that looks similar but actually completely ignores the certificate check. You need to know that the certificate is valid and signed by a cert that you trust. But in common scenarios, you know that the CN won't match the hostname you connected with. For those, set ServerName on tls.Config. If tls.Config.ServerName == remoteServerCN, then the certificate check will succeed. This is what you want. InsecureSkipVerify means that there is NO authentication; and it's ripe for a Man-In-The-Middle; defeating the purpose of using TLS.

There is one legitimate use for InsecureSkipVerify: use it to connect to a host and grab its certificate, then immediately disconnect. If you setup your code to use InsecureSkipVerify, it's generally because you didn't set ServerName properly (it will need to come from an env var or something - don't belly-ache about this requirement... do it correctly).

In particular, if you use client certs and rely on them for authentication, you basically have a fake login that doesn't actually login any more. Refuse code that does InsecureSkipVerify, or you will learn what is wrong with it the hard way!

NavigationBar bar, tint, and title text color in iOS 8

Setting text color of navigation bar title to white in Swift version 4.2:

navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]

Apache giving 403 forbidden errors

The server may need read permission for your home directory and .htaccess therein

How to insert element into arrays at specific position?

Simplest solution, if you want to insert (an element or array) after a certain key:

function array_splice_after_key($array, $key, $array_to_insert)
{
    $key_pos = array_search($key, array_keys($array));
    if($key_pos !== false){
        $key_pos++;
        $second_array = array_splice($array, $key_pos);
        $array = array_merge($array, $array_to_insert, $second_array);
    }
    return $array;
}

So, if you have:

$array = [
    'one' => 1,
    'three' => 3
];
$array_to_insert = ['two' => 2];

And execute:

$result_array = array_splice_after_key($array, 'one', $array_to_insert);

You'll have:

Array ( 
    ['one'] => 1 
    ['two'] => 2 
    ['three'] => 3 
)

Can a JSON value contain a multiline string

I'm not sure of your exact requirement but one possible solution to improve 'readability' is to store it as an array.

{
  "testCases" :
  {
    "case.1" :
    {
      "scenario" : "this the case 1.",
      "result" : ["this is a very long line which is not easily readble.",
                  "so i would like to write it in multiple lines.",
                  "but, i do NOT require any new lines in the output."]
    }
  }
}

}

The join in back again whenever required with

result.join(" ")

OS X Sprite Kit Game Optimal Default Window Size

You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.

Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.

You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.

The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.

You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.

Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.

But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).

You should provide @2x images for the Retina Macbook Pro and future Retina Macs.

initialize a vector to zeros C++/C++11

Initializing a vector having struct, class or Union can be done this way

std::vector<SomeStruct> someStructVect(length);
memset(someStructVect.data(), 0, sizeof(SomeStruct)*length);

Search and replace part of string in database

I was just faced with a similar problem. I exported the contents of the db into one sql file and used TextEdit to find and replace everything I needed. Simplicity ftw!

Python Matplotlib Y-Axis ticks on Right Side of Plot

Use ax.yaxis.tick_right()

for example:

from matplotlib import pyplot as plt

f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
plt.plot([2,3,4,5])
plt.show()

enter image description here

How to randomly select an item from a list?

If you want to randomly select more than one item from a list, or select an item from a set, I'd recommend using random.sample instead.

import random
group_of_items = {1, 2, 3, 4}               # a sequence or set will work here.
num_to_select = 2                           # set the number to select here.
list_of_random_items = random.sample(group_of_items, num_to_select)
first_random_item = list_of_random_items[0]
second_random_item = list_of_random_items[1] 

If you're only pulling a single item from a list though, choice is less clunky, as using sample would have the syntax random.sample(some_list, 1)[0] instead of random.choice(some_list).

Unfortunately though, choice only works for a single output from sequences (such as lists or tuples). Though random.choice(tuple(some_set)) may be an option for getting a single item from a set.

EDIT: Using Secrets

As many have pointed out, if you require more secure pseudorandom samples, you should use the secrets module:

import secrets                              # imports secure module.
secure_random = secrets.SystemRandom()      # creates a secure random object.
group_of_items = {1, 2, 3, 4}               # a sequence or set will work here.
num_to_select = 2                           # set the number to select here.
list_of_random_items = secure_random.sample(group_of_items, num_to_select)
first_random_item = list_of_random_items[0]
second_random_item = list_of_random_items[1]

EDIT: Pythonic One-Liner

If you want a more pythonic one-liner for selecting multiple items, you can use unpacking.

import random
first_random_item, second_random_item = random.sample(group_of_items, 2)

Pass a password to ssh in pure bash

Since there were no exact answers to my question, I made some investigation why my code doesn't work when there are other solutions that works, and decided to post what I found to complete the subject.
As it turns out:

"ssh uses direct TTY access to make sure that the password is indeed issued by an interactive keyboard user." sshpass manpage

which answers the question, why the pipes don't work in this case. The obvious solution was to create conditions so that ssh "thought" that it is run in the regular terminal and since it may be accomplished by simple posix functions, it is beyond what simple bash offers.

Subtract two dates in SQL and get days of the result

Syntax

DATEDIFF(expr1,expr2)

Description

DATEDIFF() returns (expr1 – expr2) expressed as a value in days from one date to the other. expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are used in the calculation.

@D Stanley

Does --disable-web-security Work In Chrome Anymore?

Check if you have Chrome App Launcher. You can usually see it in your toolbar. It runs as a second instance of chrome, but unlike the browser, it auto-runs so is going to be running whenever you start your PC. Even though it isn't a browser view, it is a chrome instance which is enough to prevent your arguments from taking effect. Go to your task manager and you will probably have to kill 2 chrome processes.

docker-compose up for only certain containers

I actually had a very similar challenge on my current project. That broght me to the idea of writing a small script which I called docker-compose-profile (or short: dcp). I published this today on GitLab as docker-compose-profile. So in short: I now can start several predefined docker-compose profiles using a command like dcp -p some-services "up -d". Feel free to try it out and give some feedback or suggestions for further improvements.

Find mouse position relative to element

As I didn't find a jQuery-free answer that I could copy/paste, here's the solution I used:

_x000D_
_x000D_
document.getElementById('clickme').onclick = function clickEvent(e) {
      // e = Mouse click event.
      var rect = e.target.getBoundingClientRect();
      var x = e.clientX - rect.left; //x position within the element.
      var y = e.clientY - rect.top;  //y position within the element.
      console.log("Left? : " + x + " ; Top? : " + y + ".");
    }
_x000D_
#clickme {
  margin-top: 20px;
  margin-left: 100px;
  border: 1px solid black;
  cursor: pointer;
}
_x000D_
<div id="clickme">Click Me -<br>
(this box has margin-left: 100px; margin-top: 20px;)</div>
_x000D_
_x000D_
_x000D_

JSFiddle of full example