Programs & Examples On #Cppiechart

Making an image act like a button

You could use an image submit button:

<input type="image"  id="saveform" src="logg.png " alt="Submit Form" />

Why avoid increment ("++") and decrement ("--") operators in JavaScript?

As mentioned in some of the existing answers (which annoyingly I'm unable to comment on), the problem is that x++ ++x evaluate to different values (before vs after the increment), which is not obvious and can be very confusing - if that value is used. cdmckay suggests quite wisely to allow use of increment operator, but only in a way that the returned value is not used, e.g. on its own line. I would also include the standard use within a for loop (but only in the third statement, whose return value is not used). I can't think of another example. Having been "burnt" myself, I would recommend the same guideline for other languages as well.

I disagree with the claim that this over-strictness is due to a lot of JS programmers being inexperienced. This is the exact kind of writing typical of "overly-clever" programmers, and I'm sure it's much more common in more traditional languages and with JS developers who have a background in such languages.

Can I exclude some concrete urls from <url-pattern> inside <filter-mapping>?

I used an approach described by Eric Daugherty: I created a special servlet that always answers with 403 code and put its mapping before the general one.

Mapping fragment:

  <servlet>
    <servlet-name>generalServlet</servlet-name>
    <servlet-class>project.servlet.GeneralServlet</servlet-class>
  </servlet>
 <servlet>
    <servlet-name>specialServlet</servlet-name>
    <servlet-class>project.servlet.SpecialServlet</servlet-class>
 </servlet>
 <servlet-mapping>
    <servlet-name>specialServlet</servlet-name>
    <url-pattern>/resources/restricted/*</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
    <servlet-name>generalServlet</servlet-name>
    <url-pattern>/resources/*</url-pattern>
 </servlet-mapping>

And the servlet class:

public class SpecialServlet extends HttpServlet {
    public SpecialServlet() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    }
}

What is meant by immutable?

Immutable means that once the object is created, non of its members will change. String is immutable since you can not change its content. For example:

String s1 = "  abc  ";
String s2 = s1.trim();

In the code above, the string s1 did not change, another object (s2) was created using s1.

Is there any difference between DECIMAL and NUMERIC in SQL Server?

They are the same. Numeric is functionally equivalent to decimal.

MSDN: decimal and numeric

How to Convert UTC Date To Local time Zone in MySql Select Query

 select convert_tz(now(),@@session.time_zone,'+05:30')

replace '+05:30' with desired timezone. see here - https://stackoverflow.com/a/3984412/2359994

to format into desired time format, eg:

 select DATE_FORMAT(convert_tz(now(),@@session.time_zone,'+05:30') ,'%b %d %Y %h:%i:%s %p') 

you will get similar to this -> Dec 17 2014 10:39:56 AM

How to change a dataframe column from String type to Double type in PySpark?

Preserve the name of the column and avoid extra column addition by using the same name as input column:

changedTypedf = joindf.withColumn("show", joindf["show"].cast(DoubleType()))

How to unstage large number of files without deleting the content

git reset

If all you want is to undo an overzealous "git add" run:

git reset

Your changes will be unstaged and ready for you to re-add as you please.


DO NOT RUN git reset --hard.

It will not only unstage your added files, but will revert any changes you made in your working directory. If you created any new files in working directory, it will not delete them though.

Bitwise and in place of modulus operator

In this specific case (mod 7), we still can replace %7 with bitwise operators:

// Return X%7 for X >= 0.
int mod7(int x)
{
  while (x > 7) x = (x&7) + (x>>3);
  return (x == 7)?0:x;
}

It works because 8%7 = 1. Obviously, this code is probably less efficient than a simple x%7, and certainly less readable.

Change default global installation directory for node.js modules in Windows?

Everything you need is in the npm-folders documentation. I don't want to start my Win notebook now so I cannot verify it, but you should only change prefix to C:\Program Files\nodejs in your config file. If you want to change it globally for all users, edit the C:\Program Files\nodejs\npmrc file, otherwise create/edit C:\Users\{username}\.npmrc.

But this change will probably have some side effects, so read this discussion first. I don't think it's a good idea.

How do I remove the last comma from a string using PHP?

It is better to use implode for that purpose. Implode is easy and awesome:

    $array = ['name1', 'name2', 'name3'];
    $str = implode(', ', $array);

Output:

    name1, name2, name3

error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

if you have _tmain function in your projects you need to include <tchar.h>.

How to have click event ONLY fire on parent DIV, not children?

I did not get the accepted answer to work, but this seems to do the trick, at least in vanilla JS.

if(e.target !== e.currentTarget) return;

MySQL Orderby a number, Nulls last

MySQL has an undocumented syntax to sort nulls last. Place a minus sign (-) before the column name and switch the ASC to DESC:

SELECT * FROM tablename WHERE visible=1 ORDER BY -position DESC, id DESC

It is essentially the inverse of position DESC placing the NULL values last but otherwise the same as position ASC.

A good reference is here http://troels.arvin.dk/db/rdbms#select-order_by

What is the difference between HTTP and REST?

HTTP is a protocol used for communication, usually used to communicate with internet resources or any application with a web browser client.

REST means that the main concept you are using while designing the application is the Resource: for each action you want to perform you need to define a resource on which you usually do only CRUD operation, which is a simple task. for that its very convenient to use 4 verbs used in HTTP protocol against the 4 CRUD operations (Get for Read, POST is for CREATE, PUT is for UPDATE and DELETE is for DELETE). that's unlike the older concept of RPC (Remote Procedure Call), in which you have a set of actions you want to perform as a result of the user's call. if you think for example on how to describe a facebook like on a post, with RPC you might create services called AddLikeToPost and RemoveLikeFromPost, and manage it along with all your other services related to FB posts, thus you won't need to create special object for Like. with REST you will have a Like object which will be managed separately with Delete and Create functions. It also means it will describe a separate entity in your db. that might look like a small difference, but working like that would usually yield a much simpler code and a much simpler application. with that design, most of the app's logic is obvious from the object's structure (model), unlike RPC with which you would usually have to explicitly add a lot more logic.

designing RESTful application is usually a lot harder because it requires you to describe complicated things in a simple manner. describing all functionalities using only CRUD functions is tricky, but after doing that your life would be a lot simpler and you will find that you will write a lot shorter methods.

One more restraint REST architecture present is not to use session context when communicating with client (stateless), meaning all the information needs to understand who is the client and what he wants is passed with the web message. each call to a function is self descriptive, there is no previous conversation with the client which can be referenced in the message. therefor a client could not tell you "give me the next page" since you don't have a session to store what is the previous page and what kind of page you want, the client would have to say "my name is yuval, get me page 2 of a specific post in a specific forum". that means a bit more data would have to transfer in the communication, but think of the difference between finding a bug reported from the "get me next page" function in oppose to "get me page 2 of question id 2190836 in stack overflow".

Of course there is a lot more to it, but to my opinion that's the main concepts in a teaspoon.

Implementing a slider (SeekBar) in Android

How to implement a SeekBar

enter image description here

Add the SeekBar to your layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_margin="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <SeekBar
        android:id="@+id/seekBar"
        android:max="100"
        android:progress="50"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

Notes

  • max is the highest value that the seek bar can go to. The default is 100. The minimum is 0. The xml min value is only available from API 26, but you can just programmatically convert the 0-100 range to whatever you need for earlier versions.
  • progress is the initial position of the slider dot (called a "thumb").
  • For a vertical SeekBar use android:rotation="270".

Listen for changes in code

public class MainActivity extends AppCompatActivity {

    TextView tvProgressLabel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // set a change listener on the SeekBar
        SeekBar seekBar = findViewById(R.id.seekBar);
        seekBar.setOnSeekBarChangeListener(seekBarChangeListener);

        int progress = seekBar.getProgress();
        tvProgressLabel = findViewById(R.id.textView);
        tvProgressLabel.setText("Progress: " + progress);
    }

    SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // updated continuously as the user slides the thumb
            tvProgressLabel.setText("Progress: " + progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // called when the user first touches the SeekBar
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // called after the user finishes moving the SeekBar
        }
    };
}

Notes

  • If you don't need to do any updates while the user is moving the seekbar, then you can just update the UI in onStopTrackingTouch.

See also

Can media queries resize based on a div element instead of the screen?

After nearly a decade of work — with proposals, proofs-of-concept, discussions and other contributions by the broader web developer community — the CSS Working Group has finally laid some of the groundwork needed for container queries to be written into a future edition of the CSS Containment spec! For more details on how such a feature might work and be used, check out Miriam Suzanne's extensive explainer.

Hopefully it won't be much longer before we see a robust cross-browser implementation of such a system. It's been a grueling wait, but I'm glad that it's no longer something we simply have to accept as an insurmountable limitation of CSS due to cyclic dependencies or infinite loops or what have you (these are still a potential issue in some aspects of the proposed design, but I have faith that the CSSWG will find a way).


Media queries aren't designed to work based on elements in a page. They are designed to work based on devices or media types (hence why they are called media queries). width, height, and other dimension-based media features all refer to the dimensions of either the viewport or the device's screen in screen-based media. They cannot be used to refer to a certain element on a page.

If you need to apply styles depending on the size of a certain div element on your page, you'll have to use JavaScript to observe changes in the size of that div element instead of media queries.

Alternatively, with more modern layout techniques introduced since the original publication of this answer such as flexbox and standards such as custom properties, you may not need media or element queries after all. Djave provides an example.

Calculate distance between 2 GPS coordinates

I guess you want it along the curvature of the earth. Your two points and the center of the earth are on a plane. The center of the earth is the center of a circle on that plane and the two points are (roughly) on the perimeter of that circle. From that you can calculate the distance by finding out what the angle from one point to the other is.

If the points are not the same heights, or if you need to take into account that the earth is not a perfect sphere it gets a little more difficult.

HTTP Error 401.2 - Unauthorized You are not authorized to view this page due to invalid authentication headers

Make sure Anonymous access is enabled on IIS -> Authentication.

But also right click on it, then click on Edit, and choose a domain\username and password. (With access to the physical folder of the application).

What are the git concepts of HEAD, master, origin?

HEAD is not the latest revision, it's the current revision. Usually, it's the latest revision of the current branch, but it doesn't have to be.

master is a name commonly given to the main branch, but it could be called anything else (or there could be no main branch).

origin is a name commonly given to the main remote. remote is another repository that you can pull from and push to. Usually it's on some server, like github.

How do I access properties of a javascript object if I don't know the names?

You often will want to examine the particular properties of an instance of an object, without all of it's shared prototype methods and properties:

 Obj.prototype.toString= function(){
        var A= [];
        for(var p in this){
            if(this.hasOwnProperty(p)){
                A[A.length]= p+'='+this[p];
            }
        }

    return A.join(', ');
}

What does '<?=' mean in PHP?

<?= $a ?> is the same as <? echo $a; ?>, just shorthand for convenience.

What is the best open source help ticket system?

Howabout Bugzilla. Open source and what Mozilla uses.

How to auto-reload files in Node.js?

my app structure:

NodeAPP (folder)
   |-- app (folder)
      |-- all other file is here
   |-- node_modules (folder)
   |-- package.json
   |-- server.js (my server file)

first install reload with this command:

npm install [-g] [--save-dev] reload

then change package.json:

"scripts": {
    "start": "nodemon -e css,ejs,js,json --watch app"
}

now you must use reload in your server file:

var express = require('express');
var reload = require('reload');
var app = express();

app.set('port', process.env.PORT || 3000);

var server = app.listen(app.get('port'), function() {
    console.log( 'server is running on port ' + app.get('port'));
});

reload(server, app);

and for last change, end of your response send this script:

<script src="/reload/reload.js"></script>

now start your app with this code:

npm start

Using moment.js to convert date to string "MM/dd/yyyy"

Try this:

var momentObj = $("#start_ts").datepicker("getDate");

var yourDate = momentObj.format('L');

How do I fix an "Invalid license data. Reinstall is required." error in Visual C# 2010 Express?

My prolem: -VS works fine, but when I create new Solution Setup and Deployment it make Setup file but when I run this Setup file, it say: "Invalid license data. Reinstall is required." -subinacl do not work.

My PC: -OS:Windows 7 64bit. -Visual Studio 2012

My way: -Close Visual Studio -Run regedit. -Pull down HKEY_CLASSES_ROOT -Looking for Licenses -Right click on Licenses -> click Permissions... -> click Addvanced -> click User you want edit -> click Edit -> choose This key and subkey -> check all Allow: Full Control, Query Value, SetValue, Create Subkey, Enumerate Subkeys, Notyfy, Create Link, Delete, Write DAC, Write Owner, Read Control... -> check Apply these permissions to objects... -> click OK -> click OK -> click OK -> Close Registry Edit -Start VS -Hope this help

jQuery 'each' loop with JSON array

My solutions in one of my own sites, with a table:

$.getJSON("sections/view_numbers_update.php", function(data) {
 $.each(data, function(index, objNumber) {
  $('#tr_' + objNumber.intID).find("td").eq(3).html(objNumber.datLastCalled);
  $('#tr_' + objNumber.intID).find("td").eq(4).html(objNumber.strStatus);
  $('#tr_' + objNumber.intID).find("td").eq(5).html(objNumber.intDuration);
  $('#tr_' + objNumber.intID).find("td").eq(6).html(objNumber.blnWasHuman);
 });
});

sections/view_numbers_update.php Returns something like:

[{"intID":"19","datLastCalled":"Thu, 10 Jan 13 08:52:20 +0000","strStatus":"Completed","intDuration":"0:04 secs","blnWasHuman":"Yes","datModified":1357807940},
{"intID":"22","datLastCalled":"Thu, 10 Jan 13 08:54:43 +0000","strStatus":"Completed","intDuration":"0:00 secs","blnWasHuman":"Yes","datModified":1357808079}]

HTML table:

<table id="table_numbers">
 <tr>
  <th>[...]</th>
  <th>[...]</th>
  <th>[...]</th>
  <th>Last Call</th>
  <th>Status</th>
  <th>Duration</th>
  <th>Human?</th>
  <th>[...]</th>
 </tr>
 <tr id="tr_123456">
  [...]
 </tr>
</table>

This essentially gives every row a unique id preceding with 'tr_' to allow for other numbered element ids, at server script time. The jQuery script then just gets this TR_[id] element, and fills the correct indexed cell with the json return.

The advantage is you could get the complete array from the DB, and either foreach($array as $record) to create the table html, OR (if there is an update request) you can die(json_encode($array)) before displaying the table, all in the same page, but same display code.

String to date in Oracle with milliseconds

Oracle stores only the fractions up to second in a DATE field.

Use TIMESTAMP instead:

SELECT  TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9')
FROM    dual

, possibly casting it to a DATE then:

SELECT  CAST(TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9') AS DATE)
FROM    dual

How do I abort the execution of a Python script?

To exit a script you can use,

import sys
sys.exit()

You can also provide an exit status value, usually an integer.

import sys
sys.exit(0)

Exits with zero, which is generally interpreted as success. Non-zero codes are usually treated as errors. The default is to exit with zero.

import sys
sys.exit("aa! errors!")

Prints "aa! errors!" and exits with a status code of 1.

There is also an _exit() function in the os module. The sys.exit() function raises a SystemExit exception to exit the program, so try statements and cleanup code can execute. The os._exit() version doesn't do this. It just ends the program without doing any cleanup or flushing output buffers, so it shouldn't normally be used.

The Python docs indicate that os._exit() is the normal way to end a child process created with a call to os.fork(), so it does have a use in certain circumstances.

How to get an MD5 checksum in PowerShell

Here is the snippet that I am using to get the MD5 for a given string:

$text = "text goes here..."
$md5  = [Security.Cryptography.MD5CryptoServiceProvider]::new()
$utf8 = [Text.UTF8Encoding]::UTF8
$bytes= $md5.ComputeHash($utf8.GetBytes($text))
$hash = [string]::Concat($bytes.foreach{$_.ToString("x2")}) 

how to call javascript function in html.actionlink in asp.net mvc?

This is the only one that worked for me in .cshtml file:

@Html.ActionLink(
   "Name", 
   "Action", 
   "Controller", 
   routeValues: null, 
   htmlAttributes:new Dictionary<string, object> {{ "onclick", "alert('Test');" }})

I hope this helps.

Changing image sizes proportionally using CSS?

if you know the spect ratio you can use padding-bottom with percentage to set the hight depending on with of the diff.

<div>
   <div style="padding-bottom: 33%;">
      i have 33% height of my parents width
   </div>
</div>

jQuery preventDefault() not triggered

i just had the same problems - have been testing a lot of different stuff. but it just wouldn't work. then i checked the tutorial examples on jQuery.com again and found out:

your jQuery script needs to be after the elements you are referring to !

so your script needs to be after the html-code you want to access!

seems like jQuery can't access it otherwise.

Set select option 'selected', by value

An issue I ran into when the value is an ID and the text is a code. You cannot set the value using the code but you don't have direct access to the ID.

var value;

$("#selectorId > option").each(function () {
  if ("SOMECODE" === $(this).text()) {
    value = $(this).val();
  }
});

//Do work here

sql ORDER BY multiple values in specific order?

Since i don't have enough reputation to write as a comment, added this as a new answer.

You can add asc or desc to order by clause.

ORDER BY x_field='A' ASC, x_field='I' DESC, x_field='P' DESC, x_field='F' ASC

which makes I first, P second and A as last one and F before the last.

access key and value of object using *ngFor

You could create a custom pipe to return the list of key for each element. Something like that:

import { PipeTransform, Pipe } from '@angular/core';

@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
  transform(value, args:string[]) : any {
    let keys = [];
    for (let key in value) {
      keys.push(key);
    }
    return keys;
  }
}

and use it like that:

<tr *ngFor="let c of content">           
  <td *ngFor="let key of c | keys">{{key}}: {{c[key]}}</td>
</tr>

Edit

You could also return an entry containing both key and value:

@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
  transform(value, args:string[]) : any {
    let keys = [];
    for (let key in value) {
      keys.push({key: key, value: value[key]});
    }
    return keys;
  }
}

and use it like that:

<span *ngFor="let entry of content | keys">           
  Key: {{entry.key}}, value: {{entry.value}}
</span>

Parsing JSON using C

cJSON has a decent API and is small (2 files, ~700 lines). Many of the other JSON parsers I looked at first were huge... I just want to parse some JSON.

Edit: We've made some improvements to cJSON over the years.

Nginx serves .php files as downloads, instead of executing them

First you have to Remove cache in your browser

Then open terminal and run the following command:

sudo apt-get install php-gettext
sudo nano /etc/nginx/sites-available/default

Then add the following code in the default file:

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /usr/share/nginx/html;
    index index.php index.html index.htm;

    server_name localhost;

    location / {
        try_files $uri $uri/ =404;
    }

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

If any mismatch just correction and restart Nginx from terminal by the following command

sudo systemctl restart nginx

Then go to browser and Enjoy ...

Inline Form nested within Horizontal Form in Bootstrap 3

This Bootply example seems like a much better option. Only thing is that the labels are a little too high so I added padding-top:5px to center them with my inputs.

<div class="container">
<h2>Bootstrap Mixed Form <p class="lead">with horizontal and inline fields</p></h2>
<form role="form" class="form-horizontal">
    <div class="form-group">
        <label class="col-sm-1" for="inputEmail1">Email</label>
        <div class="col-sm-5"><input type="email" class="form-control" id="inputEmail1" placeholder="Email"></div>
    </div>
    <div class="form-group">
        <label class="col-sm-1" for="inputPassword1">Password</label>
        <div class="col-sm-5"><input type="password" class="form-control" id="inputPassword1" placeholder="Password"></div>
    </div>
    <div class="form-group">
        <label class="col-sm-12" for="TextArea">Textarea</label>
        <div class="col-sm-6"><textarea class="form-control" id="TextArea"></textarea></div>
    </div>
    <div class="form-group">
        <div class="col-sm-3"><label>First name</label><input type="text" class="form-control" placeholder="First"></div>
        <div class="col-sm-3"><label>Last name</label><input type="text" class="form-control" placeholder="Last"></div>
    </div>
    <div class="form-group">
        <label class="col-sm-12">Phone number</label>
        <div class="col-sm-1"><input type="text" class="form-control" placeholder="000"><div class="help">area</div></div>
        <div class="col-sm-1"><input type="text" class="form-control" placeholder="000"><div class="help">local</div></div>
        <div class="col-sm-2"><input type="text" class="form-control" placeholder="1111"><div class="help">number</div></div>
        <div class="col-sm-2"><input type="text" class="form-control" placeholder="123"><div class="help">ext</div></div>
    </div>
    <div class="form-group">
        <label class="col-sm-1">Options</label>
        <div class="col-sm-2"><input type="text" class="form-control" placeholder="Option 1"></div>
        <div class="col-sm-3"><input type="text" class="form-control" placeholder="Option 2"></div>
    </div>
    <div class="form-group">
        <div class="col-sm-6">
            <button type="submit" class="btn btn-info pull-right">Submit</button>
        </div>
    </div>
</form>
<hr>
</div>

How to get last month/year in java?

java.time

Using java.time framework built into Java 8:

import java.time.LocalDate;

LocalDate now = LocalDate.now(); // 2015-11-24
LocalDate earlier = now.minusMonths(1); // 2015-10-24

earlier.getMonth(); // java.time.Month = OCTOBER
earlier.getMonth.getValue(); // 10
earlier.getYear(); // 2015

Showing percentages above bars on Excel column graph

Either

  1. Use a line series to show the %
  2. Update the data labels above the bars to link back directly to other cells

Method 2 by step

  • add data-lables
  • right-click the data lable
  • goto the edit bar and type in a refence to a cell (C4 in this example)
  • this changes the data lable from the defulat value (2000) to a linked cell with the 15%

enter image description here

How can I style a PHP echo text?

You can "style echo" with adding new HTML code.

echo '<span class="city">' . $ip['cityName'] . '</span>';

Get int value from enum in C#

Declare it as a static class having public constants:

public static class Question
{
    public const int Role = 2;
    public const int ProjectFunding = 3;
    public const int TotalEmployee = 4;
    public const int NumberOfServers = 5;
    public const int TopBusinessConcern = 6;
}

And then you can reference it as Question.Role, and it always evaluates to an int or whatever you define it as.

Script to Change Row Color when a cell changes text

Realise this is an old thread, but after seeing lots of scripts like this I noticed that you can do this just using conditional formatting.

Assuming the "Status" was Column D:

Highlight cells > right click > conditional formatting. Select "Custom Formula Is" and set the formula as

=RegExMatch($D2,"Complete")

or

=OR(RegExMatch($D2,"Complete"),RegExMatch($D2,"complete"))

Edit (thanks to Frederik Schøning)

=RegExMatch($D2,"(?i)Complete") then set the range to cover all the rows e.g. A2:Z10. This is case insensitive, so will match complete, Complete or CoMpLeTe.

You could then add other rules for "Not Started" etc. The $ is very important. It denotes an absolute reference. Without it cell A2 would look at D2, but B2 would look at E2, so you'd get inconsistent formatting on any given row.

How to create a project from existing source in Eclipse and then find it?

Follow this instructions from standard eclipse docs.

  1. From the main menu bar, select command link File > Import.... The Import wizard opens.
  2. Select General > Existing Project into Workspace and click Next.
  3. Choose either Select root directory or Select archive file and click the associated Browse to locate the directory or file containing the projects.
  4. Under Projects select the project or projects which you would like to import.
  5. Click Finish to start the import.

extract column value based on another column pandas dataframe

Use df[df['B']==3]['A'].values if you just want item itself without the brackets

Change Volley timeout duration

I ended up adding a method setCurrentTimeout(int timeout) to the RetryPolicy and it's implementation in DefaultRetryPolicy.

Then I added a setCurrentTimeout(int timeout) in the Request class and called it .

This seems to do the job.

Sorry for my laziness by the way and hooray for open source.

Creating a constant Dictionary in C#

I am not sure why no one mentioned this but in C# for things that I cannot assign const, I use static read-only properties.

Example:

public static readonly Dictionary<string, string[]> NewDictionary = new Dictionary<string, string[]>()
        {
            { "Reference1", Array1 },
            { "Reference2", Array2 },
            { "Reference3", Array3 },
            { "Reference4", Array4 },
            { "Reference5", Array5 }
        };

SQL SERVER: Check if variable is null and then assign statement for Where Clause

Try a case statement

WHERE
CASE WHEN @zipCode IS NULL THEN 1
ELSE @zipCode
END

String to HtmlDocument

you could get a htmldocument by:

 System.Net.WebClient wc = new System.Net.WebClient();

 System.IO.Stream stream = wc.OpenRead(url);
 System.IO.StreamReader reader = new System.IO.StreamReader(stream);
 string s = reader.ReadToEnd();

 HtmlDocument doc = new HtmlDocument();
 doc.LoadHtml(s);

so you have getbiyid and getbyname ... but any further you'd better of with
HTML Agility Pack as suggested . f.e you can do: doc.DocumentNode.SelectNodes(xpathselector) or regex to parse the doc ..

btw: why not regex ? . its soo cool if you can use it right... but xpath is also very mighty ... so "choose your poison"

cu

send checkbox value in PHP form

if(isset($_POST["newsletter"]) && $_POST["newsletter"] == "newsletter"){
    //checked
}

How do I get the offset().top value of an element without using jQuery?

For Angular 2+ to get the offset of the current element (this.el.nativeElement is equvalent of $(this) in jquery):

export class MyComponent implements  OnInit {

constructor(private el: ElementRef) {}

    ngOnInit() {
      //This is the important line you can use in your function in the code
      //-------------------------------------------------------------------------- 
        let offset = this.el.nativeElement.getBoundingClientRect().top;
      //--------------------------------------------------------------------------    

        console.log(offset);
    }

}

Google Maps: Auto close open InfoWindows?

There is a easier way besides using the close() function. if you create a variable with the InfoWindow property it closes automatically when you open another.

var info_window;
var map;
var chicago = new google.maps.LatLng(33.84659, -84.35686);

function initialize() {
    var mapOptions = {
        center: chicago,
        zoom: 14,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

    info_window = new google.maps.InfoWindow({
        content: 'loading'
    )};

createLocationOnMap('Location Name 1', new google.maps.LatLng(33.84659, -84.35686), '<p><strong>Location Name 1</strong><br/>Address 1</p>');
createLocationOnMap('Location Name 2', new google.maps.LatLng(33.84625, -84.36212), '<p><strong>Location Name 1</strong><br/>Address 2</p>');

}

function createLocationOnMap(titulo, posicao, conteudo) {            
    var m = new google.maps.Marker({
        map: map,
        animation: google.maps.Animation.DROP,
        title: titulo,
        position: posicao,
        html: conteudo
    });            

    google.maps.event.addListener(m, 'click', function () {                
        info_window.setContent(this.html);
        info_window.open(map, this);
    });
}

MySQL Incorrect datetime value: '0000-00-00 00:00:00'

I got it fixed by doing this before the query

SET SQL_MODE='ALLOW_INVALID_DATES';

Check whether a string matches a regex in JS

try

 /^[a-z\d]{5,}$/.test(str)

_x000D_
_x000D_
console.log( /^[a-z\d]{5,}$/.test("abc123") );_x000D_
_x000D_
console.log( /^[a-z\d]{5,}$/.test("ab12") );
_x000D_
_x000D_
_x000D_

Move SQL data from one table to another

Use this single sql statement which is safe no need of commit/rollback with multiple statements.

INSERT Table2 (
      username,password
) SELECT username,password
      FROM    (
           DELETE Table1
           OUTPUT
                   DELETED.username,
                   DELETED.password
           WHERE username = 'X' and password = 'X'
      ) AS RowsToMove ;

Works on SQL server make appropriate changes for MySql

C/C++ line number

Checkout __FILE__ and __LINE__ macros

How to convert SSH keypairs generated using PuTTYgen (Windows) into key-pairs used by ssh-agent and Keychain (Linux)

I recently had this problem as I was moving from Putty for Linux to Remmina for Linux. So I have a lot of PPK files for Putty in my .putty directory as I've been using it's for 8 years. For this I used a simple for command for bash shell to do all files:

cd ~/.putty
for X in *.ppk; do puttygen $X -L > ~/.ssh/$(echo $X | sed 's,./,,' | sed 's/.ppk//g').pub; puttygen $X -O private-openssh -o ~/.ssh/$(echo $X | sed 's,./,,' | sed 's/.ppk//g').pvk; done;

Very quick and to the point, got the job done for all files that putty had. If it finds a key with a password it will stop and ask for the password for that key first and then continue.

.attr('checked','checked') does not work

Why not try IS?

$('selector').is(':checked') /* result true or false */

Look a FAQ: jQuery .is() enjoin us ;-)

C# find highest array value and index

If you know max index accessing the max value is immediate. So all you need is max index.

int max=0;

for(int i = 1; i < arr.Length; i++)
    if (arr[i] > arr[max]) max = i;

How to pass text in a textbox to JavaScript function?

As opposed to passing the text as a variable, you can use the DOM to retrieve the data in your function:

var text = document.getElementsByName("textbox1").value;

Converting Integer to String with comma for thousands

First you need to include the JSTL tags :-

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> 

at the start of the page

Most efficient way to see if an ArrayList contains an object in Java

Maybe a List isn't what you need.

Maybe a TreeSet would be a better container. You get O(log N) insertion and retrieval, and ordered iteration (but won't allow duplicates).

LinkedHashMap might be even better for your use case, check that out too.

Programmatically change UITextField Keyboard type

It's worth noting that if you want a currently-focused field to update the keyboard type immediately, there's one extra step:

// textField is set to a UIKeyboardType other than UIKeyboardTypeEmailAddress

[textField setKeyboardType:UIKeyboardTypeEmailAddress];
[textField reloadInputViews];

Without the call to reloadInputViews, the keyboard will not change until the selected field (the first responder) loses and regains focus.

A full list of the UIKeyboardType values can be found here, or:

typedef enum : NSInteger {
    UIKeyboardTypeDefault,
    UIKeyboardTypeASCIICapable,
    UIKeyboardTypeNumbersAndPunctuation,
    UIKeyboardTypeURL,
    UIKeyboardTypeNumberPad,
    UIKeyboardTypePhonePad,
    UIKeyboardTypeNamePhonePad,
    UIKeyboardTypeEmailAddress,
    UIKeyboardTypeDecimalPad,
    UIKeyboardTypeTwitter,
    UIKeyboardTypeWebSearch,
    UIKeyboardTypeAlphabet = UIKeyboardTypeASCIICapable
} UIKeyboardType;

Creating a batch file, for simple javac and java command execution

you want these four lines of code in your Run.bat:

@echo off          //this makes it so you have an empty cmd window on startup
javac Main.java    //this compiles the .java into a .class
java Main          // this runs the .class file
pause              //this prevents the window from instantly closing after program end

Stop setInterval call in JavaScript

This is how I used clearInterval() method to stop the timer after 10 seconds.

_x000D_
_x000D_
function startCountDown() {_x000D_
  var countdownNumberEl = document.getElementById('countdown-number');_x000D_
  var countdown = 10;_x000D_
  const interval = setInterval(() => {_x000D_
    countdown = --countdown <= 0 ? 10 : countdown;_x000D_
    countdownNumberEl.textContent = countdown;_x000D_
    if (countdown == 1) {_x000D_
      clearInterval(interval);_x000D_
    }_x000D_
  }, 1000)_x000D_
}
_x000D_
<head>_x000D_
  <body>_x000D_
    <button id="countdown-number" onclick="startCountDown();">Show Time </button>_x000D_
  </body>_x000D_
</head>
_x000D_
_x000D_
_x000D_

Why can't DateTime.Parse parse UTC date

It can't parse that string because "UTC" is not a valid time zone designator.

UTC time is denoted by adding a 'Z' to the end of the time string, so your parsing code should look like this:

DateTime.Parse("Tue, 1 Jan 2008 00:00:00Z");

From the Wikipedia article on ISO 8601

If the time is in UTC, add a 'Z' directly after the time without a space. 'Z' is the zone designator for the zero UTC offset. "09:30 UTC" is therefore represented as "09:30Z" or "0930Z". "14:45:15 UTC" would be "14:45:15Z" or "144515Z".

UTC time is also known as 'Zulu' time, since 'Zulu' is the NATO phonetic alphabet word for 'Z'.

How to send authorization header with axios

You are nearly correct, just adjust your code this way

const headers = { Authorization: `Bearer ${token}` };
return axios.get(URLConstants.USER_URL, { headers });

notice where I place the backticks, I added ' ' after Bearer, you can omit if you'll be sure to handle at the server-side

Change arrow colors in Bootstraps carousel

I too had a similar problem, some images were very light and some dark, so the arrows didn't always show up clearly so I took a more simplistic approach.

In the modal-body section I just removed the following lines:

    <!-- Left and right controls -->
    <a class="carousel-control-prev" href="#id" data-slide="prev">
       <span class="carousel-control-prev-icon"></span>
    </a>
    <a class="carousel-control-next" href="#id" data-slide="next">
      <span class="carousel-control-next-icon"></span>
    </a>

and inserted the following into the modal-header section

    <!-- Left and right controls -->
    <a  href="#gamespandp" data-slide="prev" class="btn btn-outline-secondary btn-sm">&#10094;</a>
    <a  href="#gamespandp"  data-slide="next" class="btn btn-outline-secondary btn-sm">&#10095;</a>

The indicators can now be clearly seen, no adding extra icons or messing with style sheets, although you could style them however you wanted!

See this demo image:

[demo Image]

Multiple values in single-value context

Yes, there is.

Surprising, huh? You can get a specific value from a multiple return using a simple mute function:

package main

import "fmt"
import "strings"

func µ(a ...interface{}) []interface{} {
    return a
}

type A struct {
    B string
    C func()(string)
}

func main() {
    a := A {
        B:strings.TrimSpace(µ(E())[1].(string)),
        C:µ(G())[0].(func()(string)),
    }

    fmt.Printf ("%s says %s\n", a.B, a.C())
}

func E() (bool, string) {
    return false, "F"
}

func G() (func()(string), bool) {
    return func() string { return "Hello" }, true
}

https://play.golang.org/p/IwqmoKwVm-

Notice how you select the value number just like you would from a slice/array and then the type to get the actual value.

You can read more about the science behind that from this article. Credits to the author.

How to generate range of numbers from 0 to n in ES2015 only?

Here's another variation that doesn't use Array.

let range = (n, l=[], delta=1) => {
  if (n < 0) { 
    return l 
  }
  else {
    l.unshift(n)
    return range(n - delta, l) 
  }
}

jquery simple image slideshow tutorial

Here is my adaptation of Michael Soriano's tutorial. See below or in JSBin.

_x000D_
_x000D_
$(function() {_x000D_
  var theImage = $('ul#ss li img');_x000D_
  var theWidth = theImage.width();_x000D_
  //wrap into mother div_x000D_
  $('ul#ss').wrap('<div id="mother" />');_x000D_
  //assign height width and overflow hidden to mother_x000D_
  $('#mother').css({_x000D_
    width: function() {_x000D_
      return theWidth;_x000D_
    },_x000D_
    height: function() {_x000D_
      return theImage.height();_x000D_
    },_x000D_
    position: 'relative',_x000D_
    overflow: 'hidden'_x000D_
  });_x000D_
  //get total of image sizes and set as width for ul _x000D_
  var totalWidth = theImage.length * theWidth;_x000D_
  $('ul').css({_x000D_
    width: function() {_x000D_
      return totalWidth;_x000D_
    }_x000D_
  });_x000D_
_x000D_
  var ss_timer = setInterval(function() {_x000D_
    ss_next();_x000D_
  }, 3000);_x000D_
_x000D_
  function ss_next() {_x000D_
    var a = $(".active");_x000D_
    a.removeClass('active');_x000D_
_x000D_
    if (a.hasClass('last')) {_x000D_
      //last element -- loop_x000D_
      a.parent('ul').animate({_x000D_
        "margin-left": (0)_x000D_
      }, 1000);_x000D_
      a.siblings(":first").addClass('active');_x000D_
    } else {_x000D_
      a.parent('ul').animate({_x000D_
        "margin-left": (-(a.index() + 1) * theWidth)_x000D_
      }, 1000);_x000D_
      a.next().addClass('active');_x000D_
    }_x000D_
  }_x000D_
_x000D_
  // Cancel slideshow and move next manually on click_x000D_
  $('ul#ss li img').on('click', function() {_x000D_
    clearInterval(ss_timer);_x000D_
    ss_next();_x000D_
  });_x000D_
_x000D_
});
_x000D_
* {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
#ss {_x000D_
  list-style: none;_x000D_
}_x000D_
#ss li {_x000D_
  float: left;_x000D_
}_x000D_
#ss img {_x000D_
  width: 200px;_x000D_
  height: 100px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<ul id="ss">_x000D_
  <li class="active">_x000D_
    <img src="http://leemark.github.io/better-simple-slideshow/demo/img/colorado-colors.jpg">_x000D_
  </li>_x000D_
  <li>_x000D_
    <img src="http://leemark.github.io/better-simple-slideshow/demo/img/monte-vista.jpg">_x000D_
  </li>_x000D_
  <li class="last">_x000D_
    <img src="http://leemark.github.io/better-simple-slideshow/demo/img/colorado.jpg">_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

difference between $query>num_rows() and $this->db->count_all_results() in CodeIgniter & which one is recommended

Simply as bellow;

$this->db->get('table_name')->num_rows();

This will get number of rows/records. however you can use search parameters as well;

$this->db->select('col1','col2')->where('col'=>'crieterion')->get('table_name')->num_rows();

However, it should be noted that you will see bad bad errors if applying as below;

$this->db->get('table_name')->result()->num_rows();

Plot correlation matrix using pandas

If you dataframe is df you can simply use:

import matplotlib.pyplot as plt
import seaborn as sns

plt.figure(figsize=(15, 10))
sns.heatmap(df.corr(), annot=True)

How to add a 'or' condition in #ifdef

#if defined(CONDITION1) || defined(CONDITION2)

should work. :)

#ifdef is a bit less typing, but doesn't work well with more complex conditions

anaconda update all possible packages?

TL;DR: dependency conflicts: Updating one requires (by it's requirements) to downgrade another

You are right:

conda update --all

is actually the way to go1. Conda always tries to upgrade the packages to the newest version in the series (say Python 2.x or 3.x).

Dependency conflicts

But it is possible that there are dependency conflicts (which prevent a further upgrade). Conda usually warns very explicitly if they occur.

e.g. X requires Y <5.0, so Y will never be >= 5.0

That's why you 'cannot' upgrade them all.

Resolving

To add: maybe it could work but a newer version of X working with Y > 5.0 is not available in conda. It is possible to install with pip, since more packages are available in pip. But be aware that pip also installs packages if dependency conflicts exist and that it usually breaks your conda environment in the sense that you cannot reliably install with conda anymore. If you do that, do it as a last resort and after all packages have been installed with conda. It's rather a hack.

A safe way you can try is to add conda-forge as a channel when upgrading (add -c conda-forge as a flag) or any other channel you find that contains your package if you really need this new version. This way conda does also search in this places for available packages.

Considering your update: You can upgrade them each separately, but doing so will not only include an upgrade but also a downgrade of another package as well. Say, to add to the example above:

X > 2.0 requires Y < 5.0, X < 2.0 requires Y > 5.0

So upgrading Y > 5.0 implies downgrading X to < 2.0 and vice versa.

(this is a pedagogical example, of course, but it's the same in reality, usually just with more complicated dependencies and sub-dependencies)

So you still cannot upgrade them all by doing the upgrades separately; the dependencies are just not satisfiable so earlier or later, an upgrade will downgrade an already upgraded package again. Or break the compatibility of the packages (which you usually don't want!), which is only possible by explicitly invoking an ignore-dependencies and force-command. But that is only to hack your way around issues, definitely not the normal-user case!


1 If you actually want to update the packages of your installation, which you usually don't. The command run in the base environment will update the packages in this, but usually you should work with virtual environments (conda create -n myenv and then conda activate myenv). Executing conda update --all inside such an environment will update the packages inside this environment. However, since the base environment is also an environment, the answer applies to both cases in the same way.

CreateProcess error=2, The system cannot find the file specified

The complete first argument of exec is being interpreted as the executable. Use

p = rt.exec(new String[] {"winrar.exe", "x", "h:\\myjar.jar", "*.*", "h:\\new" }
            null, 
            dir);

How can we stop a running java process through Windows cmd?

FOR /F "tokens=1,2 delims= " %%G IN ('jps -l') DO IF %%H==name.for.the.application.main.Class taskkill /F /PID %%G

name.for.the.application.main.Class - replace this to your application's main class (you can find it in second column of jps -l output)

Are there such things as variables within an Excel formula?

You could define a name for the VLOOKUP part of the formula.

  1. Highlight the cell that contains this formula
  2. On the Insert menu, go Name, and click Define
  3. Enter a name for your variable (e.g. 'Value')
  4. In the Refers To box, enter your VLOOKUP formula: =VLOOKUP(A1,B:B, 1, 0)
  5. Click Add, and close the dialog
  6. In your original formula, replace the VLOOKUP parts with the name you just defined: =IF( Value > 10, Value - 10, Value )

Step (1) is important here: I guess on the second row, you want Excel to use VLOOKUP(A2,B:B, 1, 0), the third row VLOOKUP(A3,B:B, 1, 0), etc. Step (4) achieves this by using relative references (A1 and B:B), not absolute references ($A$1 and $B:$B).

Note:

  1. For newer Excel versions with the ribbon, go to Formulas ribbon -> Define Name. It's the same after that. Also, to use your name, you can do "Use in Formula", right under Define Name, while editing the formula, or else start typing it, and Excel will suggest the name (credits: Michael Rusch)

  2. Shortened steps: 1. Right click a cell and click Define name... 2. Enter a name and the formula which you want to associate with that name/local variable 3. Use variable (credits: Jens Bodal)

Best way to compare dates in Android

You can directly create a Calendar from a Date:

Calendar validDate = new GregorianCalendar();
validDate.setTime(strDate);
if (Calendar.getInstance().after(validDate)) {
    catalog_outdated = 1;
}

Base64 length calculation?

Seems to me that the right formula should be:

n64 = 4 * (n / 3) + (n % 3 != 0 ? 4 : 0)

How to find when a web page was last updated

There is another way to find the page update which could be useful for some occasions (if works:).

If the page has been indexed by Google, or by Wayback Machine you can try to find out what date(s) was(were) saved by them (these methods do not work for any page, and have some limitations, which are extensively investigated in this webmasters.stackexchange question's answers. But in many cases they can help you to find out the page update date(s):

  1. Google way: Go by link https://www.google.com.ua/search?q=site%3Awww.example.com&biw=1855&bih=916&source=lnt&tbs=cdr%3A1%2Ccd_min%3A1%2F1%2F2000%2Ccd_max%3A&tbm=
    • You can change text in search field by any page URL you want.
    • For example, the current stackoverflow question page search gives us as a result May 14, 2014 - which is the question creation date: enter image description here
  2. Wayback machine way: Go by link https://web.archive.org/web/*/www.example.com
    • for this stackoverflow page wayback machine gives us more results: Saved 6 times between June 7, 2014 and November 23, 2016., and you can view all saved copies for each date

Get selected value in dropdown list using JavaScript

Another solution is:

document.getElementById('elementId').selectedOptions[0].value

How can I see CakePHP's SQL dump in the controller?

What worked finally for me and also compatible with 2.0 is to add in my layout (or in model)

<?php echo $this->element('sql_dump');?>

It is also depending on debug variable setted into Config/core.php

Open file dialog box in JavaScript

AFAIK you still need an <input type="file"> element, then you can use some of the stuff from quirksmode to style it up

How to run Maven from another directory (without cd to project dir)?

For me, works this way: mvn -f /path/to/pom.xml [goals]

Integer value in TextView

just found an advance and most currently used method to set string in textView

textView.setText(String.valueOf(YourIntegerNumber));

Array.push() if does not exist?

Use a js library like underscore.js for these reasons exactly. Use: union: Computes the union of the passed-in arrays: the list of unique items, in order, that are present in one or more of the arrays.

_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2, 3, 101, 10]

Possible to make labels appear when hovering over a point in matplotlib?

A slight edit on an example provided in http://matplotlib.org/users/shell.html:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('click on points')

line, = ax.plot(np.random.rand(100), '-', picker=5)  # 5 points tolerance


def onpick(event):
    thisline = event.artist
    xdata = thisline.get_xdata()
    ydata = thisline.get_ydata()
    ind = event.ind
    print('onpick points:', *zip(xdata[ind], ydata[ind]))


fig.canvas.mpl_connect('pick_event', onpick)

plt.show()

This plots a straight line plot, as Sohaib was asking

Raise warning in Python without interrupting program

By default, unlike an exception, a warning doesn't interrupt.

After import warnings, it is possible to specify a Warnings class when generating a warning. If one is not specified, it is literally UserWarning by default.

>>> warnings.warn('This is a default warning.')
<string>:1: UserWarning: This is a default warning.

To simply use a preexisting class instead, e.g. DeprecationWarning:

>>> warnings.warn('This is a particular warning.', DeprecationWarning)
<string>:1: DeprecationWarning: This is a particular warning.

Creating a custom warning class is similar to creating a custom exception class:

>>> class MyCustomWarning(UserWarning):
...     pass
... 
... warnings.warn('This is my custom warning.', MyCustomWarning)

<string>:1: MyCustomWarning: This is my custom warning.

For testing, consider assertWarns or assertWarnsRegex.


As an alternative, especially for standalone applications, consider the logging module. It can log messages having a level of debug, info, warning, error, etc. Log messages having a level of warning or higher are by default printed to stderr.

Correct way to work with vector of arrays

Use:

vector<vector<float>> vecArray; //both dimensions are open!

Convert a Python list with strings all to lowercase or uppercase

Besides being easier to read (for many people), list comprehensions win the speed race, too:

$ python2.6 -m timeit '[x.lower() for x in ["A","B","C"]]'
1000000 loops, best of 3: 1.03 usec per loop
$ python2.6 -m timeit '[x.upper() for x in ["a","b","c"]]'
1000000 loops, best of 3: 1.04 usec per loop

$ python2.6 -m timeit 'map(str.lower,["A","B","C"])'
1000000 loops, best of 3: 1.44 usec per loop
$ python2.6 -m timeit 'map(str.upper,["a","b","c"])'
1000000 loops, best of 3: 1.44 usec per loop

$ python2.6 -m timeit 'map(lambda x:x.lower(),["A","B","C"])'
1000000 loops, best of 3: 1.87 usec per loop
$ python2.6 -m timeit 'map(lambda x:x.upper(),["a","b","c"])'
1000000 loops, best of 3: 1.87 usec per loop

What is JavaScript garbage collection?

Beware of circular references when DOM objects are involved:

Memory leak patterns in JavaScript

Keep in mind that memory can only be reclaimed when there are no active references to the object. This is a common pitfall with closures and event handlers, as some JS engines will not check which variables actually are referenced in inner functions and just keep all local variables of the enclosing functions.

Here's a simple example:

function init() {
    var bigString = new Array(1000).join('xxx');
    var foo = document.getElementById('foo');
    foo.onclick = function() {
        // this might create a closure over `bigString`,
        // even if `bigString` isn't referenced anywhere!
    };
}

A naive JS implementation can't collect bigString as long as the event handler is around. There are several ways to solve this problem, eg setting bigString = null at the end of init() (delete won't work for local variables and function arguments: delete removes properties from objects, and the variable object is inaccessible - ES5 in strict mode will even throw a ReferenceError if you try to delete a local variable!).

I recommend to avoid unnecessary closures as much as possible if you care for memory consumption.

SQL grammar for SELECT MIN(DATE)

An aggregate function requires a GROUP BY in standard SQL

This is "Get minimum date per title" in plain language

SELECT title, MIN(date) FROM table GROUP BY title

Most RDBMS and the standard require that column is either in the GROUP BY or in a functions (MIN, COUNT etc): MySQL is the notable exception with some extensions that give unpredictable behaviour

Android: How do I prevent the soft keyboard from pushing my view up?

Well i have watched these answers but in my case i fell into the same issue and got refuge through a very handy and easiest solution that involves putting a very small innocent attribute in your Scrollview tag residing in your xml file. That is

android:isScrollContainer="false"

Good luck!

Get RETURN value from stored procedure in SQL

Assign after the EXEC token:

DECLARE @returnValue INT

EXEC @returnValue = SP_One

Is putting a div inside an anchor ever correct?

Block level elements like <div> can be wrapped by <a> tags in HTML5. Although a <div> is considered to be a container/wrapper for flow content and <a>'s are considered flow content according to MDN. Semantically it may be better to create inline elements that act as block level elements.

Predefined type 'System.ValueTuple´2´ is not defined or imported

Make sure you have .NET 4.6.2 Developer Pack for VS installed and then pull in System.ValueTuple package from NuGet.

How to access parent scope from within a custom directive *with own scope* in AngularJS?

See What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

To summarize: the way a directive accesses its parent ($parent) scope depends on the type of scope the directive creates:

  1. default (scope: false) - the directive does not create a new scope, so there is no inheritance here. The directive's scope is the same scope as the parent/container. In the link function, use the first parameter (typically scope).

  2. scope: true - the directive creates a new child scope that prototypically inherits from the parent scope. Properties that are defined on the parent scope are available to the directive scope (because of prototypal inheritance). Just beware of writing to a primitive scope property -- that will create a new property on the directive scope (that hides/shadows the parent scope property of the same name).

  3. scope: { ... } - the directive creates a new isolate/isolated scope. It does not prototypically inherit the parent scope. You can still access the parent scope using $parent, but this is not normally recommended. Instead, you should specify which parent scope properties (and/or function) the directive needs via additional attributes on the same element where the directive is used, using the =, @, and & notation.

  4. transclude: true - the directive creates a new "transcluded" child scope, which prototypically inherits from the parent scope. If the directive also creates an isolate scope, the transcluded and the isolate scopes are siblings. The $parent property of each scope references the same parent scope.
    Angular v1.3 update: If the directive also creates an isolate scope, the transcluded scope is now a child of the isolate scope. The transcluded and isolate scopes are no longer siblings. The $parent property of the transcluded scope now references the isolate scope.

The above link has examples and pictures of all 4 types.

You cannot access the scope in the directive's compile function (as mentioned here: https://github.com/angular/angular.js/wiki/Dev-Guide:-Understanding-Directives). You can access the directive's scope in the link function.

Watching:

For 1. and 2. above: normally you specify which parent property the directive needs via an attribute, then $watch it:

<div my-dir attr1="prop1"></div>
scope.$watch(attrs.attr1, function() { ... });

If you are watching an object property, you'll need to use $parse:

<div my-dir attr2="obj.prop2"></div>
var model = $parse(attrs.attr2);
scope.$watch(model, function() { ... });

For 3. above (isolate scope), watch the name you give the directive property using the @ or = notation:

<div my-dir attr3="{{prop3}}" attr4="obj.prop4"></div>
scope: {
  localName3: '@attr3',
  attr4:      '='  // here, using the same name as the attribute
},
link: function(scope, element, attrs) {
   scope.$watch('localName3', function() { ... });
   scope.$watch('attr4',      function() { ... });

How to retrieve element value of XML using Java?

If your XML is a String, Then you can do the following:

String xml = ""; //Populated XML String....

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml)));
Element rootElement = document.getDocumentElement();

If your XML is in a file, then Document document will be instantiated like this:

Document document = builder.parse(new File("file.xml"));

The document.getDocumentElement() returns you the node that is the document element of the document (in your case <config>).

Once you have a rootElement, you can access the element's attribute (by calling rootElement.getAttribute() method), etc. For more methods on java's org.w3c.dom.Element

More info on java DocumentBuilder & DocumentBuilderFactory. Bear in mind, the example provided creates a XML DOM tree so if you have a huge XML data, the tree can be huge.


Update Here's an example to get "value" of element <requestqueue>

protected String getString(String tagName, Element element) {
        NodeList list = element.getElementsByTagName(tagName);
        if (list != null && list.getLength() > 0) {
            NodeList subList = list.item(0).getChildNodes();

            if (subList != null && subList.getLength() > 0) {
                return subList.item(0).getNodeValue();
            }
        }

        return null;
    }

You can effectively call it as,

String requestQueueName = getString("requestqueue", element);

how to add values to an array of objects dynamically in javascript?

You have to instantiate the object first. The simplest way is:

var lab =["1","2","3"];
var val = [42,55,51,22];
var data = [];
for(var i=0; i<4; i++)  {
    data.push({label: lab[i], value: val[i]});
}

Or an other, less concise way, but closer to your original code:

for(var i=0; i<4; i++)  {
   data[i] = {};              // creates a new object
   data[i].label = lab[i];
   data[i].value = val[i];    
}

array() will not create a new array (unless you defined that function). Either Array() or new Array() or just [].

I recommend to read the MDN JavaScript Guide.

How to click or tap on a TextView text

OK I have answered my own question (but is it the best way?)

This is how to run a method when you click or tap on some text in a TextView:

package com.textviewy;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class TextyView extends Activity implements OnClickListener {

TextView t ;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    t = (TextView)findViewById(R.id.TextView01);
    t.setOnClickListener(this);
}

public void onClick(View arg0) {
    t.setText("My text on click");  
    }
}

and my main.xml is:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 >
<LinearLayout android:id="@+id/LinearLayout01" android:layout_width="wrap_content"             android:layout_height="wrap_content"></LinearLayout>
<ListView android:id="@+id/ListView01" android:layout_width="wrap_content"   android:layout_height="wrap_content"></ListView>
<LinearLayout android:id="@+id/LinearLayout02" android:layout_width="wrap_content"   android:layout_height="wrap_content"></LinearLayout>

<TextView android:text="This is my first text"
 android:id="@+id/TextView01" 
 android:layout_width="wrap_content" 
 android:textStyle="bold"
 android:textSize="28dip"
 android:editable = "true"
 android:clickable="true"
 android:layout_height="wrap_content">
 </TextView>
 </LinearLayout>

configure: error: C compiler cannot create executables

You have an old set of developer tools. gcc is reporting its version as 4.0.1. This may be left over from migrating from an older version of the OS. If you've installed Xcode 4.3.x, you need to launch it, go into its preferences, select the Downloads tab, and click "Install" next to the Command Line Tools package.

Check difference in seconds between two times

Assuming dateTime1 and dateTime2 are DateTime values:

var diffInSeconds = (dateTime1 - dateTime2).TotalSeconds;

In your case, you 'd use DateTime.Now as one of the values and the time in the list as the other. Be careful of the order, as the result can be negative if dateTime1 is earlier than dateTime2.

How do I get the name of the current executable in C#?

  • System.Reflection.Assembly.GetEntryAssembly().Location returns location of exe name if assembly is not loaded from memory.
  • System.Reflection.Assembly.GetEntryAssembly().CodeBase returns location as URL.

What are all the possible values for HTTP "Content-Type" header?

If you are using jaxrs or any other, then there will be a class called mediatype.User interceptor before sending the request and compare it against this.

JavaScript: Create and save file

For latest browser, like Chrome, you can use the File API as in this tutorial:

window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.PERSISTENT, 5*1024*1024 /*5MB*/, saveFile, errorHandler);

How can I easily switch between PHP versions on Mac OSX?

If you have both versions of PHP installed, you can switch between versions using the link and unlink brew commands.

For example, to switch between PHP 7.4 and PHP 7.3

brew unlink [email protected]
brew link [email protected]

PS: both versions of PHP have be installed for these commands to work.

Place a button right aligned

To keep the button in the page flow:

<input type="button" value="Click Me" style="margin-left: auto; display: block;" />

(put that style in a .css file, do not use this html inline, for better maintenance)

How to print without newline or space?

The new (as of Python 3.x) print function has an optional end parameter that lets you modify the ending character:

print("HELLO", end="")
print("HELLO")

Output:

HELLOHELLO

There's also sep for separator:

print("HELLO", "HELLO", "HELLO", sep="")

Output:

HELLOHELLOHELLO

If you wanted to use this in Python 2.x just add this at the start of your file:

from __future__ import print_function

Node.js - use of module.exports as a constructor

The example code is:

in main

square(width,function (data)
{
   console.log(data.squareVal);
});

using the following may works

exports.square = function(width,callback)
{
     var aa = new Object();
     callback(aa.squareVal = width * width);    
}

Windows Batch Files: if else

An alternative would be to set a variable, and check whether it is defined:

SET ARG=%1
IF DEFINED ARG (echo "It is defined: %1") ELSE (echo "%%1 is not defined")

Unfortunately, using %1 directly with DEFINED doesn't work.

Default value for field in Django model

Set editable to False and default to your default value.

http://docs.djangoproject.com/en/stable/ref/models/fields/#editable

b = models.CharField(max_length=7, default='0000000', editable=False)

Also, your id field is unnecessary. Django will add it automatically.

Changing java platform on which netbeans runs

You can change the JDK for Netbeans by modifying the config file:

  1. Open netbeans.conf file available under etc folder inside the NetBeans installation.
  2. Modify the netbeans_jdkhome variable to point to new JDK path, and then
  3. Restart your Netbeans.

How do you get the list of targets in a makefile?

I usually do:

grep install_targets Makefile

It would come back with something like:

install_targets = install-xxx1 install-xxx2 ... etc

I hope this helps

How to implement a secure REST API with node.js

If you want to secure your application, then you should definitely start by using HTTPS instead of HTTP, this ensures a creating secure channel between you & the users that will prevent sniffing the data sent back & forth to the users & will help keep the data exchanged confidential.

You can use JWTs (JSON Web Tokens) to secure RESTful APIs, this has many benefits when compared to the server-side sessions, the benefits are mainly:

1- More scalable, as your API servers will not have to maintain sessions for each user (which can be a big burden when you have many sessions)

2- JWTs are self contained & have the claims which define the user role for example & what he can access & issued at date & expiry date (after which JWT won't be valid)

3- Easier to handle across load-balancers & if you have multiple API servers as you won't have to share session data nor configure server to route the session to same server, whenever a request with a JWT hit any server it can be authenticated & authorized

4- Less pressure on your DB as well as you won't have to constantly store & retrieve session id & data for each request

5- The JWTs can't be tampered with if you use a strong key to sign the JWT, so you can trust the claims in the JWT that is sent with the request without having to check the user session & whether he is authorized or not, you can just check the JWT & then you are all set to know who & what this user can do.

Many libraries provide easy ways to create & validate JWTs in most programming languages, for example: in node.js one of the most popular is jsonwebtoken

Since REST APIs generally aims to keep the server stateless, so JWTs are more compatible with that concept as each request is sent with Authorization token that is self contained (JWT) without the server having to keep track of user session compared to sessions which make the server stateful so that it remembers the user & his role, however, sessions are also widely used & have their pros, which you can search for if you want.

One important thing to note is that you have to securely deliver the JWT to the client using HTTPS & save it in a secure place (for example in local storage).

You can learn more about JWTs from this link

How do I use WebRequest to access an SSL encrypted site using https?

You're doing it the correct way but users may be providing urls to sites that have invalid SSL certs installed. You can ignore those cert problems if you put this line in before you make the actual web request:

ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

where AcceptAllCertifications is defined as

public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
    return true;
}

Spark read file from S3 using sc.textFile ("s3n://...)

You can add the --packages parameter with the appropriate jar: to your submission:

bin/spark-submit --packages com.amazonaws:aws-java-sdk-pom:1.10.34,org.apache.hadoop:hadoop-aws:2.6.0 code.py

jQuery "blinking highlight" effect on div?

Check it out -

<input type="button" id="btnclick" value="click" />
var intervalA;
        var intervalB;

        $(document).ready(function () {

            $('#btnclick').click(function () {
                blinkFont();

                setTimeout(function () {
                    clearInterval(intervalA);
                    clearInterval(intervalB);
                }, 5000);
            });
        });

        function blinkFont() {
            document.getElementById("blink").style.color = "red"
            document.getElementById("blink").style.background = "black"
            intervalA = setTimeout("blinkFont()", 500);
        }

        function setblinkFont() {
            document.getElementById("blink").style.color = "black"
            document.getElementById("blink").style.background = "red"
            intervalB = setTimeout("blinkFont()", 500);
        }

    </script>

    <div id="blink" class="live-chat">
        <span>This is blinking text and background</span>
    </div>

Adding Git-Bash to the new Windows Terminal

If you want to display an icon and are using a dark theme. Which means the icon provided above doesn't look that great. Then you can find the icon here

C:\Program Files\Git\mingw64\share\git\git-for-windows I copied it into.

%LOCALAPPDATA%\packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\RoamingState

and named it git-bash_32px as suggested above.

Control the opacity with CTRL + SHIFT + scrolling.

        {
            "acrylicOpacity" : 0.75,
            "closeOnExit" : true,
            "colorScheme" : "Campbell",
            "commandline" : "\"%PROGRAMFILES%\\git\\usr\\bin\\bash.exe\" -i -l",
            "cursorColor" : "#FFFFFF",
            "cursorShape" : "bar",
            "fontFace" : "Consolas",
            "fontSize" : 10,
            "guid" : "{73225108-7633-47ae-80c1-5d00111ef646}",
            "historySize" : 9001,
            "icon" : "ms-appdata:///roaming/git-bash_32px.ico",
            "name" : "Bash",
            "padding" : "0, 0, 0, 0",
            "snapOnInput" : true,
            "startingDirectory" : "%USERPROFILE%",
            "useAcrylic" : true
        },

How do I put double quotes in a string in vba?

Another work-around is to construct a string with a temporary substitute character. Then you can use REPLACE to change each temp character to the double quote. I use tilde as the temporary substitute character.

Here is an example from a project I have been working on. This is a little utility routine to repair a very complicated formula if/when the cell gets stepped on accidentally. It is a difficult formula to enter into a cell, but this little utility fixes it instantly.

Sub RepairFormula()
Dim FormulaString As String

FormulaString = "=MID(CELL(~filename~,$A$1),FIND(~[~,CELL(~filename~,$A$1))+1,FIND(~]~, CELL(~filename~,$A$1))-FIND(~[~,CELL(~filename~,$A$1))-1)"
FormulaString = Replace(FormulaString, Chr(126), Chr(34)) 'this replaces every instance of the tilde with a double quote.
Range("WorkbookFileName").Formula = FormulaString

This is really just a simple programming trick, but it makes entering the formula in your VBA code pretty easy.

Regular expressions in C: examples?

Regular expressions actually aren't part of ANSI C. It sounds like you might be talking about the POSIX regular expression library, which comes with most (all?) *nixes. Here's an example of using POSIX regexes in C (based on this):

#include <regex.h>        
regex_t regex;
int reti;
char msgbuf[100];

/* Compile regular expression */
reti = regcomp(&regex, "^a[[:alnum:]]", 0);
if (reti) {
    fprintf(stderr, "Could not compile regex\n");
    exit(1);
}

/* Execute regular expression */
reti = regexec(&regex, "abc", 0, NULL, 0);
if (!reti) {
    puts("Match");
}
else if (reti == REG_NOMATCH) {
    puts("No match");
}
else {
    regerror(reti, &regex, msgbuf, sizeof(msgbuf));
    fprintf(stderr, "Regex match failed: %s\n", msgbuf);
    exit(1);
}

/* Free memory allocated to the pattern buffer by regcomp() */
regfree(&regex);

Alternatively, you may want to check out PCRE, a library for Perl-compatible regular expressions in C. The Perl syntax is pretty much that same syntax used in Java, Python, and a number of other languages. The POSIX syntax is the syntax used by grep, sed, vi, etc.

What is the printf format specifier for bool?

In the tradition of itoa():

#define btoa(x) ((x)?"true":"false")

bool x = true;
printf("%s\n", btoa(x));

Can someone explain how to append an element to an array in C programming?

There are only two ways to put a value into an array, and one is just syntactic sugar for the other:

a[i] = v;
*(a+i) = v;

Thus, to put something as the 4th element, you don't have any choice but arr[4] = 5. However, it should fail in your code, because the array is only allocated for 4 elements.

Aborting a stash pop in Git

If you don't have to worry about any other changes you made and you just want to go back to the last commit, then you can do:

git reset .
git checkout .
git clean -f

Convert date from 'Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)' to 'YYYY-MM-DD' in javascript

The easiest way for me to convert a date was to stringify it then slice it.

var event = new Date("Fri Apr 05 2019 16:59:00 GMT-0700 (Pacific Daylight Time)");

let date = JSON.stringify(event)
date = date.slice(1,11)

// console.log(date) = '2019-04-05'

How to set session attribute in java?

Try this.

<%@page language="java" session="true" %>

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

I have been getting similar error, and just want to share with you. maybe it will help someone.

If you want to use EntityManagerFactory to get an EntityManager, make sure that you will use:

<persistence-unit name="name" transaction-type="RESOURCE_LOCAL">

and not:

<persistence-unit name="name" transaction-type="JPA">

in persistance.xml

clean and rebuild project, it should help.

Preferred Java way to ping an HTTP URL for availability

You could also use HttpURLConnection, which allows you to set the request method (to HEAD for example). Here's an example that shows how to send a request, read the response, and disconnect.

Reverse the ordering of words in a string

In Python, if you can't use [::-1] or reversed(), here is the simple way:

def reverse(text):

  r_text = text.split(" ")
  res = []
  for word in range(len(r_text) - 1, -1, -1): 
    res.append(r_text[word])

  return " ".join(res)

print (reverse("Hello World"))

>> World Hello
[Finished in 0.1s]

How can I add raw data body to an axios request?

Here is my solution:

axios({
  method: "POST",
  url: "https://URL.com/api/services/fetchQuizList",
  headers: {
    "x-access-key": data,
    "x-access-token": token,
  },
  data: {
    quiz_name: quizname,
  },
})
.then(res => {
  console.log("res", res.data.message);
})
.catch(err => {
  console.log("error in request", err);
});

This should help

Print a div using javascript in angularJS single page application

$scope.printDiv = function(divName) {
  var printContents = document.getElementById(divName).innerHTML;
  var popupWin = window.open('', '_blank', 'width=300,height=300');
  popupWin.document.open();
  popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
  popupWin.document.close();
} 

Reading *.wav files in Python

If you want to procces an audio block by block, some of the given solutions are quite awful in the sense that they imply loading the whole audio into memory producing many cache misses and slowing down your program. python-wavefile provides some pythonic constructs to do NumPy block-by-block processing using efficient and transparent block management by means of generators. Other pythonic niceties are context manager for files, metadata as properties... and if you want the whole file interface, because you are developing a quick prototype and you don't care about efficency, the whole file interface is still there.

A simple example of processing would be:

import sys
from wavefile import WaveReader, WaveWriter

with WaveReader(sys.argv[1]) as r :
    with WaveWriter(
            'output.wav',
            channels=r.channels,
            samplerate=r.samplerate,
            ) as w :

        # Just to set the metadata
        w.metadata.title = r.metadata.title + " II"
        w.metadata.artist = r.metadata.artist

        # This is the prodessing loop
        for data in r.read_iter(size=512) :
            data[1] *= .8     # lower volume on the second channel
            w.write(data)

The example reuses the same block to read the whole file, even in the case of the last block that usually is less than the required size. In this case you get an slice of the block. So trust the returned block length instead of using a hardcoded 512 size for any further processing.

How do you create a custom AuthorizeAttribute in ASP.NET Core?

I'm the asp.net security person. Firstly let me apologize that none of this is documented yet outside of the music store sample or unit tests, and it's all still being refined in terms of exposed APIs. Detailed documentation is here.

We don't want you writing custom authorize attributes. If you need to do that we've done something wrong. Instead, you should be writing authorization requirements.

Authorization acts upon Identities. Identities are created by authentication.

You say in comments you want to check a session ID in a header. Your session ID would be the basis for identity. If you wanted to use the Authorize attribute you'd write an authentication middleware to take that header and turn it into an authenticated ClaimsPrincipal. You would then check that inside an authorization requirement. Authorization requirements can be as complicated as you like, for example here's one that takes a date of birth claim on the current identity and will authorize if the user is over 18;

public class Over18Requirement : AuthorizationHandler<Over18Requirement>, IAuthorizationRequirement
{
        public override void Handle(AuthorizationHandlerContext context, Over18Requirement requirement)
        {
            if (!context.User.HasClaim(c => c.Type == ClaimTypes.DateOfBirth))
            {
                context.Fail();
                return;
            }

            var dateOfBirth = Convert.ToDateTime(context.User.FindFirst(c => c.Type == ClaimTypes.DateOfBirth).Value);
            int age = DateTime.Today.Year - dateOfBirth.Year;
            if (dateOfBirth > DateTime.Today.AddYears(-age))
            {
                age--;
            }

            if (age >= 18)
            {
                context.Succeed(requirement);
            }
            else
            {
                context.Fail();
            }
        }
    }
}

Then in your ConfigureServices() function you'd wire it up

services.AddAuthorization(options =>
{
    options.AddPolicy("Over18", 
        policy => policy.Requirements.Add(new Authorization.Over18Requirement()));
});

And finally, apply it to a controller or action method with

[Authorize(Policy = "Over18")]

What's the console.log() of java?

The Log class:

API for sending log output.

Generally, use the Log.v() Log.d() Log.i() Log.w() and Log.e() methods.

The order in terms of verbosity, from least to most is ERROR, WARN, INFO, DEBUG, VERBOSE. Verbose should never be compiled into an application except during development. Debug logs are compiled in but stripped at runtime. Error, warning and info logs are always kept.

Outside of Android, System.out.println(String msg) is used.

uint8_t vs unsigned char

That is really important for example when you are writing a network analyzer. packet headers are defined by the protocol specification, not by the way a particular platform's C compiler works.

When to use MyISAM and InnoDB?

Use MyISAM for very unimportant data or if you really need those minimal performance advantages. The read performance is not better in every case for MyISAM.

I would personally never use MyISAM at all anymore. Choose InnoDB and throw a bit more hardware if you need more performance. Another idea is to look at database systems with more features like PostgreSQL if applicable.

EDIT: For the read-performance, this link shows that innoDB often is actually not slower than MyISAM: https://www.percona.com/blog/2007/01/08/innodb-vs-myisam-vs-falcon-benchmarks-part-1/

How do I pass data to Angular routed components?

It is 2019 and many of the answers here would work, depending on what you want to do. If you want to pass in some internal state not visible in URL (params, query) you can use state since 7.2 (as I have learned just today :) ).

From the blog (credits Tomasz Kula) - you navigate to route....

...from ts: this.router.navigateByUrl('/details', { state: { hello: 'world' } });

...from HTML template: <a routerLink="/details" [state]="{ hello: 'world' }">Go</a>

And to pick it up in the target component:

constructor(public activatedRoute: ActivatedRoute) {}

  ngOnInit() {
    this.state$ = this.activatedRoute.paramMap
      .pipe(map(() => window.history.state))
  }

Late, but hope this helps someone with recent Angular.

Use of Java's Collections.singletonList()?

From the javadoc

@param  the sole object to be stored in the returned list.
@return an immutable list containing only the specified object.

example

import java.util.*;

public class HelloWorld {
    public static void main(String args[]) {
        // create an array of string objs
        String initList[] = { "One", "Two", "Four", "One",};

        // create one list
        List list = new ArrayList(Arrays.asList(initList));

        System.out.println("List value before: "+list);

        // create singleton list
        list = Collections.singletonList("OnlyOneElement");
        list.add("five"); //throws UnsupportedOperationException
        System.out.println("List value after: "+list);
    }
}

Use it when code expects a read-only list, but you only want to pass one element in it. singletonList is (thread-)safe and fast.

Get div tag scroll position using JavaScript

you use the scrollTop attribute

var position = document.getElementById('id').scrollTop;

sed edit file in place

Versions of sed that support the -i option for editing a file in place write to a temporary file and then rename the file.

Alternatively, you can just use ed. For example, to change all occurrences of foo to bar in the file file.txt, you can do:

echo ',s/foo/bar/g; w' | tr \; '\012' | ed -s file.txt

Syntax is similar to sed, but certainly not exactly the same.

Even if you don't have a -i supporting sed, you can easily write a script to do the work for you. Instead of sed -i 's/foo/bar/g' file, you could do inline file sed 's/foo/bar/g'. Such a script is trivial to write. For example:

#!/bin/sh
IN=$1
shift
trap 'rm -f "$tmp"' 0
tmp=$( mktemp )
<"$IN" "$@" >"$tmp" && cat "$tmp" > "$IN"  # preserve hard links

should be adequate for most uses.

How to convert a timezone aware string to datetime in Python without dateutil?

I'm new to Python, but found a way to convert

2017-05-27T07:20:18.000-04:00 to

2017-05-27T07:20:18 without downloading new utilities.

from datetime import datetime, timedelta

time_zone1 = int("2017-05-27T07:20:18.000-04:00"[-6:][:3])
>>returns -04

item_date = datetime.strptime("2017-05-27T07:20:18.000-04:00".replace(".000", "")[:-6], "%Y-%m-%dT%H:%M:%S") + timedelta(hours=-time_zone1)

I'm sure there are better ways to do this without slicing up the string so much, but this got the job done.

PHPUnit assert that an exception was thrown?

An alternative way can be the following:

$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Expected Exception Message');

Please ensure that your test class extents \PHPUnit_Framework_TestCase.

How to import a JSON file in ECMAScript 6?

A bit late, but I just stumbled across the same problem while trying to provide analytics for my web app that involved sending app version based on the package.json version.

Configuration is as follows: React + Redux, Webpack 3.5.6

The json-loader isn't doing much since Webpack 2+, so after some fiddling with it, I ended up removing it.

The solution that actually worked for me, was simply using fetch. While this will most probably enforce some code changes to adapt to the async approach, it worked perfectly, especially given the fact that fetch will offer json decoding on the fly.

So here it is:

  fetch('../../package.json')
  .then(resp => resp.json())
  .then((packageJson) => {
    console.log(packageJson.version);
  });

Do keep in mind, that since we're talking about package.json specifically here, the file will not usually come bundled in your production build (or even dev for that matter), so you will have to use the CopyWebpackPlugin to have access to it when using fetch.

Understanding __get__ and __set__ and Python descriptors

I tried (with minor changes as suggested) the code from Andrew Cooke's answer. (I am running python 2.7).

The code:

#!/usr/bin/env python
class Celsius:
    def __get__(self, instance, owner): return 9 * (instance.fahrenheit + 32) / 5.0
    def __set__(self, instance, value): instance.fahrenheit = 32 + 5 * value / 9.0

class Temperature:
    def __init__(self, initial_f): self.fahrenheit = initial_f
    celsius = Celsius()

if __name__ == "__main__":

    t = Temperature(212)
    print(t.celsius)
    t.celsius = 0
    print(t.fahrenheit)

The result:

C:\Users\gkuhn\Desktop>python test2.py
<__main__.Celsius instance at 0x02E95A80>
212

With Python prior to 3, make sure you subclass from object which will make the descriptor work correctly as the get magic does not work for old style classes.

Filter output in logcat by tagname

Do not depend on ADB shell, just treat it (the adb logcat) a normal linux output and then pip it:

$ adb shell logcat | grep YouTag
# just like: 
$ ps -ef | grep your_proc 

How to use jQuery to get the current value of a file input field

Jquery works differently in IE and other browsers. You can access the last file name by using

alert($('input').attr('value'));

In IE the above alert will give the complete path but in other browsers it will give only the file name.

How to link to a <div> on another page?

You simply combine the ideas of a link to another page, as with href=foo.html, and a link to an element on the same page, as with href=#bar, so that the fragment like #bar is written immediately after the URL that refers to another page:

<a href="foo.html#bar">Some nice link text</a>

The target is specified the same was as when linking inside one page, e.g.

<div id="bar">
<h2>Some heading</h2>
Some content
</div>

or (if you really want to link specifically to a heading only)

<h2 id="bar">Some heading</h2>

C programming: Dereferencing pointer to incomplete type error

The reason why you're getting that error is because you've declared your struct as:

struct {
 char name[32];
 int  size;
 int  start;
 int  popularity;
} stasher_file;

This is not declaring a stasher_file type. This is declaring an anonymous struct type and is creating a global instance named stasher_file.

What you intended was:

struct stasher_file {
 char name[32];
 int  size;
 int  start;
 int  popularity;
};

But note that while Brian R. Bondy's response wasn't correct about your error message, he's right that you're trying to write into the struct without having allocated space for it. If you want an array of pointers to struct stasher_file structures, you'll need to call malloc to allocate space for each one:

struct stasher_file *newFile = malloc(sizeof *newFile);
if (newFile == NULL) {
   /* Failure handling goes here. */
}
strncpy(newFile->name, name, 32);
newFile->size = size;
...

(BTW, be careful when using strncpy; it's not guaranteed to NUL-terminate.)

Add views in UIStackView programmatically

Swift 5 version of Oleg Popov's answer, which is based on user1046037's answer

//Image View
let imageView = UIImageView()
imageView.backgroundColor = UIColor.blue
imageView.heightAnchor.constraint(equalToConstant: 120.0).isActive = true
imageView.widthAnchor.constraint(equalToConstant: 120.0).isActive = true
imageView.image = UIImage(named: "buttonFollowCheckGreen")

//Text Label
let textLabel = UILabel()
textLabel.backgroundColor = UIColor.yellow
textLabel.widthAnchor.constraint(equalToConstant: self.view.frame.width).isActive = true
textLabel.heightAnchor.constraint(equalToConstant: 20.0).isActive = true
textLabel.text  = "Hi World"
textLabel.textAlignment = .center

//Stack View
let stackView   = UIStackView()
stackView.axis  = NSLayoutConstraint.Axis.vertical
stackView.distribution  = UIStackView.Distribution.equalSpacing
stackView.alignment = UIStackView.Alignment.center
stackView.spacing   = 16.0

stackView.addArrangedSubview(imageView)
stackView.addArrangedSubview(textLabel)
stackView.translatesAutoresizingMaskIntoConstraints = false

self.view.addSubview(stackView)

//Constraints
stackView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
stackView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true

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

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

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

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

How to remove a Gitlab project?

Goto

Setting->Advance(Expand it)->RemoveProject 

click After The Remove Project button Browser Display One Confirm Box Then Click On Ok and remove your project from Gitlab

enter image description here

The ScriptManager must appear before any controls that need it

The ScriptManager is a control that needs to be added to the page you have created.

Take a look at this Sample AJAX Application.

<body>
    <form runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        ...
    </form>
</body>

How to get logged-in user's name in Access vba?

In a Form, Create a text box, with in text box properties select data tab

Default value =CurrentUser()

Current source "select table field name"

It will display current user log on name in text box / label as well as saves the user name in the table field

How to prompt for user input and read command-line arguments

If it's a 3.x version then just simply use:

variantname = input()

For example, you want to input 8:

x = input()
8

x will equal 8 but it's going to be a string except if you define it otherwise.

So you can use the convert command, like:

a = int(x) * 1.1343
print(round(a, 2)) # '9.07'
9.07

Converting ArrayList to Array in java

What you did with the iteration is not wrong from what I can make of it based on the question. It gives you a valid array of String objects. Like mentioned in another answer it is however easier to use the toArray() method available for the ArrayList object => http://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html#toArray%28%29

Just a side note. If you would iterate your dsf array properly and print each element on its own you would get valid output. Like this:

for(String str : dsf){
   System.out.println(str);
}

What you probably tried to do was print the complete Array object at once since that would give an object memory address like you got in your question. If you see that kind of output you need to provide a toString() method for the object you're printing.

jQuery - disable selected options

pls try this,

$('#select_id option[value="'+value+'"]').attr("disabled", true);

Is it possible to clone html element objects in JavaScript / JQuery?

Yes, you can copy children of one element and paste them into the other element:

var foo1 = jQuery('#foo1');
var foo2 = jQuery('#foo2');

foo1.html(foo2.children().clone());

Proof: http://jsfiddle.net/de9kc/

Math functions in AngularJS bindings

Better option is to use :

{{(100*score/questionCounter) || 0 | number:0}}

It sets default value of equation to 0 in the case when values are not initialized.

Eloquent ->first() if ->exists()

(ps - I couldn't comment) I think your best bet is something like you've done, or similar to:

$user = User::where('mobile', Input::get('mobile'));
$user->exists() and $user = $user->first();

Oh, also: count() instead if exists but this could be something used after get.

JavaScript listener, "keypress" doesn't detect backspace?

KeyPress event is invoked only for character (printable) keys, KeyDown event is raised for all including nonprintable such as Control, Shift, Alt, BackSpace, etc.

UPDATE:

The keypress event is fired when a key is pressed down and that key normally produces a character value

Reference.

HashSet vs. List performance

Whether to use a HashSet<> or List<> comes down to how you need to access your collection. If you need to guarantee the order of items, use a List. If you don't, use a HashSet. Let Microsoft worry about the implementation of their hashing algorithms and objects.

A HashSet will access items without having to enumerate the collection (complexity of O(1) or near it), and because a List guarantees order, unlike a HashSet, some items will have to be enumerated (complexity of O(n)).

Jquery UI Datepicker not displaying

Try putting the z-index of your datepicker css a lot higher (eg z-index: 1000). The datepicker is probably shown under your original content. I had the same problem and this helped me out.

Access denied for user 'root'@'localhost' (using password: YES) (Mysql::Error)

From my answer here, thought this might be useful:

I tried many steps to get this issue corrected. There are so many sources for possible solutions to this issue that is is hard to filter out the sense from the nonsense. I finally found a good solution here:

Step 1: Identify the Database Version

$ mysql --version

You'll see some output like this with MySQL:

$ mysql  Ver 14.14 Distrib 5.7.16, for Linux (x86_64) using  EditLine wrapper

Or output like this for MariaDB:

mysql  Ver 15.1 Distrib 5.5.52-MariaDB, for Linux (x86_64) using readline 5.1

Make note of which database and which version you're running, as you'll use them later. Next, you need to stop the database so you can access it manually.

Step 2: Stopping the Database Server

To change the root password, you have to shut down the database server beforehand.

You can do that for MySQL with:

$ sudo systemctl stop mysql

And for MariaDB with:

$ sudo systemctl stop mariadb

Step 3: Restarting the Database Server Without Permission Checking

If you run MySQL and MariaDB without loading information about user privileges, it will allow you to access the database command line with root privileges without providing a password. This will allow you to gain access to the database without knowing it.

To do this, you need to stop the database from loading the grant tables, which store user privilege information. Because this is a bit of a security risk, you should also skip networking as well to prevent other clients from connecting.

Start the database without loading the grant tables or enabling networking:

$ sudo mysqld_safe --skip-grant-tables --skip-networking &

The ampersand at the end of this command will make this process run in the background so you can continue to use your terminal.

Now you can connect to the database as the root user, which should not ask for a password.

$ mysql -u root

You'll immediately see a database shell prompt instead.

MySQL Prompt

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

MariaDB Prompt

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]>

Now that you have root access, you can change the root password.

Step 4: Changing the Root Password

mysql> FLUSH PRIVILEGES;

Now we can actually change the root password.

For MySQL 5.7.6 and newer as well as MariaDB 10.1.20 and newer, use the following command:

mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';

For MySQL 5.7.5 and older as well as MariaDB 10.1.20 and older, use:

mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_password');

Make sure to replace new_password with your new password of choice.

Note: If the ALTER USER command doesn't work, it's usually indicative of a bigger problem. However, you can try UPDATE ... SET to reset the root password instead.

[IMPORTANT] This is the specific line that fixed my particular issue:

mysql> UPDATE mysql.user SET authentication_string = PASSWORD('new_password') WHERE User = 'root' AND Host = 'localhost';

Remember to reload the grant tables after this.

In either case, you should see confirmation that the command has been successfully executed.

Query OK, 0 rows affected (0.00 sec)

The password has been changed, so you can now stop the manual instance of the database server and restart it as it was before.

Step 5: Restart the Database Server Normally

The tutorial goes into some further steps to restart the database, but the only piece I used was this:

For MySQL, use: $ sudo systemctl start mysql

For MariaDB, use:

$ sudo systemctl start mariadb

Now you can confirm that the new password has been applied correctly by running:

$ mysql -u root -p

The command should now prompt for the newly assigned password. Enter it, and you should gain access to the database prompt as expected.

Conclusion

You now have administrative access to the MySQL or MariaDB server restored. Make sure the new root password you choose is strong and secure and keep it in safe place.

How do I use arrays in cURL POST requests

You are just creating your array incorrectly. You could use http_build_query:

$fields = array(
            'username' => "annonymous",
            'api_key' => urlencode("1234"),
            'images' => array(
                 urlencode(base64_encode('image1')),
                 urlencode(base64_encode('image2'))
            )
        );
$fields_string = http_build_query($fields);

So, the entire code that you could use would be:

<?php
//extract data from the post
extract($_POST);

//set POST variables
$url = 'http://api.example.com/api';
$fields = array(
            'username' => "annonymous",
            'api_key' => urlencode("1234"),
            'images' => array(
                 urlencode(base64_encode('image1')),
                 urlencode(base64_encode('image2'))
            )
        );

//url-ify the data for the POST
$fields_string = http_build_query($fields);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);
echo $result;

//close connection
curl_close($ch);
?>

What are metaclasses in Python?

The type() function can return the type of an object or create a new type,

for example, we can create a Hi class with the type() function and do not need to use this way with class Hi(object):

def func(self, name='mike'):
    print('Hi, %s.' % name)

Hi = type('Hi', (object,), dict(hi=func))
h = Hi()
h.hi()
Hi, mike.

type(Hi)
type

type(h)
__main__.Hi

In addition to using type() to create classes dynamically, you can control creation behavior of class and use metaclass.

According to the Python object model, the class is the object, so the class must be an instance of another certain class. By default, a Python class is instance of the type class. That is, type is metaclass of most of the built-in classes and metaclass of user-defined classes.

class ListMetaclass(type):
    def __new__(cls, name, bases, attrs):
        attrs['add'] = lambda self, value: self.append(value)
        return type.__new__(cls, name, bases, attrs)

class CustomList(list, metaclass=ListMetaclass):
    pass

lst = CustomList()
lst.add('custom_list_1')
lst.add('custom_list_2')

lst
['custom_list_1', 'custom_list_2']

Magic will take effect when we passed keyword arguments in metaclass, it indicates the Python interpreter to create the CustomList through ListMetaclass. new (), at this point, we can modify the class definition, for example, and add a new method and then return the revised definition.

How do I detect the Python version at runtime?

The best solution depends on how much code is incompatible. If there are a lot of places you need to support Python 2 and 3, six is the compatibility module. six.PY2 and six.PY3 are two booleans if you want to check the version.

However, a better solution than using a lot of if statements is to use six compatibility functions if possible. Hypothetically, if Python 3000 has a new syntax for next, someone could update six so your old code would still work.

import six

#OK
if six.PY2:
  x = it.next() # Python 2 syntax
else:
  x = next(it) # Python 3 syntax

#Better
x = six.next(it)

http://pythonhosted.org/six/

Cheers

XAMPP Apache Webserver localhost not working on MAC OS

I had success with easy killing all active httpd processes in Monitor Activity tool:

1) close XAMPP control

2) open Monitor Activity

3) select filter for All processes (default is My processes)

4) in fulltext search type: httpd

5) kill all showen items

6) relaunch XAMPP control and launch apache again

Get AVG ignoring Null or Zero values

In Case of not considering '0' or 'NULL' in average function. Simply use

AVG(NULLIF(your_column_name,0))

Split string and get first value only

You can do it:

var str = "Doctor Who,Fantasy,Steven Moffat,David Tennant";

var title = str.Split(',').First();

Also you can do it this way:

var index = str.IndexOf(",");
var title = index < 0 ? str : str.Substring(0, index);

How can I force users to access my page over HTTPS instead of HTTP?

Use $_SERVER['HTTPS'] to tell if it is SSL, and redirect to the right place if not.

And remember, the page that displays the form does not need to be fed via HTTPS, it's the post back URL that needs it most.

Edit: yes, as is pointed out below, it's best to have the entire process in HTTPS. It's much more reassuring - I was pointing out that the post is the most critical part. Also, you need to take care that any cookies are set to be secure, so they will only be sent via SSL. The mod_rewrite solution is also very nifty, I've used it to secure a lot of applications on my own website.

Placing a textview on top of imageview in android

you can try this too. I use just framelayout.

 <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/cover"
                android:gravity="bottom">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:text="Hello !"
                    android:id="@+id/welcomeTV"
                    android:textColor="@color/textColor"
                    android:layout_gravity="left|bottom" />
            </FrameLayout>

Identify duplicates in a List

This also works:

public static Set<Integer> findDuplicates(List<Integer> input) {
    List<Integer> copy = new ArrayList<Integer>(input);
    for (Integer value : new HashSet<Integer>(input)) {
        copy.remove(value);
    }
    return new HashSet<Integer>(copy);
}

"No backupset selected to be restored" SQL Server 2012

In my case, it was a permissions issue.

enter image description here

For the Windows user, I was using did not have dbcreator role.

So I followed the below steps

  1. Connect as sa to the SQL server
  2. Expand Security in Object Explorer
  3. Expand Logins
  4. Right click on the Windows user in question
  5. Click on Properties
  6. Select Server Roles from Select a page options
  7. Check dbcreator role for the user
  8. Click OK

enter image description here

How to decrypt the password generated by wordpress

This is one of the proposed solutions found in the article Jacob mentioned, and it worked great as a manual way to change the password without having to use the email reset.

  1. In the DB table wp_users, add a key, like abc123 to the user_activation column.
  2. Visit yoursite.com/wp-login.php?action=rp&key=abc123&login=yourusername
  3. You will be prompted to enter a new password.

The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path

Add servlet-api.jar file which is present in the lib folder under tomcat folder. You can do this using the following steps:

1.Select project properties
2.Select Java Build Path
3.Select Libraries
4.Select External Jars
5.Select servlet-api.jar
6. Apply & Ok.

The issue should be resolved after these steps.

update package.json version automatically

If you are using yarn you can use

yarn version --patch

This will increment package.json version by patch (0.0.x), commit, and tag it with format v0.0.0

Likewise you can bump minor or major version by using --minor or --major

When pushing to git ensure you also push the tags with --follow-tags

git push --follow-tags

You can also create a script for it

    "release-it": "yarn version --patch && git push --follow-tags"

Simply run it by typing yarn release-it

Setting DataContext in XAML in WPF

First of all you should create property with employee details in the Employee class:

public class Employee
{
    public Employee()
    {
        EmployeeDetails = new EmployeeDetails();
        EmployeeDetails.EmpID = 123;
        EmployeeDetails.EmpName = "ABC";
    }

    public EmployeeDetails EmployeeDetails { get; set; }
}

If you don't do that, you will create instance of object in Employee constructor and you lose reference to it.

In the XAML you should create instance of Employee class, and after that you can assign it to DataContext.

Your XAML should look like this:

<Window x:Class="SampleApplication.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    xmlns:local="clr-namespace:SampleApplication"
   >
    <Window.Resources>
        <local:Employee x:Key="Employee" />
    </Window.Resources>
    <Grid DataContext="{StaticResource Employee}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="200" />
        </Grid.ColumnDefinitions>

        <Label Grid.Row="0" Grid.Column="0" Content="ID:"/>
        <Label Grid.Row="1" Grid.Column="0" Content="Name:"/>
        <TextBox Grid.Column="1" Grid.Row="0" Margin="3" Text="{Binding EmployeeDetails.EmpID}" />
        <TextBox Grid.Column="1" Grid.Row="1" Margin="3" Text="{Binding EmployeeDetails.EmpName}" />
    </Grid>
</Window>

Now, after you created property with employee details you should binding by using this property:

Text="{Binding EmployeeDetails.EmpID}"

Failed to resolve: com.google.android.gms:play-services in IntelliJ Idea with gradle

I got this error too but for a different reason. It turns out I had made a typo when I tried to specify the version number as a variable:

dependencies {
    // ...
    implementation "com.google.android.gms:play-services-location:{$playServices}"
    // ...
}

I had defined the variable playServices in gradle.properties in my project's root directory:

playServices=15.0.1

The typo was {$playServices} which should have said ${playServices} like this:

dependencies {
    // ...
    implementation "com.google.android.gms:play-services-location:${playServices}"
    // ...
}

That fixed the problem for me.

How to combine two byte arrays

String temp = passwordSalt;
byte[] byteSalt = temp.getBytes();
int start = 32;
for (int i = 0; i < byteData.length; i ++)
{
    byteData[start + i] = byteSalt[i];
}

The problem with your code here is that the variable i that is being used to index the arrays is going past both the byteSalt array and the byteData array. So, Make sure that byteData is dimensioned to be at least the maximum length of the passwordSalt string plus 32. What will correct it is replacing the following line:

for (int i = 0; i < byteData.length; i ++)

with:

for (int i = 0; i < byteSalt.length; i ++)

What is the best open-source java charting library? (other than jfreechart)

Good question, I was just looking for alternatives to JFreeChart myself the other day. JFreeChart is excellent and very comprehensive, I've used it on several projects. My recent problem was that it meant adding 1.6mb of libraries to a 50kb applet, so I was looking for something smaller.

The JFreeChart FAQ itself lists alternatives. Compared to JFreeChart, most of them are pretty basic, and some pretty ugly. The most promising seem to be the Java Chart Construction Kit and OpenChart2.

I also found EasyCharts, which is a commercial product but seemingly free to use in some circumstances.

In the end, I went back to the tried and trusted JFreeChart and used Proguard to butcher it into a more manageable size.

I suggest that you take another look at JFreeChart. The user guide is only available to buy, but the demo shows what is possible and it's pretty easy to work out how from the API documentation. Basically you start with the ChartFactory static methods and plug the resultant JFreeChart object into a ChartPanel to display it. If you get stuck, I'm sure you'll get some quick answers to your problems on StackOverflow.

What is wrong with this code that uses the mysql extension to fetch data from a database in PHP?

Try this

<?php
// 1. Enter Database details
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$dbname = 'database name';

// 2. Create a database connection
$connection = mysql_connect($dbhost,$dbuser,$dbpass);
if (!$connection) {
    die("Database connection failed: " . mysql_error());
}

// 3. Select a database to use 
$db_select = mysql_select_db($dbname,$connection);
if (!$db_select) {
    die("Database selection failed: " . mysql_error());
}

$query = mysql_query("SELECT * FROM users WHERE name = 'Admin' ");

while ($rows = mysql_fetch_array($query)) { 
   $name = $rows['Name'];
   $address = $rows['Address'];
   $email = $rows['Email'];
   $subject = $rows['Subject'];
   $comment = $rows['Comment']

   echo "$name<br>$address<br>$email<br>$subject<br>$comment<br><br>";      
} 

?>

Not tested!! *UPDATED!!

getResourceAsStream() is always returning null

To my knowledge the file has to be right in the folder where the 'this' class resides, i.e. not in WEB-INF/classes but nested even deeper (unless you write in a default package):

net/domain/pkg1/MyClass.java  
net/domain/pkg1/abc.txt

Putting the file in to your java sources should work, compiler copies that file together with class files.

What is the function of FormulaR1C1?

I find the most valuable feature of .FormulaR1C1 is sheer speed. Versus eg a couple of very large loops filling some data into a sheet, If you can convert what you are doing into a .FormulaR1C1 form. Then a single operation eg myrange.FormulaR1C1 = "my particular formuala" is blindingly fast (can be a thousand times faster). No looping and counting - just fill the range at high speed.

LIMIT 10..20 in SQL Server

For SQL Server 2012 + you can use.

SELECT  *
FROM     sys.databases
ORDER BY name 
OFFSET  5 ROWS 
FETCH NEXT 5 ROWS ONLY 

Putting HTML inside Html.ActionLink(), plus No Link Text?

I thought this might be useful when using bootstrap and some glypicons:

<a class="btn btn-primary" 
    href="<%: Url.Action("Download File", "Download", 
    new { id = msg.Id, distributorId = msg.DistributorId }) %>">
    Download
    <span class="glyphicon glyphicon-paperclip"></span>
</a>

This will show an A tag, with a link to a controller, with a nice paperclip icon on it to represent a download link, and the html output is kept clean

How to add more than one machine to the trusted hosts list using winrm

winrm set winrm/config/client '@{TrustedHosts="machineA,machineB"}'

MySQL Delete all rows from table and reset ID to zero

Do not delete, use truncate:

Truncate table XXX

The table handler does not remember the last used AUTO_INCREMENT value, but starts counting from the beginning. This is true even for MyISAM and InnoDB, which normally do not reuse sequence values.

Source.

jQuery Set Select Index

select 3rd option

$('#selectBox').val($('#selectBox option').eq(2).val());

Example on jsfiddle

Tomcat 7.0.43 "INFO: Error parsing HTTP request header"

If you don't want to upgrade your tomcat, Add this line in your catalina.properties

tomcat.util.http.parser.HttpParser.requestTargetAllow=|{}

It works for me http://www.zhoulujun.cn/zhoulujun/html/java/tomcat/2018_0508_8109.html

javascript multiple OR conditions in IF statement

With an OR (||) operation, if any one of the conditions are true, the result is true.

I think you want an AND (&&) operation here.

Custom thread pool in Java 8 parallel stream

The original solution (setting the ForkJoinPool common parallelism property) no longer works. Looking at the links in the original answer, an update which breaks this has been back ported to Java 8. As mentioned in the linked threads, this solution was not guaranteed to work forever. Based on that, the solution is the forkjoinpool.submit with .get solution discussed in the accepted answer. I think the backport fixes the unreliability of this solution also.

ForkJoinPool fjpool = new ForkJoinPool(10);
System.out.println("stream.parallel");
IntStream range = IntStream.range(0, 20);
fjpool.submit(() -> range.parallel()
        .forEach((int theInt) ->
        {
            try { Thread.sleep(100); } catch (Exception ignore) {}
            System.out.println(Thread.currentThread().getName() + " -- " + theInt);
        })).get();
System.out.println("list.parallelStream");
int [] array = IntStream.range(0, 20).toArray();
List<Integer> list = new ArrayList<>();
for (int theInt: array)
{
    list.add(theInt);
}
fjpool.submit(() -> list.parallelStream()
        .forEach((theInt) ->
        {
            try { Thread.sleep(100); } catch (Exception ignore) {}
            System.out.println(Thread.currentThread().getName() + " -- " + theInt);
        })).get();

How to make PyCharm always show line numbers

PyCharm Version 3.4.1(For all files in the project):

File -> Preferences -> Editor (IDE Settings) -> Appearance -> mark 'Show line numbers'

PyCharm Version 3.4.1(only for existing file in the project):

View -> Active Editor -> Show Line Numbers

image

wkhtmltopdf: cannot connect to X server

Update to latest wkhtmltopdf version from SourceForge (0.12 as of this writing). It does not need an X Server to run.

Example for Ubuntu 14.04:

$ cd /tmp/                                                                                                                                                                                                       
$ wget -q http://downloads.sourceforge.net/project/wkhtmltopdf/0.12.2.1/wkhtmltox-0.12.2.1_linux-trusty-amd64.deb
$ dpkg -x wkhtmltox-0.12.2.1_linux-trusty-amd64.deb foo

$ echo '<p>hi</p>' | ./foo/usr/local/bin/wkhtmltopdf - /tmp/hi.pdf
Loading pages (1/6)
Counting pages (2/6)                                               
Resolving links (4/6)                                                       
Loading headers and footers (5/6)                                           
Printing pages (6/6)
Done                                                                      

$ head -n3 /tmp/hi.pdf 
%PDF-1.4
1 0 obj
<<

Expanding tuples into arguments

Note that you can also expand part of argument list:

myfun(1, *("foo", "bar"))

Do AJAX requests retain PHP Session info?

It is very important that AJAX requests retain session. The easiest example is when you try to do an AJAX request for the admin panel, let's say. Of course that you will protect the page that you make the request to, not to accessible by others who don't have the session you get after administrator login. Makes sense?

What is the command to exit a Console application in C#?

Console applications will exit when the main function has finished running. A "return" will achieve this.

    static void Main(string[] args)
    {
        while (true)
        {
            Console.WriteLine("I'm running!");
            return; //This will exit the console application's running thread
        }
    }

If you're returning an error code you can do it this way, which is accessible from functions outside of the initial thread:

    System.Environment.Exit(-1);

'Java' is not recognized as an internal or external command

I had the same problem. Just Install the exact bit of java as of your computer. If your PC is 64 bit then install 64 bit java. If it is 32 bit then vice versa :)

How do I rename a MySQL schema?

If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE

Edit: On the model overview it's under Physical Schemata

Screenshot:

enter image description here