Programs & Examples On #Visual inheritance

A mechanism of Windows Forms that lets forms inherit controls and appearance.

How do I print a list of "Build Settings" in Xcode project?

Apple's "Build Setting Reference" documentation for what's officially documented (or as rjstelling's answer shows, use env in a build script to see what Xcode actually passes you.

In case the above link changes, Google search for: "build setting reference" site:developer.apple.com

Serializing to JSON in jQuery

Yes, you should JSON.stringify and JSON.parse your Json_PostData before calling $.ajax:

$.ajax({
        url:    post_http_site,  
        type: "POST",         
        data:   JSON.parse(JSON.stringify(Json_PostData)),       
        cache: false,
        error: function (xhr, ajaxOptions, thrownError) {
            alert(" write json item, Ajax error! " + xhr.status + " error =" + thrownError + " xhr.responseText = " + xhr.responseText );    
        },
        success: function (data) {
            alert("write json item, Ajax  OK");

        } 
});

How to convert a Hibernate proxy to a real entity object

Here's a method I'm using.

public static <T> T initializeAndUnproxy(T entity) {
    if (entity == null) {
        throw new 
           NullPointerException("Entity passed for initialization is null");
    }

    Hibernate.initialize(entity);
    if (entity instanceof HibernateProxy) {
        entity = (T) ((HibernateProxy) entity).getHibernateLazyInitializer()
                .getImplementation();
    }
    return entity;
}

CSS no text wrap

Just use:

overflow: hidden;
white-space: nowrap;

In your item's divs

What is "406-Not Acceptable Response" in HTTP?

"Sometimes" this can mean that the server had an internal error, and wanted to respond with an error message (ex: 500 with JSON payload) but since the request headers didn't say it accepted JSON, it returns a 406 instead. Go figure. (in this case: spring boot webapp).

In which case, your operation did fail. But the failure message was obscured by another.

Perl - If string contains text?

if ($string =~ m/something/) {
   # Do work
}

Where something is a regular expression.

Laravel Escaping All HTML in Blade Template

use this tag {!! description text !!}

How to parse JSON data with jQuery / JavaScript?

Try following code, it works in my project:

//start ajax request
$.ajax({
    url: "data.json",
    //force to handle it as text
    dataType: "text",
    success: function(data) {

        //data downloaded so we call parseJSON function 
        //and pass downloaded data
        var json = $.parseJSON(data);
        //now json variable contains data in json format
        //let's display a few items
        for (var i=0;i<json.length;++i)
        {
            $('#results').append('<div class="name">'+json[i].name+'</>');
        }
    }
});

How do I specify the JDK for a GlassFish domain?

ERROR MESSAGE :

..... PWC6199: Generated servlet error: -Source 1.5 does not support the diamond operator (please use -source version 7 or higher to enable the diamond operator)

Solution

On MAC : go to

  • /Users/username/GlassFish_Server/glassfish/domains/domain2/config
  • open the default_web.xml file
  • find the jsp
  • add

    enter image description here

How does "304 Not Modified" work exactly?

When the browser puts something in its cache, it also stores the Last-Modified or ETag header from the server.

The browser then sends a request with the If-Modified-Since or If-None-Match header, telling the server to send a 304 if the content still has that date or ETag.

The server needs some way of calculating a date-modified or ETag for each version of each resource; this typically comes from the filesystem or a separate database column.

How do you read CSS rule values with JavaScript?

I added return of object where attributes are parsed out style/values:

var getClassStyle = function(className){
    var x, sheets,classes;
    for( sheets=document.styleSheets.length-1; sheets>=0; sheets-- ){
        classes = document.styleSheets[sheets].rules || document.styleSheets[sheets].cssRules;
        for(x=0;x<classes.length;x++) {
            if(classes[x].selectorText===className){
                classStyleTxt = (classes[x].cssText ? classes[x].cssText : classes[x].style.cssText).match(/\{\s*([^{}]+)\s*\}/)[1];
                var classStyles = {};
                var styleSets = classStyleTxt.match(/([^;:]+:\s*[^;:]+\s*)/g);
                for(y=0;y<styleSets.length;y++){
                    var style = styleSets[y].match(/\s*([^:;]+):\s*([^;:]+)/);
                    if(style.length > 2)
                        classStyles[style[1]]=style[2];
                }
                return classStyles;
            }
        }
    }
    return false;
};

How can I capture packets in Android?

Option 1 - Android PCAP

Limitation

Android PCAP should work so long as:

Your device runs Android 4.0 or higher (or, in theory, the few devices which run Android 3.2). Earlier versions of Android do not have a USB Host API

Option 2 - TcpDump

Limitation

Phone should be rooted

Option 3 - bitshark (I would prefer this)

Limitation

Phone should be rooted

Reason - the generated PCAP files can be analyzed in WireShark which helps us in doing the analysis.

Other Options without rooting your phone

  1. tPacketCapture

https://play.google.com/store/apps/details?id=jp.co.taosoftware.android.packetcapture&hl=en

Advantages

Using tPacketCapture is very easy, captured packet save into a PCAP file that can be easily analyzed by using a network protocol analyzer application such as Wireshark.

  1. You can route your android mobile traffic to PC and capture the traffic in the desktop using any network sniffing tool.

http://lifehacker.com/5369381/turn-your-windows-7-pc-into-a-wireless-hotspot

How can I make a .NET Windows Forms application that only runs in the System Tray?

As far as I'm aware you have to still write the application using a form, but have no controls on the form and never set it visible. Use the NotifyIcon (an MSDN sample of which can be found here) to write your application.

How to get the Facebook user id using the access token

With the newest API, here's the code I used for it

/*params*/
NSDictionary *params = @{
                         @"access_token": [[FBSDKAccessToken currentAccessToken] tokenString],
                         @"fields": @"id"
                         };
/* make the API call */
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
                              initWithGraphPath:@"me"
                              parameters:params
                              HTTPMethod:@"GET"];

[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
                                      id result,
                                      NSError *error) {
    NSDictionary *res = result;
    //res is a dict that has the key
    NSLog([res objectForKey:@"id"]);

How to cherry-pick multiple commits

Actually, the simplest way to do it could be to:

  1. record the merge-base between the two branches: MERGE_BASE=$(git merge-base branch-a branch-b)
  2. fast-forward or rebase the older branch onto the newer branch
  3. rebase the resulting branch onto itself, starting at the merge base from step 1, and manually remove commits that are not desired:

    git rebase ${SAVED_MERGE_BASE} -i
    

    Alternatively, if there are only a few new commits, skip step 1, and simply use

    git rebase HEAD^^^^^^^ -i
    

    in the first step, using enough ^ to move past the merge-base.

You will see something like this in the interactive rebase:

pick 3139276 commit a
pick c1b421d commit b
pick 7204ee5 commit c
pick 6ae9419 commit d
pick 0152077 commit e
pick 2656623 commit f

Then remove lines b (and any others you want)

SQL/mysql - Select distinct/UNIQUE but return all columns?

SELECT *
FROM tblname
GROUP BY duplicate_values
ORDER BY ex.VISITED_ON DESC
LIMIT 0 , 30

in ORDER BY i have just put example here, you can also add ID field in this

NLS_NUMERIC_CHARACTERS setting for decimal

Jaanna, the session parameters in Oracle SQL Developer are dependent on your client computer, while the NLS parameters on PL/SQL is from server.

For example the NLS_NUMERIC_CHARACTERS on client computer can be ',.' while it's '.,' on server.

So when you run script from PL/SQL and Oracle SQL Developer the decimal separator can be completely different for the same script, unless you alter session with your expected NLS_NUMERIC_CHARACTERS in the script.

One way to easily test your session parameter is to do:

select to_number(5/2) from dual;

JVM heap parameters

The JVM will start with memory useage at the initial heap level. If the maxheap is higher, it will grow to the maxheap size as memory requirements exceed it's current memory.

So,

  • -Xms512m -Xmx512m

JVM starts with 512 M, never resizes.

  • -Xms64m -Xmx512m

JVM starts with 64M, grows (up to max ceiling of 512) if mem. requirements exceed 64.

Temporarily disable all foreign key constraints

Truncating the table wont be possible even if you disable the foreign keys.so you can use delete command to remove all the records from the table,but be aware if you are using delete command for a table which consists of millions of records then your package will be slow and your transaction log size will increase and it may fill up your valuable disk space.

If you drop the constraints it may happen that you will fill up your table with unclean data and when you try to recreate the constraints it may not allow you to as it will give errors. so make sure that if you drop the constraints,you are loading data which are correctly related to each other and satisfy the constraint relations which you are going to recreate.

so please carefully think the pros and cons of each method and use it according to your requirements

Vim multiline editing like in sublimetext?

if you use the "global" command, you can repeat what you can do on one online an any number of lines.

:g/<search>/.<your ex command>

example:

:g/foo/.s/bar/baz/g

The above command finds all lines that have foo, and replace all occurrences of bar on that line with baz.

:g/.*/

will do on every line

Compiling simple Hello World program on OS X via command line

Try

g++ hw.cpp
./a.out

g++ is the C++ compiler frontend to GCC.
gcc is the C compiler frontend to GCC.

Yes, Xcode is definitely an option. It is a GUI IDE that is built on-top of GCC.

Though I prefer a slightly more verbose approach:

#include <iostream>

int main()
{
    std::cout << "Hello world!" << std::endl;
}

Getting All Variables In Scope

As everyone noticed: you can't. But you can create a obj and assign every var you declare to that obj. That way you can easily check out your vars:

var v = {}; //put everything here

var f = function(a, b){//do something
}; v.f = f; //make's easy to debug
var a = [1,2,3];
v.a = a;
var x = 'x';
v.x = x;  //so on...

console.log(v); //it's all there

CMD (command prompt) can't go to the desktop

You need to use the change directory command 'cd' to change directory

cd C:\Users\MyName\Desktop

you can use cd \d to change the drive as well.

link for additional resources http://ss64.com/nt/cd.html

System.BadImageFormatException: Could not load file or assembly

Try to configure the setting of your projects, it is usually due to x86/x64 architecture problems:

Go and set your choice as shown:

Check if string is upper, lower, or mixed case in Python

There are a number of "is methods" on strings. islower() and isupper() should meet your needs:

>>> 'hello'.islower()
True

>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

Here's an example of how to use those methods to classify a list of strings:

>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']

Get Character value from KeyCode in JavaScript... then trim

I recently wrote a module called keysight that translates keypress, keydown, and keyup events into characters and keys respectively.

Example:

 element.addEventListener("keydown", function(event) {
    var character = keysight(event).char
 })

Barcode scanner for mobile phone for Website in form

There's a JS QrCode scanner, that works on mobile sites with a camera:

https://github.com/LazarSoft/jsqrcode

I have worked with it for one of my project and it works pretty good !

How to delete the contents of a folder?

This should do the trick just using the OS module to list and then remove!

import os
DIR = os.list('Folder')
for i in range(len(DIR)):
    os.remove('Folder'+chr(92)+i)

Worked for me, any problems let me know!

What are the differences between LinearLayout, RelativeLayout, and AbsoluteLayout?

LinearLayout - In LinearLayout, views are organized either in vertical or horizontal orientation.

RelativeLayout - RelativeLayout is way more complex than LinearLayout, hence provides much more functionalities. Views are placed, as the name suggests, relative to each other.

FrameLayout - It behaves as a single object and its child views are overlapped over each other. FrameLayout takes the size of as per the biggest child element.

Coordinator Layout - This is the most powerful ViewGroup introduced in Android support library. It behaves as FrameLayout and has a lot of functionalities to coordinate amongst its child views, for example, floating button and snackbar, Toolbar with scrollable view.

How to reposition Chrome Developer Tools

Keyboard shortcut to toggle the docking position (side/bottom)

CTRL+SHIFT+D

And there are many shortcuts you can see them by going to

Settings » Shortcuts, as displayed here:
Settings screenshot

Alternatively, use CTRL + ? to go to the settings, from there one can reach the "Shortcuts" sub-item on the left or use the Official reference.

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

This was resolved. It turns out our IT Staff was correct. Both TLS 1.1 and TLS 1.2 were installed on the server. However, the issue was that our sites are running as ASP.NET 4.0 and you have to have ASP.NET 4.5 to run TLS 1.1 or TLS 1.2. So, to resolve the issue, our IT Staff had to re-enable TLS 1.0 to allow a connection with PayTrace.

So in short, the error message, "the client and server cannot communicate, because they do not possess a common algorithm", was caused because there was no SSL Protocol available on the server to communicate with PayTrace's servers.

UPDATE: Please do not enable TLS 1.0 on your servers, this was a temporary fix and is not longer applicable since there are now better work-arounds that ensure strong security practices. Please see accepted answer for a solution. FYI, I'm going to keep this answer on the site as it provides information on what the problem was, please do not down-vote.

How to execute a stored procedure inside a select query

Functions are easy to call inside a select loop, but they don't let you run inserts, updates, deletes, etc. They are only useful for query operations. You need a stored procedure to manipulate the data.

So, the real answer to this question is that you must iterate through the results of a select statement via a "cursor" and call the procedure from within that loop. Here's an example:

DECLARE @myId int;
DECLARE @myName nvarchar(60);
DECLARE myCursor CURSOR FORWARD_ONLY FOR
    SELECT Id, Name FROM SomeTable;
OPEN myCursor;
FETCH NEXT FROM myCursor INTO @myId, @myName;
WHILE @@FETCH_STATUS = 0 BEGIN
    EXECUTE dbo.myCustomProcedure @myId, @myName;
    FETCH NEXT FROM myCursor INTO @myId, @myName;
END;
CLOSE myCursor;
DEALLOCATE myCursor;

Note that @@FETCH_STATUS is a standard variable which gets updated for you. The rest of the object names here are custom.

How to get the Power of some Integer in Swift language?

func calc (base:Int, number:Int) -> Int {
    var answer : Int = base
    for _ in 2...number {answer *= base } 
    return answer
}

Example:

calc (2,2)

Markdown and including multiple files

I would just mention that you can use the cat command to concatenate the input files prior to piping them to markdown_py which has the same effect as what pandoc does with multiple input files coming in.

cat *.md | markdown_py > youroutputname.html

works pretty much the same as the pandoc example above for the Python version of Markdown on my Mac.

How do I shutdown, restart, or log off Windows via a bat file?

I'm late to the party, but did not see this answer yet. When you don't want to use a batch file or type the command. You can just set focus to the desktop and then use Alt + F4.

Windows will ask you what you want to do, select shutdown or restart.

For screenshots and even a video, see: https://tinkertry.com/how-to-shutdown-or-restart-windows-over-rdp

How to check if a value exists in an object using JavaScript

if( myObj.hasOwnProperty('key') && myObj['key'] === value ){
    ...
}

How do I print the content of a .txt file in Python?

It's pretty simple

#Opening file
f= open('sample.txt')
#reading everything in file
r=f.read()
#reading at particular index
r=f.read(1)
#print
print(r)

Presenting snapshot from my visual studio IDE.

enter image description here

Postgresql 9.2 pg_dump version mismatch

The answer sounds silly but if you get the above error and wanna run the pg_dump for earlier version go to bin directory of postgres and type

./pg_dump servername > out.sql ./ ignores the root and looks for pg_dump in current directory

Node update a specific package

Use npm outdated to see Current and Latest version of all packages.


Then npm i packageName@versionNumber to install specific version : example npm i [email protected].

Or npm i packageName@latest to install latest version : example npm i browser-sync@latest.

Difference between text and varchar (character varying)

UPDATING BENCHMARKS FOR 2016 (pg9.5+)

And using "pure SQL" benchmarks (without any external script)

  1. use any string_generator with UTF8

  2. main benchmarks:

    2.1. INSERT

    2.2. SELECT comparing and counting


CREATE FUNCTION string_generator(int DEFAULT 20,int DEFAULT 10) RETURNS text AS $f$
  SELECT array_to_string( array_agg(
    substring(md5(random()::text),1,$1)||chr( 9824 + (random()*10)::int )
  ), ' ' ) as s
  FROM generate_series(1, $2) i(x);
$f$ LANGUAGE SQL IMMUTABLE;

Prepare specific test (examples)

DROP TABLE IF EXISTS test;
-- CREATE TABLE test ( f varchar(500));
-- CREATE TABLE test ( f text); 
CREATE TABLE test ( f text  CHECK(char_length(f)<=500) );

Perform a basic test:

INSERT INTO test  
   SELECT string_generator(20+(random()*(i%11))::int)
   FROM generate_series(1, 99000) t(i);

And other tests,

CREATE INDEX q on test (f);

SELECT count(*) FROM (
  SELECT substring(f,1,1) || f FROM test WHERE f<'a0' ORDER BY 1 LIMIT 80000
) t;

... And use EXPLAIN ANALYZE.

UPDATED AGAIN 2018 (pg10)

little edit to add 2018's results and reinforce recommendations.


Results in 2016 and 2018

My results, after average, in many machines and many tests: all the same
(statistically less tham standard deviation).

Recommendation

  • Use text datatype,
    avoid old varchar(x) because sometimes it is not a standard, e.g. in CREATE FUNCTION clauses varchar(x)?varchar(y).

  • express limits (with same varchar performance!) by with CHECK clause in the CREATE TABLE
    e.g. CHECK(char_length(x)<=10).
    With a negligible loss of performance in INSERT/UPDATE you can also to control ranges and string structure
    e.g. CHECK(char_length(x)>5 AND char_length(x)<=20 AND x LIKE 'Hello%')

How to dynamically build a JSON object with Python?

  myjson={}
  myjson["Country"]= {"KR": { "id": "220", "name": "South Korea"}}
  myjson["Creative"]= {
                    "1067405": {
                        "id": "1067405",
                        "url": "https://cdn.gowadogo.com/559d1ba1-8d50-4c7f-b3f5-d80f918006e0.jpg"
                    },
                    "1067406": {
                        "id": "1067406",
                        "url": "https://cdn.gowadogo.com/3799a70d-339c-4ecb-bc1f-a959dde675b8.jpg"
                    },
                    "1067407": {
                        "id": "1067407",
                        "url": "https://cdn.gowadogo.com/180af6a5-251d-4aa9-9cd9-51b2fc77d0c6.jpg"
                    }
                }
   myjson["Offer"]= {
                    "advanced_targeting_enabled": "f",
                    "category_name": "E-commerce/ Shopping",
                    "click_lifespan": "168",
                    "conversion_cap": "50",
                    "currency": "USD",
                    "default_payout": "1.5"
                }

   json_data = json.dumps(myjson)

   #reverse back into a json

   paths=[]
   def walk_the_tree(inputDict,suffix=None):
       for key, value in inputDict.items():
            if isinstance(value, dict):
                if suffix==None:
                    suffix=key
                else:
                    suffix+=":"+key

                walk_the_tree(value,suffix)
            else:
                paths.append(suffix+":"+key+":"+value)
 walk_the_tree(myjson)
 print(paths)  

 #split and build your nested dictionary
 json_specs = {}
 for path in paths:
     parts=path.split(':')
     value=(parts[-1])
     d=json_specs
     for p in parts[:-1]:
         if p==parts[-2]:
             d = d.setdefault(p,value)
         else:
             d = d.setdefault(p,{})
    
 print(json_specs)        

 Paths:
 ['Country:KR:id:220', 'Country:KR:name:South Korea', 'Country:Creative:1067405:id:1067405', 'Country:Creative:1067405:url:https://cdn.gowadogo.com/559d1ba1-8d50-4c7f-b3f5-d80f918006e0.jpg', 'Country:Creative:1067405:1067406:id:1067406', 'Country:Creative:1067405:1067406:url:https://cdn.gowadogo.com/3799a70d-339c-4ecb-bc1f-a959dde675b8.jpg', 'Country:Creative:1067405:1067406:1067407:id:1067407', 'Country:Creative:1067405:1067406:1067407:url:https://cdn.gowadogo.com/180af6a5-251d-4aa9-9cd9-51b2fc77d0c6.jpg', 'Country:Creative:Offer:advanced_targeting_enabled:f', 'Country:Creative:Offer:category_name:E-commerce/ Shopping', 'Country:Creative:Offer:click_lifespan:168', 'Country:Creative:Offer:conversion_cap:50', 'Country:Creative:Offer:currency:USD', 'Country:Creative:Offer:default_payout:1.5']

How do I copy folder with files to another folder in Unix/Linux?

You are looking for the cp command. You need to change directories so that you are outside of the directory you are trying to copy.

If the directory you're copying is called dir1 and you want to copy it to your /home/Pictures folder:

cp -r dir1/ ~/Pictures/

Linux is case-sensitive and also needs the / after each directory to know that it isn't a file. ~ is a special character in the terminal that automatically evaluates to the current user's home directory. If you need to know what directory you are in, use the command pwd.

When you don't know how to use a Linux command, there is a manual page that you can refer to by typing:

man [insert command here]

at a terminal prompt.

Also, to auto complete long file paths when typing in the terminal, you can hit Tab after you've started typing the path and you will either be presented with choices, or it will insert the remaining part of the path.

Sql Server trigger insert values from new row into another table

try this for sql server

CREATE TRIGGER yourNewTrigger ON yourSourcetable
FOR INSERT
AS

INSERT INTO yourDestinationTable
        (col1, col2    , col3, user_id, user_name)
    SELECT
        'a'  , default , null, user_id, user_name
        FROM inserted

go

Scanner vs. BufferedReader

Difference between BufferedReader and Scanner are following:

  1. BufferedReader is synchronized but Scanner is not synchronized.
  2. BufferedReader is thread safe but Scanner is not thread safe.
  3. BufferedReader has larger buffer memory but Scanner has smaller buffer memory.
  4. BufferedReader is faster but Scanner is slower in execution.
  5. Code to read a line from console:

    BufferedReader:

     InputStreamReader isr=new InputStreamReader(System.in);
     BufferedReader br= new BufferedReader(isr);
     String st= br.readLine();
    

    Scanner:

    Scanner sc= new Scanner(System.in);
    String st= sc.nextLine();
    

how to pass list as parameter in function

You can pass it as a List<DateTime>

public void somefunction(List<DateTime> dates)
{
}

However, it's better to use the most generic (as in general, base) interface possible, so I would use

public void somefunction(IEnumerable<DateTime> dates)
{
}

or

public void somefunction(ICollection<DateTime> dates)
{
}

You might also want to call .AsReadOnly() before passing the list to the method if you don't want the method to modify the list - add or remove elements.

How to print variables in Perl

How do I print out my $ids and $nIds?
print "$ids\n";
print "$nIds\n";
I tried simply print $ids, but Perl complains.

Complains about what? Uninitialised value? Perhaps your loop was never entered due to an error opening the file. Be sure to check if open returned an error, and make sure you are using use strict; use warnings;.

my ($ids, $nIds) is a list, right? With two elements?

It's a (very special) function call. $ids,$nIds is a list with two elements.

Identify duplicates in a List

Compact generified version of the top answer, also added empty check and preallocated Set size:

public static final <T> Set<T> findDuplicates(final List<T> listWhichMayHaveDuplicates) {
    final Set<T> duplicates = new HashSet<>();
    final int listSize = listWhichMayHaveDuplicates.size();
    if (listSize > 0) {
      final Set<T> tempSet = new HashSet<>(listSize);
      for (final T element : listWhichMayHaveDuplicates) {
        if (!tempSet.add(element)) {
          duplicates.add(element);
        }
      }
    }
    return duplicates;
  }

Tomcat Server Error - Port 8080 already in use

In case of MAC users, go to Terminal and do the following

lsof -i :8080 //returns the PID (process id) that runs on port 8080
kill 1234 //kill the process using PID (used dummy PID here)
lsof -i :8443
kill 4321

8080 is HTTP port and 8443 is HTTPS port, by default.

How can I delete using INNER JOIN with SQL Server?

You don't specify the tables for Company and Date, and you might want to fix that.

Standard SQL using MERGE:

MERGE WorkRecord2 T
   USING Employee S
      ON T.EmployeeRun = S.EmployeeNo
         AND Company = '1'
         AND Date = '2013-05-06'
WHEN MATCHED THEN DELETE;

The answer from Devart is also standard SQL, though incomplete. It should look more like this:

DELETE
  FROM WorkRecord2
  WHERE EXISTS ( SELECT *
                   FROM Employee S
                  WHERE S.EmployeeNo = WorkRecord2.EmployeeRun
                        AND Company = '1'
                        AND Date = '2013-05-06' );

The important thing to note about the above is it is clear the delete is targeting a single table, as enforced in the second example by requiring a scalar subquery.

For me, the various proprietary syntax answers are harder to read and understand. I guess the mindset for is best described in the answer by frans eilering, i.e. the person writing the code doesn't necessarily care about the person who will read and maintain the code.

How to search a specific value in all tables (PostgreSQL)?

There is a way to achieve this without creating a function or using an external tool. By using Postgres' query_to_xml() function that can dynamically run a query inside another query, it's possible to search a text across many tables. This is based on my answer to retrieve the rowcount for all tables:

To search for the string foo across all tables in a schema, the following can be used:

with found_rows as (
  select format('%I.%I', table_schema, table_name) as table_name,
         query_to_xml(format('select to_jsonb(t) as table_row 
                              from %I.%I as t 
                              where t::text like ''%%foo%%'' ', table_schema, table_name), 
                      true, false, '') as table_rows
  from information_schema.tables 
  where table_schema = 'public'
)
select table_name, x.table_row
from found_rows f
  left join xmltable('//table/row' 
                     passing table_rows
                       columns
                         table_row text path 'table_row') as x on true

Note that the use of xmltable requires Postgres 10 or newer. For older Postgres version, this can be also done using xpath().

with found_rows as (
  select format('%I.%I', table_schema, table_name) as table_name,
         query_to_xml(format('select to_jsonb(t) as table_row 
                              from %I.%I as t 
                              where t::text like ''%%foo%%'' ', table_schema, table_name), 
                      true, false, '') as table_rows
  from information_schema.tables 
  where table_schema = 'public'
)
select table_name, x.table_row
from found_rows f
   cross join unnest(xpath('/table/row/table_row/text()', table_rows)) as r(data)

The common table expression (WITH ...) is only used for convenience. It loops through all tables in the public schema. For each table the following query is run through the query_to_xml() function:

select to_jsonb(t)
from some_table t
where t::text like '%foo%';

The where clause is used to make sure the expensive generation of XML content is only done for rows that contain the search string. This might return something like this:

<table xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<row>
  <table_row>{"id": 42, "some_column": "foobar"}</table_row>
</row>
</table>

The conversion of the complete row to jsonb is done, so that in the result one could see which value belongs to which column.

The above might return something like this:

table_name   |   table_row
-------------+----------------------------------------
public.foo   |  {"id": 1, "some_column": "foobar"}
public.bar   |  {"id": 42, "another_column": "barfoo"}

Online example for Postgres 10+

Online example for older Postgres versions

PHP Warning: PHP Startup: ????????: Unable to initialize module

Erase the module that can't be initialized and reinstall it.

Adding and using header (HTTP) in nginx

To add a header just add the following code to the location block where you want to add the header:

location some-location {
  add_header X-my-header my-header-content;      
}

Obviously, replace the x-my-header and my-header-content with what you want to add. And that's all there is to it.

Tools: replace not replacing in Android manifest

I also went through this problem and changed that:

<application  android:debuggable="true" android:icon="@drawable/app_icon" android:label="@string/app_name" android:supportsRtl="true" android:allowBackup="false" android:fullBackupOnly="false" android:theme="@style/UnityThemeSelector">

to

 <application tools:replace="android:allowBackup" android:debuggable="true" android:icon="@drawable/app_icon" android:label="@string/app_name" android:supportsRtl="true" android:allowBackup="false" android:fullBackupOnly="false" android:theme="@style/UnityThemeSelector">

Class 'DOMDocument' not found

For PHP 7.4 Install the DOM extension.

Debian / Ubuntu:

sudo apt-get update
sudo apt-get install php7.4-xml
sudo service apache2 restart

Centos / Fedora / Red Hat:

yum update
yum install php74w-xml
systemctl restart httpd

For previous PHP releases, replace with your version.

Pipenv: Command Not Found

This is fixed for me to:

sudo -H pip install -U pipenv

How do I get a plist as a Dictionary in Swift?

Swift 2.0 : Accessing Info.Plist

I have a Dictionary named CoachMarksDictionary with a boolean value in Info.Plist . I want to access the bool value and make it true.

let path = NSBundle.mainBundle().pathForResource("Info", ofType: "plist")!
  let dict = NSDictionary(contentsOfFile: path) as! [String: AnyObject]

  if let CoachMarksDict = dict["CoachMarksDictionary"] {
       print("Info.plist : \(CoachMarksDict)")

   var dashC = CoachMarksDict["DashBoardCompleted"] as! Bool
    print("DashBoardCompleted state :\(dashC) ")
  }

Writing To Plist:

From a Custom Plist:- (Make from File-New-File-Resource-PropertyList. Added three strings named : DashBoard_New, DashBoard_Draft, DashBoard_Completed)

func writeToCoachMarksPlist(status:String?,keyName:String?)
 {
  let path1 = NSBundle.mainBundle().pathForResource("CoachMarks", ofType: "plist")
  let coachMarksDICT = NSMutableDictionary(contentsOfFile: path1!)! as NSMutableDictionary
  var coachMarksMine = coachMarksDICT.objectForKey(keyName!)

  coachMarksMine  = status
  coachMarksDICT.setValue(status, forKey: keyName!)
  coachMarksDICT.writeToFile(path1!, atomically: true)
 }

The method can be called as

self.writeToCoachMarksPlist(" true - means user has checked the marks",keyName: "the key in the CoachMarks dictionary").

Set value for particular cell in pandas DataFrame using index

If one wants to change the cell in the position (0,0) of the df to a string such as '"236"76"', the following options will do the work:

df[0][0] = '"236"76"'
# %timeit df[0][0] = '"236"76"'
# 938 µs ± 83.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Or using pandas.DataFrame.at

df.at[0, 0] = '"236"76"'
#  %timeit df.at[0, 0] = '"236"76"' 
#15 µs ± 2.09 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Or using pandas.DataFrame.iat

df.iat[0, 0] = '"236"76"'
#  %timeit df.iat[0, 0] = '"236"76"'
# 41.1 µs ± 3.09 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Or using pandas.DataFrame.loc

df.loc[0, 0] = '"236"76"'
#  %timeit df.loc[0, 0] = '"236"76"'
# 5.21 ms ± 401 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Or using pandas.DataFrame.iloc

df.iloc[0, 0] = '"236"76"'
#  %timeit df.iloc[0, 0] = '"236"76"'
# 5.12 ms ± 300 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

If time is of relevance, using pandas.DataFrame.at is the fastest approach.

How to store the hostname in a variable in a .bat file?

 set host=%COMPUTERNAME%
 echo %host%

This one enough. no need of extra loops of big coding.

lists and arrays in VBA

You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.

Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String

'Assign data to first item in array
compArray(1) = "asdf"

'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"

'Prints "ErrorState"
Debug.Print Computers("Computer Name")

Collections cannot be sorted so if you need to sort data you will probably want to use an array.

Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx

Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx

Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!

Edit:

Sub ArrayExample()
    Dim subject As String
    Dim TestArray() As String
    Dim counter As Long

    subject = "Example"
    counter = Len(subject)

    ReDim TestArray(1 To counter) As String

    For counter = 1 To Len(subject)
        TestArray(counter) = Right(Left(subject, counter), 1)
    Next
End Sub

"getaddrinfo failed", what does that mean?

The problem, in my case, was that some install at some point defined an environment variable http_proxy on my machine when I had no proxy.

Removing the http_proxy environment variable fixed the problem.

Sorting a Python list by two fields

python 3 https://docs.python.org/3.5/howto/sorting.html#the-old-way-using-the-cmp-parameter

from functools import cmp_to_key

def custom_compare(x, y):
    # custom comparsion of x[0], x[1] with y[0], y[1]
    return 0

sorted(entries, key=lambda e: (cmp_to_key(custom_compare)(e[0]), e[1]))

How to stretch the background image to fill a div

Add

background-size:100% 100%;

to your css underneath background-image.

You can also specify exact dimensions, i.e.:

background-size: 30px 40px;

Here: JSFiddle

Calculating how many days are between two dates in DB2?

I faced the same problem in Derby IBM DB2 embedded database in a java desktop application, and after a day of searching I finally found how it's done :

SELECT days (table1.datecolomn) - days (current date) FROM table1 WHERE days (table1.datecolomn) - days (current date) > 5

for more information check this site

Can I map a hostname *and* a port with /etc/hosts?

No, that's not possible. The port is not part of the hostname, so it has no meaning in the hosts-file.

Reactjs - Form input validation

I've taken your code and adapted it with library react-form-with-constraints: https://codepen.io/tkrotoff/pen/LLraZp

const {
  FormWithConstraints,
  FieldFeedbacks,
  FieldFeedback
} = ReactFormWithConstraints;

class Form extends React.Component {
  handleChange = e => {
    this.form.validateFields(e.target);
  }

  contactSubmit = e => {
    e.preventDefault();

    this.form.validateFields();

    if (!this.form.isValid()) {
      console.log('form is invalid: do not submit');
    } else {
      console.log('form is valid: submit');
    }
  }

  render() {
    return (
      <FormWithConstraints
        ref={form => this.form = form}
        onSubmit={this.contactSubmit}
        noValidate>

        <div className="col-md-6">
          <input name="name" size="30" placeholder="Name"
                 required onChange={this.handleChange}
                 className="form-control" />
          <FieldFeedbacks for="name">
            <FieldFeedback when="*" />
          </FieldFeedbacks>

          <input type="email" name="email" size="30" placeholder="Email"
                 required onChange={this.handleChange}
                 className="form-control" />
          <FieldFeedbacks for="email">
            <FieldFeedback when="*" />
          </FieldFeedbacks>

          <input name="phone" size="30" placeholder="Phone"
                 required onChange={this.handleChange}
                 className="form-control" />
          <FieldFeedbacks for="phone">
            <FieldFeedback when="*" />
          </FieldFeedbacks>

          <input name="address" size="30" placeholder="Address"
                 required onChange={this.handleChange}
                 className="form-control" />
          <FieldFeedbacks for="address">
            <FieldFeedback when="*" />
          </FieldFeedbacks>
        </div>

        <div className="col-md-6">
          <textarea name="comments" cols="40" rows="20" placeholder="Message"
                    required minLength={5} maxLength={50}
                    onChange={this.handleChange}
                    className="form-control" />
          <FieldFeedbacks for="comments">
            <FieldFeedback when="*" />
          </FieldFeedbacks>
        </div>

        <div className="col-md-12">
          <button className="btn btn-lg btn-primary">Send Message</button>
        </div>
      </FormWithConstraints>
    );
  }
}

Screenshot:

form validation screenshot

This is a quick hack. For a proper demo, check https://github.com/tkrotoff/react-form-with-constraints#examples

Running CMD command in PowerShell

Try this:

& "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\i386\CmRcViewer.exe" PCNAME

To PowerShell a string "..." is just a string and PowerShell evaluates it by echoing it to the screen. To get PowerShell to execute the command whose name is in a string, you use the call operator &.

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

Some JavaScript engines can parse that format directly, which makes the task pretty easy:

_x000D_
_x000D_
function convertDate(inputFormat) {_x000D_
  function pad(s) { return (s < 10) ? '0' + s : s; }_x000D_
  var d = new Date(inputFormat)_x000D_
  return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/')_x000D_
}_x000D_
_x000D_
console.log(convertDate('Mon Nov 19 13:29:40 2012')) // => "19/11/2012"
_x000D_
_x000D_
_x000D_

Firebase: how to generate a unique numeric ID for key?

As explained above, you can use the Firebase default push id.

If you want something numeric you can do something based on the timestamp to avoid collisions

f.e. something based on date,hour,second,ms, and some random int at the end

01612061353136799031

Which translates to:

016-12-06 13:53:13:679 9031

It all depends on the precision you need (social security numbers do the same with some random characters at the end of the date). Like how many transactions will be expected during the day, hour or second. You may want to lower precision to favor ease of typing.

You can also do a transaction that increments the number id, and on success you will have a unique consecutive number for that user. These can be done on the client or server side.

(https://firebase.google.com/docs/database/android/read-and-write)

Is there any native DLL export functions viewer?

you can use Dependency Walker to view the function name. you can see the function's parameters only if it's decorated. read the following from the FAQ:

How do I view the parameter and return types of a function? For most functions, this information is simply not present in the module. The Windows' module file format only provides a single text string to identify each function. There is no structured way to list the number of parameters, the parameter types, or the return type. However, some languages do something called function "decoration" or "mangling", which is the process of encoding information into the text string. For example, a function like int Foo(int, int) encoded with simple decoration might be exported as _Foo@8. The 8 refers to the number of bytes used by the parameters. If C++ decoration is used, the function would be exported as ?Foo@@YGHHH@Z, which can be directly decoded back to the function's original prototype: int Foo(int, int). Dependency Walker supports C++ undecoration by using the Undecorate C++ Functions Command.

Java 8 Distinct by property

Building on @josketres's answer, I created a generic utility method:

You could make this more Java 8-friendly by creating a Collector.

public static <T> Set<T> removeDuplicates(Collection<T> input, Comparator<T> comparer) {
    return input.stream()
            .collect(toCollection(() -> new TreeSet<>(comparer)));
}


@Test
public void removeDuplicatesWithDuplicates() {
    ArrayList<C> input = new ArrayList<>();
    Collections.addAll(input, new C(7), new C(42), new C(42));
    Collection<C> result = removeDuplicates(input, (c1, c2) -> Integer.compare(c1.value, c2.value));
    assertEquals(2, result.size());
    assertTrue(result.stream().anyMatch(c -> c.value == 7));
    assertTrue(result.stream().anyMatch(c -> c.value == 42));
}

@Test
public void removeDuplicatesWithoutDuplicates() {
    ArrayList<C> input = new ArrayList<>();
    Collections.addAll(input, new C(1), new C(2), new C(3));
    Collection<C> result = removeDuplicates(input, (t1, t2) -> Integer.compare(t1.value, t2.value));
    assertEquals(3, result.size());
    assertTrue(result.stream().anyMatch(c -> c.value == 1));
    assertTrue(result.stream().anyMatch(c -> c.value == 2));
    assertTrue(result.stream().anyMatch(c -> c.value == 3));
}

private class C {
    public final int value;

    private C(int value) {
        this.value = value;
    }
}

In Flask, What is request.args and how is it used?

request.args is a MultiDict with the parsed contents of the query string. From the documentation of get method:

get(key, default=None, type=None)

Return the default value if the requested data doesn’t exist. If type is provided and is a callable it should convert the value, return it or raise a ValueError if that is not possible.

Python - 'ascii' codec can't decode byte

If you're using Python < 3, you'll need to tell the interpreter that your string literal is Unicode by prefixing it with a u:

Python 2.7.2 (default, Jan 14 2012, 23:14:09) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> "??".encode("utf8")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
>>> u"??".encode("utf8")
'\xe4\xbd\xa0\xe5\xa5\xbd'

Further reading: Unicode HOWTO.

Using %s in C correctly - very basic level

For both *printf and *scanf, %s expects the corresponding argument to be of type char *, and for scanf, it had better point to a writable buffer (i.e., not a string literal).

char *str_constant = "I point to a string literal";
char str_buf[] = "I am an array of char initialized with a string literal";

printf("string literal = %s\n", "I am a string literal");
printf("str_constant = %s\n", str_constant);
printf("str_buf = %s\n", str_buf);

scanf("%55s", str_buf);

Using %s in scanf without an explcit field width opens the same buffer overflow exploit that gets did; namely, if there are more characters in the input stream than the target buffer is sized to hold, scanf will happily write those extra characters to memory outside the buffer, potentially clobbering something important. Unfortunately, unlike in printf, you can't supply the field with as a run time argument:

printf("%*s\n", field_width, string);

One option is to build the format string dynamically:

char fmt[10];
sprintf(fmt, "%%%lus", (unsigned long) (sizeof str_buf) - 1);
...
scanf(fmt, target_buffer); // fmt = "%55s"

EDIT

Using scanf with the %s conversion specifier will stop scanning at the first whitespace character; for example, if your input stream looks like

"This is a test"

then scanf("%55s", str_buf) will read and assign "This" to str_buf. Note that the field with specifier doesn't make a difference in this case.

phpMyAdmin - Error > Incorrect format parameter?

I had this error and as I'm on shared hosting I don't have access to the php.ini so wasn't sure how I could fix it, the host didn't seem to have a clue either. In the end I emptied my browser cache and reloaded phpmyadmin and it came back!

angular.js ng-repeat li items with html content

ng-bind-html-unsafe is deprecated from 1.2. The correct answer should be currently:

HTML-side: (the same as the accepted answer stated):

<div ng-app ng-controller="MyCtrl">
   <ul>
      <li ng-repeat=" opt in opts" ng-bind-html-unsafe="opt.text">
        {{ opt.text }}
      </li>
   </ul>

   <p>{{opt}}</p>
</div>

But in the controller-side:

myApp.controller('myCtrl', ['$scope', '$sce', function($scope, $sce) {
// ...
   $scope.opts.map(function(opt) { 
      opt = $sce.trustAsHtml(opt);
   });
}

jquery: get elements by class name and add css to each of them

What makes jQuery easy to use is that you don't have to apply attributes to each element. The jQuery object contains an array of elements, and the methods of the jQuery object applies the same attributes to all the elements in the array.

There is also a shorter form for $(document).ready(function(){...}) in $(function(){...}).

So, this is all you need:

$(function(){
  $('div.easy_editor').css('border','9px solid red');
});

If you want the code to work for any element with that class, you can just specify the class in the selector without the tag name:

$(function(){
  $('.easy_editor').css('border','9px solid red');
});

java.io.IOException: Broken pipe

Basically, what is happening is that your user is either closing the browser tab, or is navigating away to a different page, before communication was complete. Your webserver (Jetty) generates this exception because it is unable to send the remaining bytes.

org.eclipse.jetty.io.EofException: null
! at org.eclipse.jetty.http.HttpGenerator.flushBuffer(HttpGenerator.java:914)
! at org.eclipse.jetty.http.HttpGenerator.complete(HttpGenerator.java:798)
! at org.eclipse.jetty.server.AbstractHttpConnection.completeResponse(AbstractHttpConnection.java:642)
! 

This is not an error on your application logic side. This is simply due to user behavior. There is nothing wrong in your code per se.

There are two things you may be able to do:

  1. Ignore this specific exception so that you don't log it.
  2. Make your code more efficient/packed so that it transmits less data. (Not always an option!)

Why does Eclipse Java Package Explorer show question mark on some classes?

It means the class is not yet added to the repository.

If your project was checked-out (most probably a CVS project) and you added a new class file, it will have the ? icon.

For other CVS Label Decorations, check http://help.eclipse.org/help33/index.jsp?topic=/org.eclipse.platform.doc.user/reference/ref-cvs-decorations.htm

How do I fix 'Invalid character value for cast specification' on a date column in flat file?

The proper data type for "2010-12-20 00:00:00.0000000" value is DATETIME2(7) / DT_DBTIME2 ().

But used data type for CYCLE_DATE field is DATETIME - DT_DATE. This means milliseconds precision with accuracy down to every third millisecond (yyyy-mm-ddThh:mi:ss.mmL where L can be 0,3 or 7).

The solution is to change CYCLE_DATE date type to DATETIME2 - DT_DBTIME2.

How to set lifetime of session

Sessions can be configured in your php.ini file or in your .htaccess file. Have a look at the PHP session documentation.

What you basically want to do is look for the line session.cookie_lifetime in php.ini and make it's value is 0 so that the session cookie is valid until the browser is closed. If you can't edit that file, you could add php_value session.cookie_lifetime 0 to your .htaccess file.

Simple Vim commands you wish you'd known earlier

Build and debug your code from within Vim!

Configuration

Not much, really. You need a Makefile in the current directory.

To Compile

While you're in Vim, type :make to invoke a shell and build your program. Don't worry when the output scrolls by; just press Enter when it's finished to return to Vim.

The Magic

Back within Vim, you have the following commands at your disposal:

  1. :cl lists the errors, warnings, and other messages.
  2. :cc displays the current error/warning message at the bottom of the screen and jumps to the offending line in your code.
  3. :cc n jumps to the nth message.
  4. :cn advances to the next message.
  5. :cp jumps to the previous message.

There are more; if you're interested, type :help :cc from within Vim.

How to read all of Inputstream in Server Socket JAVA

The problem you have is related to TCP streaming nature.

The fact that you sent 100 Bytes (for example) from the server doesn't mean you will read 100 Bytes in the client the first time you read. Maybe the bytes sent from the server arrive in several TCP segments to the client.

You need to implement a loop in which you read until the whole message was received. Let me provide an example with DataInputStream instead of BufferedinputStream. Something very simple to give you just an example.

Let's suppose you know beforehand the server is to send 100 Bytes of data.

In client you need to write:

byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";

try 
{
    DataInputStream in = new DataInputStream(clientSocket.getInputStream());

    while(!end)
    {
        int bytesRead = in.read(messageByte);
        dataString += new String(messageByte, 0, bytesRead);
        if (dataString.length == 100)
        {
            end = true;
        }
    }
    System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
    e.printStackTrace();
}

Now, typically the data size sent by one node (the server here) is not known beforehand. Then you need to define your own small protocol for the communication between server and client (or any two nodes) communicating with TCP.

The most common and simple is to define TLV: Type, Length, Value. So you define that every message sent form server to client comes with:

  • 1 Byte indicating type (For example, it could also be 2 or whatever).
  • 1 Byte (or whatever) for length of message
  • N Bytes for the value (N is indicated in length).

So you know you have to receive a minimum of 2 Bytes and with the second Byte you know how many following Bytes you need to read.

This is just a suggestion of a possible protocol. You could also get rid of "Type".

So it would be something like:

byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";

try 
{
    DataInputStream in = new DataInputStream(clientSocket.getInputStream());
    int bytesRead = 0;

    messageByte[0] = in.readByte();
    messageByte[1] = in.readByte();

    int bytesToRead = messageByte[1];

    while(!end)
    {
        bytesRead = in.read(messageByte);
        dataString += new String(messageByte, 0, bytesRead);
        if (dataString.length == bytesToRead )
        {
            end = true;
        }
    }
    System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
    e.printStackTrace();
}

The following code compiles and looks better. It assumes the first two bytes providing the length arrive in binary format, in network endianship (big endian). No focus on different encoding types for the rest of the message.

import java.nio.ByteBuffer;
import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;

class Test
{
    public static void main(String[] args)
    {
        byte[] messageByte = new byte[1000];
        boolean end = false;
        String dataString = "";

        try 
        {
            Socket clientSocket;
            ServerSocket server;

            server = new ServerSocket(30501, 100);
            clientSocket = server.accept();

            DataInputStream in = new DataInputStream(clientSocket.getInputStream());
            int bytesRead = 0;

            messageByte[0] = in.readByte();
            messageByte[1] = in.readByte();
            ByteBuffer byteBuffer = ByteBuffer.wrap(messageByte, 0, 2);

            int bytesToRead = byteBuffer.getShort();
            System.out.println("About to read " + bytesToRead + " octets");

            //The following code shows in detail how to read from a TCP socket

            while(!end)
            {
                bytesRead = in.read(messageByte);
                dataString += new String(messageByte, 0, bytesRead);
                if (dataString.length() == bytesToRead )
                {
                    end = true;
                }
            }

            //All the code in the loop can be replaced by these two lines
            //in.readFully(messageByte, 0, bytesToRead);
            //dataString = new String(messageByte, 0, bytesToRead);

            System.out.println("MESSAGE: " + dataString);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

How to display pie chart data values of each slice in chart.js

For Chart.js 2.0 and up, the Chart object data has changed. For those who are using Chart.js 2.0+, below is an example of using HTML5 Canvas fillText() method to display data value inside of the pie slice. The code works for doughnut chart, too, with the only difference being type: 'pie' versus type: 'doughnut' when creating the chart.

Script:

Javascript

var data = {
    datasets: [{
        data: [
            11,
            16,
            7,
            3,
            14
        ],
        backgroundColor: [
            "#FF6384",
            "#4BC0C0",
            "#FFCE56",
            "#E7E9ED",
            "#36A2EB"
        ],
        label: 'My dataset' // for legend
    }],
    labels: [
        "Red",
        "Green",
        "Yellow",
        "Grey",
        "Blue"
    ]
};

var pieOptions = {
  events: false,
  animation: {
    duration: 500,
    easing: "easeOutQuart",
    onComplete: function () {
      var ctx = this.chart.ctx;
      ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
      ctx.textAlign = 'center';
      ctx.textBaseline = 'bottom';

      this.data.datasets.forEach(function (dataset) {

        for (var i = 0; i < dataset.data.length; i++) {
          var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model,
              total = dataset._meta[Object.keys(dataset._meta)[0]].total,
              mid_radius = model.innerRadius + (model.outerRadius - model.innerRadius)/2,
              start_angle = model.startAngle,
              end_angle = model.endAngle,
              mid_angle = start_angle + (end_angle - start_angle)/2;

          var x = mid_radius * Math.cos(mid_angle);
          var y = mid_radius * Math.sin(mid_angle);

          ctx.fillStyle = '#fff';
          if (i == 3){ // Darker text color for lighter background
            ctx.fillStyle = '#444';
          }
          var percent = String(Math.round(dataset.data[i]/total*100)) + "%";      
          //Don't Display If Legend is hide or value is 0
          if(dataset.data[i] != 0 && dataset._meta[0].data[i].hidden != true) {
            ctx.fillText(dataset.data[i], model.x + x, model.y + y);
            // Display percent in another line, line break doesn't work for fillText
            ctx.fillText(percent, model.x + x, model.y + y + 15);
          }
        }
      });               
    }
  }
};

var pieChartCanvas = $("#pieChart");
var pieChart = new Chart(pieChartCanvas, {
  type: 'pie', // or doughnut
  data: data,
  options: pieOptions
});

HTML

<canvas id="pieChart" width=200 height=200></canvas>

jsFiddle

"The operation is not valid for the state of the transaction" error and transaction scope

After doing some research, it seems I cannot have two connections opened to the same database with the TransactionScope block. I needed to modify my code to look like this:

public void MyAddUpdateMethod()
{
    using (TransactionScope Scope = new TransactionScope(TransactionScopeOption.RequiresNew))
    {
        using(SQLServer Sql = new SQLServer(this.m_connstring))
        {
            //do my first add update statement            
        }

        //removed the method call from the first sql server using statement
        bool DoesRecordExist = this.SelectStatementCall(id)
    }
}

public bool SelectStatementCall(System.Guid id)
{
    using(SQLServer Sql = new SQLServer(this.m_connstring))
    {
        //create parameters
    }
}

Read pdf files with php

There is a php library (pdfparser) that does exactly what you want.

project website

http://www.pdfparser.org/

github

https://github.com/smalot/pdfparser

Demo page/api

http://www.pdfparser.org/demo

After including pdfparser in your project you can get all text from mypdf.pdf like so:

<?php
$parser = new \installpath\PdfParser\Parser();
$pdf    = $parser->parseFile('mypdf.pdf');  
$text = $pdf->getText();
echo $text;//all text from mypdf.pdf

?>

Simular you can get the metadata from the pdf as wel as getting the pdf objects (for example images).

Verify host key with pysftp

Cook book to use different ways of pysftp.CnOpts() and hostkeys options.

Source : https://pysftp.readthedocs.io/en/release_0.2.9/cookbook.html

Host Key checking is enabled by default. It will use ~/.ssh/known_hosts by default. If you wish to disable host key checking (NOT ADVISED) you will need to modify the default CnOpts and set the .hostkeys to None.

import pysftp
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
with pysftp.Connection('host', username='me', password='pass', cnopts=cnopts):
    # do stuff here

To use a completely different known_hosts file, you can override CnOpts looking for ~/.ssh/known_hosts by specifying the file when instantiating.

import pysftp
cnopts = pysftp.CnOpts(knownhosts='path/to/your/knownhostsfile')

with pysftp.Connection('host', username='me', password='pass', cnopts=cnopts):
    # do stuff here

If you wish to use ~/.ssh/known_hosts but add additional known host keys you can merge with update additional known_host format files by using .load method.

import pysftp
cnopts = pysftp.CnOpts()
cnopts.hostkeys.load('path/to/your/extra_knownhosts')
with pysftp.Connection('host', username='me', password='pass', cnopts=cnopts):
    # do stuff here

Returning first x items from array

A more object oriented way would be to provide a range to the #[] method. For instance:

Say you want the first 3 items from an array.

numbers = [1,2,3,4,5,6]

numbers[0..2] # => [1,2,3]

Say you want the first x items from an array.

numbers[0..x-1]

The great thing about this method is if you ask for more items than the array has, it simply returns the entire array.

numbers[0..100] # => [1,2,3,4,5,6]

How to install Guest addition in Mac OS as guest and Windows machine as host

Before you start, close VirtualBox! After those manipulations start VB as Administrator!


  1. Run CMD as Administrator
  2. Use lines below one by one:
  • cd "C:\Program Files\Oracle\Virtualbox"
  • VBoxManage setextradata “macOS_Catalina” VBoxInternal2/EfiGraphicsResolution 1920x1080

Screen Resolutions: 1280x720, 1920x1080, 2048x1080, 2560x1440, 3840x2160, 1280x800, 1280x1024, 1440x900, 1600x900

Description:

  • macOS_Catalina - insert your VB machine name.

  • 1920x1080 - put here your Screen Resolution.

Cheers!

Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)

This is a simple way from XML only

spanCount for number of columns

layoutManager for making it grid or linear(Vertical or Horizontal)

<androidx.recyclerview.widget.RecyclerView
        android:id="@+id/personListRecyclerView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
        app:spanCount="2"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

What is meaning of negative dbm in signal strength?

At ms end Rx lev ranges 0 to -120 dbm Mean antenna power which received at ms end alway less than 1mW.

Thats why it always -ve.

Detecting value change of input[type=text] in jQuery

Try this:

Basically, just account for each event:

Html:

<input id = "textbox" type = "text">

Jquery:

$("#textbox").keyup(function() { 
    alert($(this).val());  
}); 

$("#textbox").change(function() { 
alert($(this).val());  
}); 

Case statement in MySQL

MySQL also has IF():

SELECT 
  id, action_heading, 
      IF(action_type='Income',action_amount,0) income, 
      IF(action_type='Expense', action_amount, 0) expense
FROM tbl_transaction

When maven says "resolution will not be reattempted until the update interval of MyRepo has elapsed", where is that interval specified?

According to the settings reference:

updatePolicy: This element specifies how often updates should attempt to occur. Maven will compare the local POM’s timestamp (stored in a repository’s maven-metadata file) to the remote. The choices are: always, daily (default), interval:X (where X is an integer in minutes) or never.

Example:

<profiles>
    <profile>
      ...
      <repositories>
        <repository>
          <id>myRepo</id>
          <name>My Repository</name>
          <releases>
            <enabled>false</enabled>
            <updatePolicy>always</updatePolicy>
            <checksumPolicy>warn</checksumPolicy>
          </releases>
         </repository>
      </repositories>
      ...
    </profile>
  </profiles>
  ...
</settings>

Replacement for "rename" in dplyr

The next version of dplyr will support an improved version of select that also incorporates renaming:

> mtcars2 <- select( mtcars, disp2 = disp )
> head( mtcars2 )
                  disp2
Mazda RX4         160
Mazda RX4 Wag     160
Datsun 710        108
Hornet 4 Drive    258
Hornet Sportabout 360
Valiant           225
> changes( mtcars, mtcars2 )
Changed variables:
      old         new
disp  0x105500400
disp2             0x105500400

Changed attributes:
      old         new
names 0x106d2cf50 0x106d28a98

Adding a Scrollable JTextArea (Java)

  1. Open design view
  2. Right click to textArea
  3. open surround with option
  4. select "...JScrollPane".

Using HTML and Local Images Within UIWebView

You can add folder (say WEB with sub folders css, img and js and file test.html) to your project by choosing Add Files to "MyProj" and selecting Create folder references. Now the following code will take care about all the referred images, css and javascript

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"WEB/test.html" ofType:nil];
[webView  loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];

What is the difference between a schema and a table and a database?

More on schemas:

In SQL 2005 a schema is a way to group objects. It is a container you can put objects into. People can own this object. You can grant rights on the schema.

In 2000 a schema was equivalent to a user. Now it has broken free and is quite useful. You could throw all your user procs in a certain schema and your admin procs in another. Grant EXECUTE to the appropriate user/role and you're through with granting EXECUTE on specific procedures. Nice.

The dot notation would go like this:

Server.Database.Schema.Object

or

myserver01.Adventureworks.Accounting.Beans

What is the difference between active and passive FTP?

I recently run into this question in my work place so I think I should say something more here. I will use image to explain how the FTP works as an additional source for previous answer.

Active mode:

active mode


Passive mode:

enter image description here


In an active mode configuration, the server will attempt to connect to a random client-side port. So chances are, that port wouldn't be one of those predefined ports. As a result, an attempt to connect to it will be blocked by the firewall and no connection will be established.

enter image description here


A passive configuration will not have this problem since the client will be the one initiating the connection. Of course, it's possible for the server side to have a firewall too. However, since the server is expected to receive a greater number of connection requests compared to a client, then it would be but logical for the server admin to adapt to the situation and open up a selection of ports to satisfy passive mode configurations.

So it would be best for you to configure server to support passive mode FTP. However, passive mode would make your system vulnerable to attacks because clients are supposed to connect to random server ports. Thus, to support this mode, not only should your server have to have multiple ports available, your firewall should also allow connections to all those ports to pass through!

To mitigate the risks, a good solution would be to specify a range of ports on your server and then to allow only that range of ports on your firewall.

For more information, please read the official document.

node.js http 'get' request with query string parameters

No need for a 3rd party library. Use the nodejs url module to build a URL with query parameters:

const requestUrl = url.parse(url.format({
    protocol: 'https',
    hostname: 'yoursite.com',
    pathname: '/the/path',
    query: {
        key: value
    }
}));

Then make the request with the formatted url. requestUrl.path will include the query parameters.

const req = https.get({
    hostname: requestUrl.hostname,
    path: requestUrl.path,
}, (res) => {
   // ...
})

VBScript - How to make program wait until process has finished?

Probably something like this? (UNTESTED)

Sub Sample()
    Dim strWB4, strMyMacro
    strMyMacro = "Sheet1.my_macro_name"

    '
    '~~> Rest of Code
    '

    'loop through the folder and get the file names
    For Each Fil In FLD.Files
        Set x4WB = x1.Workbooks.Open(Fil)
        x4WB.Application.Visible = True

        x1.Run strMyMacro

        x4WB.Close

        Do Until IsWorkBookOpen(Fil) = False
            DoEvents
        Loop
    Next

    '
    '~~> Rest of Code
    '
End Sub

'~~> Function to check if the file is open
Function IsWorkBookOpen(FileName As String)
    Dim ff As Long, ErrNo As Long

    On Error Resume Next
    ff = FreeFile()
    Open FileName For Input Lock Read As #ff
    Close ff
    ErrNo = Err
    On Error GoTo 0

    Select Case ErrNo
    Case 0:    IsWorkBookOpen = False
    Case 70:   IsWorkBookOpen = True
    Case Else: Error ErrNo
    End Select
End Function

jQuery trigger file input

It is too late to answer but I think this minimal setup work best. I am also looking for the same.

  <div class="btn-file">
     <input type="file" class="hidden-input">
     Select your new picture
  </div>

//css

.btn-file {
  display: inline-block;
  padding: 8px 12px;
  cursor: pointer;
  background: #89f;
  color: #345;
  position: relative;
  overflow: hidden;
}

.btn-file input[type=file] {
  position: absolute;
  top: 0;
  right: 0;
  min-width: 100%;
  min-height: 100%;
  filter: alpha(opacity=0);
  opacity: 0;
  cursor: inherit;
  display: block;
}

jsbin

bootstrap file input buttons demo

Could not install packages due to an EnvironmentError: [Errno 13]

Regarding the permissions command, try using sudo in front of your terminal command:

sudo pip install --upgrade pip

Sudo allows you to run the command with the privileges of the superuser and will install the package for the global, system-wide Python installation. Ideally, you should create a virtual environment for the project you are working on. Have a look at this

Regarding the python Try running pip as an executable like this:

python3.6 -m pip install <package>

IIS7 Permissions Overview - ApplicationPoolIdentity

ApplicationPoolIdentity is actually the best practice to use in IIS7+. It is a dynamically created, unprivileged account. To add file system security for a particular application pool see IIS.net's "Application Pool Identities". The quick version:

If the application pool is named "DefaultAppPool" (just replace this text below if it is named differently)

  1. Open Windows Explorer
  2. Select a file or directory.
  3. Right click the file and select "Properties"
  4. Select the "Security" tab
  5. Click the "Edit" and then "Add" button
  6. Click the "Locations" button and make sure you select the local machine. (Not the Windows domain if the server belongs to one.)
  7. Enter "IIS AppPool\DefaultAppPool" in the "Enter the object names to select:" text box. (Don't forget to change "DefaultAppPool" here to whatever you named your application pool.)
  8. Click the "Check Names" button and click "OK".

Get values from a listbox on a sheet

The accepted answer doesn't cut it because if a user de-selects a row the list is not updated accordingly.

Here is what I suggest instead:

Private Sub CommandButton2_Click()
    Dim lItem As Long

    For lItem = 0 To ListBox1.ListCount - 1
        If ListBox1.Selected(lItem) = True Then
            MsgBox(ListBox1.List(lItem))
        End If
    Next
End Sub

Courtesy of http://www.ozgrid.com/VBA/multi-select-listbox.htm

Generating random, unique values C#

randomNumber function return unqiue integer value between 0 to 100000

  bool check[] = new bool[100001];
  Random r = new Random();
  public int randomNumber() {
      int num = r.Next(0,100000);
       while(check[num] == true) {
             num = r.Next(0,100000);
     }
    check[num] = true;
   return num;
 }

How to include another XHTML in XHTML using JSF 2.0 Facelets?

Included page:

<!-- opening and closing tags of included page -->
<ui:composition ...>
</ui:composition>

Including page:

<!--the inclusion line in the including page with the content-->
<ui:include src="yourFile.xhtml"/>
  • You start your included xhtml file with ui:composition as shown above.
  • You include that file with ui:include in the including xhtml file as also shown above.

How can I pass a member function where a free function is expected?

There isn't anything wrong with using function pointers. However, pointers to non-static member functions are not like normal function pointers: member functions need to be called on an object which is passed as an implicit argument to the function. The signature of your member function above is, thus

void (aClass::*)(int, int)

rather than the type you try to use

void (*)(int, int)

One approach could consist in making the member function static in which case it doesn't require any object to be called on and you can use it with the type void (*)(int, int).

If you need to access any non-static member of your class and you need to stick with function pointers, e.g., because the function is part of a C interface, your best option is to always pass a void* to your function taking function pointers and call your member through a forwarding function which obtains an object from the void* and then calls the member function.

In a proper C++ interface you might want to have a look at having your function take templated argument for function objects to use arbitrary class types. If using a templated interface is undesirable you should use something like std::function<void(int, int)>: you can create a suitably callable function object for these, e.g., using std::bind().

The type-safe approaches using a template argument for the class type or a suitable std::function<...> are preferable than using a void* interface as they remove the potential for errors due to a cast to the wrong type.

To clarify how to use a function pointer to call a member function, here is an example:

// the function using the function pointers:
void somefunction(void (*fptr)(void*, int, int), void* context) {
    fptr(context, 17, 42);
}

void non_member(void*, int i0, int i1) {
    std::cout << "I don't need any context! i0=" << i0 << " i1=" << i1 << "\n";
}

struct foo {
    void member(int i0, int i1) {
        std::cout << "member function: this=" << this << " i0=" << i0 << " i1=" << i1 << "\n";
    }
};

void forwarder(void* context, int i0, int i1) {
    static_cast<foo*>(context)->member(i0, i1);
}

int main() {
    somefunction(&non_member, nullptr);
    foo object;
    somefunction(&forwarder, &object);
}

Merging two arrays in .NET

If you can manipulate one of the arrays, you can resize it before performing the copy:

T[] array1 = getOneArray();
T[] array2 = getAnotherArray();
int array1OriginalLength = array1.Length;
Array.Resize<T>(ref array1, array1OriginalLength + array2.Length);
Array.Copy(array2, 0, array1, array1OriginalLength, array2.Length);

Otherwise, you can make a new array

T[] array1 = getOneArray();
T[] array2 = getAnotherArray();
T[] newArray = new T[array1.Length + array2.Length];
Array.Copy(array1, newArray, array1.Length);
Array.Copy(array2, 0, newArray, array1.Length, array2.Length);

More on available Array methods on MSDN.

must appear in the GROUP BY clause or be used in an aggregate function

SELECT t1.cname, t1.wmname, t2.max
FROM makerar t1 JOIN (
    SELECT cname, MAX(avg) max
    FROM makerar
    GROUP BY cname ) t2
ON t1.cname = t2.cname AND t1.avg = t2.max;

Using rank() window function:

SELECT cname, wmname, avg
FROM (
    SELECT cname, wmname, avg, rank() 
    OVER (PARTITION BY cname ORDER BY avg DESC)
    FROM makerar) t
WHERE rank = 1;

Note

Either one will preserve multiple max values per group. If you want only single record per group even if there is more than one record with avg equal to max you should check @ypercube's answer.

How can I center text (horizontally and vertically) inside a div block?

Apply style:

position: absolute;
top: 50%;
left: 0;
right: 0;

Your text would be centered irrespective of its length.

Encoding as Base64 in Java

Use Java 8's never-too-late-to-join-in-the-fun class: java.util.Base64

new String(Base64.getEncoder().encode(bytes));

Search code inside a Github project

Recent private repositories have a search field for searching through that repo.

enter image description here

Bafflingly, it looks like this functionality is not available to public repositories, though.

"if not exist" command in batch file

When testing for directories remember that every directory contains two special files.

One is called '.' and the other '..'

. is the directory's own name while .. is the name of it's parent directory.

To avoid trailing backslash problems just test to see if the directory knows it's own name.

eg:

if not exist %temp%\buffer\. mkdir %temp%\buffer

MySQL : ERROR 1215 (HY000): Cannot add foreign key constraint

I don't see anyone stating this explicitly and I had this same error message and my problem was that I was trying to add a foreign key to a TEMPORARY table. Which is disallowed as noted in the manual

Foreign key relationships involve a parent table that holds the central data values, and a child table with identical values pointing back to its parent. The FOREIGN KEY clause is specified in the child table. The parent and child tables must use the same storage engine. They must not be TEMPORARY tables.

(emphasis mine)

Set min-width either by content or 200px (whichever is greater) together with max-width

The problem is that flex: 1 sets flex-basis: 0. Instead, you need

.container .box {
  min-width: 200px;
  max-width: 400px;
  flex-basis: auto; /* default value */
  flex-grow: 1;
}

_x000D_
_x000D_
.container {_x000D_
  display: -webkit-flex;_x000D_
  display: flex;_x000D_
  -webkit-flex-wrap: wrap;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
  -webkit-flex-grow: 1;_x000D_
  flex-grow: 1;_x000D_
  min-width: 100px;_x000D_
  max-width: 400px;_x000D_
  height: 200px;_x000D_
  background-color: #fafa00;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to Add Stacktrace or debug Option when Building Android Studio Project

To Increase Maximum heap: Click to open your Android Studio, look at below pictures. Step by step. ANDROID STUDIO v2.1.2

Click to navigate to Settings from the Configure or GO TO FILE SETTINGS at the top of Android Studio.

enter image description here

check also the android compilers from the link to confirm if it also change if not increase to the same size you modify from the compiler link.

Note: You can increase the size base on your memory capacity and remember this setting is base on Android Studio v2.1.2

How to maintain page scroll position after a jquery event is carried out?

Try the code below to prevent the default behaviour scrolling back to the top of the page

$(document).ready(function() {   
  $('.galleryicon').live("click", function(e) {  // the (e) represent the event
    $('#mainImage').hide();     
    $('#cakebox').css('background-image', "url('ajax-loader.gif')");     
    var i = $('<img />').attr('src',this.href).load(function() {         
      $('#mainImage').attr('src', i.attr('src'));         
      $('#cakebox').css('background-image', 'none');         
      $('#mainImage').fadeIn();     
    });
  e.preventDefault(); //Prevent default click action which is causing the 
  return false;       //page to scroll back to the top
  });  
});

For more information on event.preventDefault() have a look here at the official documentation.

How to set background image in Java?

Or try this ;)

try {
  this.setContentPane(
    new JLabel(new ImageIcon(ImageIO.read(new File("your_file.jpeg")))));
} catch (IOException e) {};

How can I get the SQL of a PreparedStatement?

Very late :) but you can get the original SQL from an OraclePreparedStatementWrapper by

((OraclePreparedStatementWrapper) preparedStatement).getOriginalSql();

How to convert String to long in Java?

To convert a String to a Long (object), use Long.valueOf(String s).longValue();

See link

Is it possible to make desktop GUI application in .NET Core?

One option would be using Electron with JavaScript, HTML, and CSS for UI and build a .NET Core console application that will self-host a web API for back-end logic. Electron will start the console application in the background that will expose a service on localhost:xxxx.

This way you can implement all back-end logic using .NET to be accessible through HTTP requests from JavaScript.

Take a look at this post, it explains how to build a cross-platform desktop application with Electron and .NET Core and check code on GitHub.

What is Parse/parsing?

Parsing is just process of analyse the string of character and find the tokens from that string and parser is a component of interpreter and compiler.It uses lexical analysis and then syntactic analysis.It parse it and then compile this code after this whole process of compilation.

Javascript foreach loop on associative array object

The .length property only tracks properties with numeric indexes (keys). You're using strings for keys.

You can do this:

var arr_jq_TabContents = {}; // no need for an array

arr_jq_TabContents["Main"] = jq_TabContents_Main;
arr_jq_TabContents["Guide"] = jq_TabContents_Guide;
arr_jq_TabContents["Articles"] = jq_TabContents_Articles;
arr_jq_TabContents["Forum"] = jq_TabContents_Forum;

for (var key in arr_jq_TabContents) {
    console.log(arr_jq_TabContents[key]);
}

To be safe, it's a good idea in loops like that to make sure that none of the properties are unexpected results of inheritance:

for (var key in arr_jq_TabContents) {
  if (arr_jq_TabContents.hasOwnProperty(key))
    console.log(arr_jq_TabContents[key]);
}

edit — it's probably a good idea now to note that the Object.keys() function is available on modern browsers and in Node etc. That function returns the "own" keys of an object, as an array:

Object.keys(arr_jq_TabContents).forEach(function(key, index) {
  console.log(this[key]);
}, arr_jq_TabContents);

The callback function passed to .forEach() is called with each key and the key's index in the array returned by Object.keys(). It's also passed the array through which the function is iterating, but that array is not really useful to us; we need the original object. That can be accessed directly by name, but (in my opinion) it's a little nicer to pass it explicitly, which is done by passing a second argument to .forEach() — the original object — which will be bound as this inside the callback. (Just saw that this was noted in a comment below.)

Insert node at a certain position in a linked list C++

Node* insert_node_at_nth_pos(Node *head, int data, int position)
{   
    /* current node */
    Node* cur = head;

    /* initialize new node to be inserted at given position */
    Node* nth = new Node;
    nth->data = data;
    nth->next = NULL;

    if(position == 0){
        /* insert new node at head */
        head = nth;
        head->next = cur;
        return head;
    }else{
        /* traverse list */
        int count = 0;            
        Node* pre = new Node;

        while(count != position){
            if(count == (position - 1)){
                pre = cur;
            }
            cur = cur->next;            
            count++;
        }

        /* insert new node here */
        pre->next = nth;
        nth->next = cur;

        return head;
    }    
}

What is the size of a boolean variable in Java?

On a side note...

If you are thinking about using an array of Boolean objects, don't. Use a BitSet instead - it has some performance optimisations (and some nice extra methods, allowing you to get the next set/unset bit).

How to show current time in JavaScript in the format HH:MM:SS?

_x000D_
_x000D_
function checkTime(i) {_x000D_
  if (i < 10) {_x000D_
    i = "0" + i;_x000D_
  }_x000D_
  return i;_x000D_
}_x000D_
_x000D_
function startTime() {_x000D_
  var today = new Date();_x000D_
  var h = today.getHours();_x000D_
  var m = today.getMinutes();_x000D_
  var s = today.getSeconds();_x000D_
  // add a zero in front of numbers<10_x000D_
  m = checkTime(m);_x000D_
  s = checkTime(s);_x000D_
  document.getElementById('time').innerHTML = h + ":" + m + ":" + s;_x000D_
  t = setTimeout(function() {_x000D_
    startTime()_x000D_
  }, 500);_x000D_
}_x000D_
startTime();
_x000D_
<div id="time"></div>
_x000D_
_x000D_
_x000D_

DEMO using javaScript only

Update

Updated Demo

(function () {
    function checkTime(i) {
        return (i < 10) ? "0" + i : i;
    }

    function startTime() {
        var today = new Date(),
            h = checkTime(today.getHours()),
            m = checkTime(today.getMinutes()),
            s = checkTime(today.getSeconds());
        document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
        t = setTimeout(function () {
            startTime()
        }, 500);
    }
    startTime();
})();

Why does multiplication repeats the number several times?

It's the difference between strings and integers. See:

>>> "1" * 9
'111111111'

>>> 1 * 9
9

How to remove a row from JTable?

In order to remove a row from a JTable, you need to remove the target row from the underlying TableModel. If, for instance, your TableModel is an instance of DefaultTableModel, you can remove a row by doing the following:

((DefaultTableModel)myJTable.getModel()).removeRow(rowToRemove);

The PowerShell -and conditional operator

Another option:

if( ![string]::IsNullOrEmpty($user_sam) -and ![string]::IsNullOrEmpty($user_case) )
{
   ...
}

Excel - find cell with same value in another worksheet and enter the value to the left of it

Assuming employee numbers are in the first column and their names are in the second:

=VLOOKUP(A1, Sheet2!A:B, 2,false)

Python not working in command prompt?

Just a few comments:

  1. Don't set PYTHONPATH if all you want is to get Python on the PATH. The PYTHONPATH environment variable tells Python where to look for modules to import. Setting it to C:\Python27\ will not accomplish anything useful, although it's probably harmless.

  2. Modifying environment variables (including PATH) from the "Edit System Variables" has no effect on already running processes. This means you have to re-launch cmd.exe for the changes to work. A reboot, however, is not required.

  3. When modifying the PATH, also add the Scripts subdirectory. Or, to put it in other words (and using the previous example): add ;C:\Python27;C:\Python27\Scripts. This will allow you to run scripts like easy_install, pip, virtualenv or sphinx from the command line - once you install those, that is. This is about as UNIX-y as it gets for Windows. (N.B. The Scripts subdirectory is not present after a clean install of Python, but will be created when needed.)

  4. Don't put any additional Lib or DLL directory on the PATH. There's no need, and it might do harm.

  5. If you have installed multiple versions of Python (which isn't all that uncommon) you might be better off not putting any of them on the PATH but instead create different shortcuts to cmd.exe for the different versions which set the PATH for each version. You might also be interested in PEP-397.

how to break the _.each function in underscore.js

Update:

_.find would be better as it breaks out of the loop when the element is found:

var searchArr = [{id:1,text:"foo"},{id:2,text:"bar"}];
var count = 0;
var filteredEl = _.find(searchArr,function(arrEl){ 
              count = count +1;
              if(arrEl.id === 1 ){
                  return arrEl;
              }
            });

console.log(filteredEl);
//since we are searching the first element in the array, the count will be one
console.log(count);
//output: filteredEl : {id:1,text:"foo"} , count: 1

** Old **

If you want to conditionally break out of a loop, use _.filter api instead of _.each. Here is a code snippet

var searchArr = [{id:1,text:"foo"},{id:2,text:"bar"}];
var filteredEl = _.filter(searchArr,function(arrEl){ 
                  if(arrEl.id === 1 ){
                      return arrEl;
                  }
                });
console.log(filteredEl);
//output: {id:1,text:"foo"}

Django optional url parameters

You can use nested routes

Django <1.8

urlpatterns = patterns(''
    url(r'^project_config/', include(patterns('',
        url(r'^$', ProjectConfigView.as_view(), name="project_config")
        url(r'^(?P<product>\w+)$', include(patterns('',
            url(r'^$', ProductView.as_view(), name="product"),
            url(r'^(?P<project_id>\w+)$', ProjectDetailView.as_view(), name="project_detail")
        ))),
    ))),
)

Django >=1.8

urlpatterns = [
    url(r'^project_config/', include([
        url(r'^$', ProjectConfigView.as_view(), name="project_config")
        url(r'^(?P<product>\w+)$', include([
            url(r'^$', ProductView.as_view(), name="product"),
            url(r'^(?P<project_id>\w+)$', ProjectDetailView.as_view(), name="project_detail")
        ])),
    ])),
]

This is a lot more DRY (Say you wanted to rename the product kwarg to product_id, you only have to change line 4, and it will affect the below URLs.

Edited for Django 1.8 and above

Extract first item of each sublist

Using list comprehension:

>>> lst = [['a','b','c'], [1,2,3], ['x','y','z']]
>>> lst2 = [item[0] for item in lst]
>>> lst2
['a', 1, 'x']

Flutter: how to make a TextField with HintText but no Underline?

TextField widget has a property decoration which has a sub property border: InputBorder.none.This property would Remove TextField Text Input Bottom Underline in Flutter app. So you can set the border property of the decoration of the TextField to InputBorder.none, see here for an example:

border: InputBorder.none : Hide bottom underline from Text Input widget.

 Container(
        width: 280,
        padding: EdgeInsets.all(8.0),
        child : TextField(
                autocorrect: true,
                decoration: InputDecoration(
                border: InputBorder.none,
                hintText: 'Enter Some Text Here')
            )
    )

How to check if a line is blank using regex

Well...I tinkered around (using notepadd++) and this is the solution I found

\n\s

\n for end of line (where you start matching) -- the caret would not be of help in my case as the beginning of the row is a string \s takes any space till the next string

hope it helps

What is href="#" and why is it used?

The href attribute defines the URL of the resource of a link. If the anchor tag does not have href tag then it will not become hyperlink. The href attribute have the following values:

1. Absolute path: move to another site like href="http://www.google.com"
2. Relative path: move to another page within the site like herf ="defaultpage.aspx"
3. Move to an element with a specified id within the page like href="#bottom"
4. href="javascript:void(0)", it does not move anywhere.
5. href="#" , it does not move anywhere but scroll on the top of the current page.
6. href= "" , it will load the current page but some browsers causes forbidden errors.

Note: When we do not need to specified any url inside a anchor tag then use 
<a href="javascript:void(0)">Test1</a>

How can I use threading in Python?

For me, the perfect example for threading is monitoring asynchronous events. Look at this code.

# thread_test.py
import threading
import time

class Monitor(threading.Thread):
    def __init__(self, mon):
        threading.Thread.__init__(self)
        self.mon = mon

    def run(self):
        while True:
            if self.mon[0] == 2:
                print "Mon = 2"
                self.mon[0] = 3;

You can play with this code by opening an IPython session and doing something like:

>>> from thread_test import Monitor
>>> a = [0]
>>> mon = Monitor(a)
>>> mon.start()
>>> a[0] = 2
Mon = 2
>>>a[0] = 2
Mon = 2

Wait a few minutes

>>> a[0] = 2
Mon = 2

Javascript split regex question

you could just use

date.split(/-/);

or

date.split('-');

Xcode 4 - "Archive" is greyed out?

As the other answers state, you need to select an active scheme to something that is not a simulator, i.e. a device that's connected to your mac.

If you have no device connected to the mac then selecting "Generic IOS Device" works also.

enter image description here

Rotating a two-dimensional array in Python

That's a clever bit.

First, as noted in a comment, in Python 3 zip() returns an iterator, so you need to enclose the whole thing in list() to get an actual list back out, so as of 2020 it's actually:

list(zip(*original[::-1]))

Here's the breakdown:

  • [::-1] - makes a shallow copy of the original list in reverse order. Could also use reversed() which would produce a reverse iterator over the list rather than actually copying the list (more memory efficient).
  • * - makes each sublist in the original list a separate argument to zip() (i.e., unpacks the list)
  • zip() - takes one item from each argument and makes a list (well, a tuple) from those, and repeats until all the sublists are exhausted. This is where the transposition actually happens.
  • list() converts the output of zip() to a list.

So assuming you have this:

[ [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9] ]

You first get this (shallow, reversed copy):

[ [7, 8, 9],
  [4, 5, 6],
  [1, 2, 3] ]

Next each of the sublists is passed as an argument to zip:

zip([7, 8, 9], [4, 5, 6], [1, 2, 3])

zip() repeatedly consumes one item from the beginning of each of its arguments and makes a tuple from it, until there are no more items, resulting in (after it's converted to a list):

[(7, 4, 1), 
 (8, 5, 2), 
 (9, 6, 3)]

And Bob's your uncle.

To answer @IkeMiguel's question in a comment about rotating it in the other direction, it's pretty straightforward: you just need to reverse both the sequences that go into zip and the result. The first can be achieved by removing the [::-1] and the second can be achieved by throwing a reversed() around the whole thing. Since reversed() returns an iterator over the list, we will need to put list() around that to convert it. With a couple extra list() calls to convert the iterators to an actual list. So:

rotated = list(reversed(list(zip(*original))))

We can simplify that a bit by using the "Martian smiley" slice rather than reversed()... then we don't need the outer list():

rotated = list(zip(*original))[::-1]

Of course, you could also simply rotate the list clockwise three times. :-)

Difference between onStart() and onResume()

A particularly feisty example is when you decide to show a managed Dialog from an Activity using showDialog(). If the user rotates the screen while the dialog is still open (we call this a "configuration change"), then the main Activity will go through all the ending lifecycle calls up untill onDestroy(), will be recreated, and go back up through the lifecycles. What you might not expect however, is that onCreateDialog() and onPrepareDialog() (the methods that are called when you do showDialog() and now again automatically to recreate the dialog - automatically since it is a managed dialog) are called between onStart() and onResume(). The pointe here is that the dialog does not cover the full screen and therefore leaves part of the main activity visible. It's a detail but it does matter!

Load image with jQuery and append it to the DOM

$('<img src="'+ imgPath +'">').load(function() {
  $(this).width(some).height(some).appendTo('#some_target');
});

If you want to do for several images then:

function loadImage(path, width, height, target) {
    $('<img src="'+ path +'">').load(function() {
      $(this).width(width).height(height).appendTo(target);
    });
}

Use:

loadImage(imgPath, 800, 800, '#some_target');

Easy way to add drop down menu with 1 - 100 without doing 100 different options?

Are you using JavaScript or jQuery besides the html? If you are, you can do something like:

HTML:

<select id='some_selector'></select>?

jQuery:

var select = '';
for (i=1;i<=100;i++){
    select += '<option val=' + i + '>' + i + '</option>';
}
$('#some_selector').html(select);

As you can see here.

Another option for compatible browsers instead of select, you can use is HTML5's input type=number:

<input type="number" min="1" max="100" value="1">

String contains another string

You can use .indexOf():

if(str.indexOf(substr) > -1) {

}

change image opacity using javascript

I'm not sure if you can do this in every browser but you can set the css property of the specified img.
Try to work with jQuery which allows you to make css changes much faster and efficiently.
in jQuery you will have the options of using .animate(),.fadeTo(),.fadeIn(),.hide("slow"),.show("slow") for example.
I mean this CSS snippet should do the work for you:

img
{
opacity:0.4;
filter:alpha(opacity=40); /* For IE8 and earlier */
}

Also check out this website where everything further is explained:
http://www.w3schools.com/css/css_image_transparency.asp

How to get a list of images on docker registry v2

I wrote an easy-to-use command line tool for listing images in various ways (like list all images, list all tags of those images, list all layers of those tags).

It also allows you to delete unused images in various ways, like delete only older tags of a single image or from all images etc. This is convenient when you are filling your registry from a CI server and want to keep only latest/stable versions.

It is written in python and does not need you to download bulky big custom registry images.

How to concatenate int values in java?

How about not using strings at all...

This should work for any number of digits...

int[] nums = {1, 0, 2, 2, 1};

int retval = 0;

for (int digit : nums)
{
    retval *= 10;
    retval += digit;
}

System.out.println("Return value is: " + retval);

Response::json() - Laravel 5.1

You need to add use Response; facade in header at your file.

Only then you can successfully retrieve your data with

return Response::json($data);

C++ inheritance - inaccessible base?

You have to do this:

class Bar : public Foo
{
    // ...
}

The default inheritance type of a class in C++ is private, so any public and protected members from the base class are limited to private. struct inheritance on the other hand is public by default.

Why is PHP session_destroy() not working?

I had to also remove session cookies like this:

session_start(); 
$_SESSION = []; 

// If it's desired to kill the session, also 
// delete the session cookie. 
// Note: This will destroy the session, and 
// not just the session data! 
if (ini_get("session.use_cookies")) { 
    $params = session_get_cookie_params(); 
    setcookie(session_name(), '', time() - 42000, 
        $params["path"], $params["domain"], 
        $params["secure"], $params["httponly"] 
    ); 
} 

// Finally, destroy the session. 
session_destroy();

Source: geeksforgeeks.org

What is the maximum length of data I can put in a BLOB column in MySQL?

May or may not be accurate, but according to this site: http://www.htmlite.com/mysql003.php.

BLOB A string with a maximum length of 65535 characters.

The MySQL manual says:

The maximum size of a BLOB or TEXT object is determined by its type, but the largest value you actually can transmit between the client and server is determined by the amount of available memory and the size of the communications buffers

I think the first site gets their answers from interpreting the MySQL manual, per http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html

Get commit list between tags in git

If your team uses descriptive commit messages (eg. "Ticket #12345 - Update dependencies") on this project, then generating changelog since the latest tag can de done like this:

git log --no-merges --pretty=format:"%s" 'old-tag^'...new-tag > /path/to/changelog.md
  • --no-merges omits the merge commits from the list
  • old-tag^ refers to the previous commit earlier than the tagged one. Useful if you want to see the tagged commit at the bottom of the list by any reason. (Single quotes needed only for iTerm on mac OS).

Deleting records before a certain date

This helped me delete data based on different attributes. This is dangerous so make sure you back up database or the table before doing it:

mysqldump -h hotsname -u username -p password database_name > backup_folder/backup_filename.txt

Now you can perform the delete operation:

delete from table_name where column_name < DATE_SUB(NOW() , INTERVAL 1 DAY)

This will remove all the data from before one day. For deleting data from before 6 months:

delete from table_name where column_name < DATE_SUB(NOW() , INTERVAL 6 MONTH)

JavaScript string with new line - but not using \n

I think they using \n anyway even couse it not visible, or maybe they using \r. So just replace \n or \r with <br/>

What is android:weightSum in android, and how does it work?

The documentation says it best and includes an example, (highlighting mine).

android:weightSum

Defines the maximum weight sum. If unspecified, the sum is computed by adding the layout_weight of all of the children. This can be used for instance to give a single child 50% of the total available space by giving it a layout_weight of 0.5 and setting the weightSum to 1.0.

So to correct superM's example, suppose you have a LinearLayout with horizontal orientation that contains two ImageViews and a TextView with. You define the TextView to have a fixed size, and you'd like the two ImageViews to take up the remaining space equally.

To accomplish this, you would apply layout_weight 1 to each ImageView, none on the TextView, and a weightSum of 2.0 on the LinearLayout.

Set session variable in laravel

php artisan make:controller SessionController --plain

Then

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class SessionController extends Controller {
   public function accessSessionData(Request $request) {
      if($request->session()->has('my_name'))
         echo $request->session()->get('my_name');
      else
         echo 'No data in the session';
   }
   public function storeSessionData(Request $request) {
      $request->session()->put('my_name','Ajay kumar');
      echo "Data has been added to session";
   }
   public function deleteSessionData(Request $request) {
      $request->session()->forget('my_name');
      echo "Data has been removed from session.";
   }
}
?>

And all route:

Route::get('session/get','SessionController@accessSessionData');
Route::get('session/set','SessionController@storeSessionData');
Route::get('session/remove','SessionController@deleteSessionData');

More Help: How To Set Session In Laravel?

Split / Explode a column of dictionaries into separate columns with pandas

You can use join with pop + tolist. Performance is comparable to concat with drop + tolist, but some may find this syntax cleaner:

res = df.join(pd.DataFrame(df.pop('b').tolist()))

Benchmarking with other methods:

df = pd.DataFrame({'a':[1,2,3], 'b':[{'c':1}, {'d':3}, {'c':5, 'd':6}]})

def joris1(df):
    return pd.concat([df.drop('b', axis=1), df['b'].apply(pd.Series)], axis=1)

def joris2(df):
    return pd.concat([df.drop('b', axis=1), pd.DataFrame(df['b'].tolist())], axis=1)

def jpp(df):
    return df.join(pd.DataFrame(df.pop('b').tolist()))

df = pd.concat([df]*1000, ignore_index=True)

%timeit joris1(df.copy())  # 1.33 s per loop
%timeit joris2(df.copy())  # 7.42 ms per loop
%timeit jpp(df.copy())     # 7.68 ms per loop

How can I check for Python version in a program that uses new language features?

Sets became part of the core language in Python 2.4, in order to stay backwards compatible. I did this back then, which will work for you as well:

if sys.version_info < (2, 4):
    from sets import Set as set

How to auto-indent code in the Atom editor?

I was working on some groovy code, which doesn't auto-format on save. What I did was right-click on the code pane, then chose ESLint Fix. That fixed my indents.

enter image description here

Can I embed a .png image into an html page?

I don't know for how long this post has been here. But I stumbled upon similar problem now. Hence posting the solution so that it might help others.

#!/usr/bin/env perl
use strict;
use warnings;
use utf8;

use GD::Graph::pie;
use MIME::Base64;
my @data = (['A','O','S','I'],[3,16,12,47]);

my $mygraph = GD::Graph::pie->new(200, 200);
my $myimage = $mygraph->plot(\@data)->png;

print <<end_html;
<html><head><title>Current Stats</title></head>
<body>
<p align="center">
<img src="data:image/png;base64,
end_html

print encode_base64($myimage);

print <<end_html;
" style="width: 888px; height: 598px; border-width: 2px; border-style: solid;" /></p>
</body>
</html>

end_html

Get: TypeError: 'dict_values' object does not support indexing when using python 3.2.3

In Python 3, dict.values() (along with dict.keys() and dict.items()) returns a view, rather than a list. See the documentation here. You therefore need to wrap your call to dict.values() in a call to list like so:

v = list(d.values())
{names[i]:v[i] for i in range(len(names))}

Is there a vr (vertical rule) in html?

There is no tag in HTML, but you can use |.

Set active tab style with AngularJS

Came here for solution .. though above solutions are working fine but found them little bit complex unnecessary. For people who still looking for a easy and neat solution, it will do the task perfectly.

<section ng-init="tab=1">
                <ul class="nav nav-tabs">
                    <li ng-class="{active: tab == 1}"><a ng-click="tab=1" href="#showitem">View Inventory</a></li>
                    <li ng-class="{active: tab == 2}"><a ng-click="tab=2" href="#additem">Add new item</a></li>
                    <li ng-class="{active: tab == 3}"><a ng-click="tab=3" href="#solditem">Sold item</a></li>
                </ul>
            </section>

How to set auto increment primary key in PostgreSQL?

Auto incrementing primary key in postgresql:

Step 1, create your table:

CREATE TABLE epictable
(
    mytable_key    serial primary key,
    moobars        VARCHAR(40) not null,
    foobars        DATE
);

Step 2, insert values into your table like this, notice that mytable_key is not specified in the first parameter list, this causes the default sequence to autoincrement.

insert into epictable(moobars,foobars) values('delicious moobars','2012-05-01')
insert into epictable(moobars,foobars) values('worldwide interblag','2012-05-02')

Step 3, select * from your table:

el@voyager$ psql -U pgadmin -d kurz_prod -c "select * from epictable"

Step 4, interpret the output:

mytable_key  |        moobars        |  foobars   
-------------+-----------------------+------------
           1 | delicious moobars     | 2012-05-01
           2 | world wide interblags | 2012-05-02
(2 rows)

Observe that mytable_key column has been auto incremented.

ProTip:

You should always be using a primary key on your table because postgresql internally uses hash table structures to increase the speed of inserts, deletes, updates and selects. If a primary key column (which is forced unique and non-null) is available, it can be depended on to provide a unique seed for the hash function. If no primary key column is available, the hash function becomes inefficient as it selects some other set of columns as a key.

Java Error: illegal start of expression

public static int [] locations={1,2,3};

public static test dot=new test();

Declare the above variables above the main method and the code compiles fine.

public static void main(String[] args){

Distinct in Linq based on only one field of the table

From what I have found, your query is mostly correct. Just change "select r" to "select r.Text" is all and that should solve the problem. This is how MSDN documented how it should work.

Ex:

    var query = (from r in table1 orderby r.Text select r.Text).distinct();

How to kill a child process after a given timeout in Bash?

# Spawn a child process:
(dosmth) & pid=$!
# in the background, sleep for 10 secs then kill that process
(sleep 10 && kill -9 $pid) &

or to get the exit codes as well:

# Spawn a child process:
(dosmth) & pid=$!
# in the background, sleep for 10 secs then kill that process
(sleep 10 && kill -9 $pid) & waiter=$!
# wait on our worker process and return the exitcode
exitcode=$(wait $pid && echo $?)
# kill the waiter subshell, if it still runs
kill -9 $waiter 2>/dev/null
# 0 if we killed the waiter, cause that means the process finished before the waiter
finished_gracefully=$?

How can I round down a number in Javascript?

Math.floor() will work, but it's very slow compared to using a bitwise OR operation:

var rounded = 34.923 | 0;
alert( rounded );
//alerts "34"

EDIT Math.floor() is not slower than using the | operator. Thanks to Jason S for checking my work.

Here's the code I used to test:

var a = [];
var time = new Date().getTime();
for( i = 0; i < 100000; i++ ) {
    //a.push( Math.random() * 100000  | 0 );
    a.push( Math.floor( Math.random() * 100000 ) );
}
var elapsed = new Date().getTime() - time;
alert( "elapsed time: " + elapsed );

How to pipe list of files returned by find command to cat to view all the files

This will print the name and contents of files-only recursively..

find . -type f -printf '\n\n%p:\n' -exec cat {} \;

Edit (Improved version): This will print the name and contents of text (ascii) files-only recursively..

find . -type f -exec grep -Iq . {} \; -print | xargs awk 'FNR==1{print FILENAME ":" $0; }'

One more attempt

find . -type f -exec grep -Iq . {} \; -printf "\n%p:" -exec cat {} \;

Best way to use PHP to encrypt and decrypt passwords?

This will only give you marginal protection. If the attacker can run arbitrary code in your application they can get at the passwords in exactly the same way your application can. You could still get some protection from some SQL injection attacks and misplaced db backups if you store a secret key in a file and use that to encrypt on the way to the db and decrypt on the way out. But you should use bindparams to completely avoid the issue of SQL injection.

If decide to encrypt, you should use some high level crypto library for this, or you will get it wrong. You'll have to get the key-setup, message padding and integrity checks correct, or all your encryption effort is of little use. GPGME is a good choice for one example. Mcrypt is too low level and you will probably get it wrong.

PHP how to get local IP of system

A reliable way to get the external IP address of the local machine would be to query the routing table, although we have no direct way to do it in PHP.

However we can get the system to do it for us by binding a UDP socket to a public address, and getting its address:

$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_connect($sock, "8.8.8.8", 53);
socket_getsockname($sock, $name); // $name passed by reference

// This is the local machine's external IP address
$localAddr = $name;

socket_connect will not cause any network traffic because it's an UDP socket.

org.hibernate.MappingException: Unknown entity

You can enable entity scan by adding below annotation on Application .java @EntityScan(basePackageClasses=YourEntityClassName.class)

Or you can set the packageToScan in your session factory. sessionFactory.setPackagesToScan(“com.all.entity”);

How to show shadow around the linearlayout in Android?

Well, this is easy to achieve .

Just build a GradientDrawable that comes from black and goes to a transparent color, than use parent relationship to place your shape close to the View that you want to have a shadow, then you just have to give any values to height or width .

Here is an example, this file have to be created inside res/drawable , I name it as shadow.xml :

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <gradient
        android:startColor="#9444"
        android:endColor="#0000"
        android:type="linear"
        android:angle="90"> <!-- Change this value to have the correct shadow angle, must be multiple from 45 -->
    </gradient>

</shape>

Place the following code above from a LinearLayout , for example, set the android:layout_width and android:layout_height to fill_parent and 2.3dp, you'll have a nice shadow effect on your LinearLayout .

<View
    android:id="@+id/shadow"
    android:layout_width="fill_parent"
    android:layout_height="2.3dp"  
    android:layout_above="@+id/id_from_your_LinearLayout" 
    android:background="@drawable/shadow">
</View>

Note 1: If you increase android:layout_height more shadow will be shown .

Note 2: Use android:layout_above="@+id/id_from_your_LinearLayout" attribute if you are placing this code inside a RelativeLayout, otherwise ignore it.

Hope it help someone.

Statically rotate font-awesome icons

If you want to rotate 45 degrees, you can use the CSS transform property:

.fa-rotate-45 {
    -ms-transform:rotate(45deg);     /* Internet Explorer 9 */
    -webkit-transform:rotate(45deg); /* Chrome, Safari, Opera */
    transform:rotate(45deg);         /* Standard syntax */
}

Serial Port (RS -232) Connection in C++

For the answer above, the default serial port is

        serialParams.BaudRate = 9600;
        serialParams.ByteSize = 8;
        serialParams.StopBits = TWOSTOPBITS;
        serialParams.Parity = NOPARITY;

Split string with string as delimiter

Try this:

for /F "tokens=1,3 delims=. " %%a in ("%string%") do (
   echo %%a
   echo %%b
)

that is, take the first and third tokens delimited by space or point...

Correct path for img on React.js

If the image is placed inside the 'src' folder, use the following:

<img src={require('../logo.png')} alt="logo" className="brand-logo"/>

Java NIO: What does IOException: Broken pipe mean?

Broken pipe simply means that the connection has failed. It is reasonable to assume that this is unrecoverable, and to then perform any required cleanup actions (closing connections, etc). I don't believe that you would ever see this simply due to the connection not yet being complete.

If you are using non-blocking mode then the SocketChannel.connect method will return false, and you will need to use the isConnectionPending and finishConnect methods to insure that the connection is complete. I would generally code based upon the expectation that things will work, and then catch exceptions to detect failure, rather than relying on frequent calls to "isConnected".

How do you show animated GIFs on a Windows Form (c#)

It doesn't when you start a long operation behind, because everything STOPS since you'Re in the same thread.

Use CSS to make a span not clickable

In response to piemesons rant against jQuery, a Vanilla JavaScript(TM) solution (tested on FF and IE):

Put this in a script tag after your markup is loaded (right before the close of the body tag) and you'll get a similar effect to the jQuery example.

a = document.getElementsByTagName('a');
for (var i = 0; i < a.length;i++) {
  a[i].getElementsByTagName('span')[1].onclick = function() { return false;};
}

This will disable the click on every 2nd span inside of an a tag. You could also check the innerHTML of each span for "description", or set an attribute or class and check that.

Convert ArrayList<String> to String[] array

I can see many answers showing how to solve problem, but only Stephen's answer is trying to explain why problem occurs so I will try to add something more on this subject. It is a story about possible reasons why Object[] toArray wasn't changed to T[] toArray where generics ware introduced to Java.


Why String[] stockArr = (String[]) stock_list.toArray(); wont work?

In Java, generic type exists at compile-time only. At runtime information about generic type (like in your case <String>) is removed and replaced with Object type (take a look at type erasure). That is why at runtime toArray() have no idea about what precise type to use to create new array, so it uses Object as safest type, because each class extends Object so it can safely store instance of any class.

Now the problem is that you can't cast instance of Object[] to String[].

Why? Take a look at this example (lets assume that class B extends A):

//B extends A
A a = new A();
B b = (B)a;

Although such code will compile, at runtime we will see thrown ClassCastException because instance held by reference a is not actually of type B (or its subtypes). Why is this problem (why this exception needs to be cast)? One of the reasons is that B could have new methods/fields which A doesn't, so it is possible that someone will try to use these new members via b reference even if held instance doesn't have (doesn't support) them. In other words we could end up trying to use data which doesn't exist, which could lead to many problems. So to prevent such situation JVM throws exception, and stop further potentially dangerous code.

You could ask now "So why aren't we stopped even earlier? Why code involving such casting is even compilable? Shouldn't compiler stop it?". Answer is: no because compiler can't know for sure what is the actual type of instance held by a reference, and there is a chance that it will hold instance of class B which will support interface of b reference. Take a look at this example:

A a = new B(); 
      //  ^------ Here reference "a" holds instance of type B
B b = (B)a;    // so now casting is safe, now JVM is sure that `b` reference can 
               // safely access all members of B class

Now lets go back to your arrays. As you see in question, we can't cast instance of Object[] array to more precise type String[] like

Object[] arr = new Object[] { "ab", "cd" };
String[] arr2 = (String[]) arr;//ClassCastException will be thrown

Here problem is a little different. Now we are sure that String[] array will not have additional fields or methods because every array support only:

  • [] operator,
  • length filed,
  • methods inherited from Object supertype,

So it is not arrays interface which is making it impossible. Problem is that Object[] array beside Strings can store any objects (for instance Integers) so it is possible that one beautiful day we will end up with trying to invoke method like strArray[i].substring(1,3) on instance of Integer which doesn't have such method.

So to make sure that this situation will never happen, in Java array references can hold only

  • instances of array of same type as reference (reference String[] strArr can hold String[])
  • instances of array of subtype (Object[] can hold String[] because String is subtype of Object),

but can't hold

  • array of supertype of type of array from reference (String[] can't hold Object[])
  • array of type which is not related to type from reference (Integer[] can't hold String[])

In other words something like this is OK

Object[] arr = new String[] { "ab", "cd" }; //OK - because
               //  ^^^^^^^^                  `arr` holds array of subtype of Object (String)
String[] arr2 = (String[]) arr; //OK - `arr2` reference will hold same array of same type as 
                                //     reference

You could say that one way to resolve this problem is to find at runtime most common type between all list elements and create array of that type, but this wont work in situations where all elements of list will be of one type derived from generic one. Take a look

//B extends A
List<A> elements = new ArrayList<A>();
elements.add(new B());
elements.add(new B());

now most common type is B, not A so toArray()

A[] arr = elements.toArray();

would return array of B class new B[]. Problem with this array is that while compiler would allow you to edit its content by adding new A() element to it, you would get ArrayStoreException because B[] array can hold only elements of class B or its subclass, to make sure that all elements will support interface of B, but instance of A may not have all methods/fields of B. So this solution is not perfect.


Best solution to this problem is explicitly tell what type of array toArray() should be returned by passing this type as method argument like

String[] arr = list.toArray(new String[list.size()]);

or

String[] arr = list.toArray(new String[0]); //if size of array is smaller then list it will be automatically adjusted.

JavaScript function to add X months to a date

Simple solution: 2678400000 is 31 day in milliseconds

var oneMonthFromNow = new Date((+new Date) + 2678400000);

Update:

Use this data to build our own function:

  • 2678400000 - 31 day
  • 2592000000 - 30 days
  • 2505600000 - 29 days
  • 2419200000 - 28 days

Understanding the difference between Object.create() and new SomeFunction()

The object used in Object.create actually forms the prototype of the new object, where as in the new Function() form the declared properties/functions do not form the prototype.

Yes, Object.create builds an object that inherits directly from the one passed as its first argument.

With constructor functions, the newly created object inherits from the constructor's prototype, e.g.:

var o = new SomeConstructor();

In the above example, o inherits directly from SomeConstructor.prototype.

There's a difference here, with Object.create you can create an object that doesn't inherit from anything, Object.create(null);, on the other hand, if you set SomeConstructor.prototype = null; the newly created object will inherit from Object.prototype.

You cannot create closures with the Object.create syntax as you would with the functional syntax. This is logical given the lexical (vs block) type scope of JavaScript.

Well, you can create closures, e.g. using property descriptors argument:

var o = Object.create({inherited: 1}, {
  foo: {
    get: (function () { // a closure
      var closured = 'foo';
      return function () {
        return closured+'bar';
      };
    })()
  }
});

o.foo; // "foobar"

Note that I'm talking about the ECMAScript 5th Edition Object.create method, not the Crockford's shim.

The method is starting to be natively implemented on latest browsers, check this compatibility table.

Display animated GIF in iOS

FLAnimatedImage is a performant open source animated GIF engine for iOS:

  • Plays multiple GIFs simultaneously with a playback speed comparable to desktop browsers
  • Honors variable frame delays
  • Behaves gracefully under memory pressure
  • Eliminates delays or blocking during the first playback loop
  • Interprets the frame delays of fast GIFs the same way modern browsers do

It's a well-tested component that I wrote to power all GIFs in Flipboard.

Node Version Manager install - nvm command not found

I had fixed this problem.

  1. touch ~/.bash_profile
  2. open ~/.bash_profile
  3. pasteexport NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion

How do I update zsh to the latest version?

If you're not using Homebrew, this is what I just did on MAC OS X Lion (10.7.5):

  1. Get the latest version of the ZSH sourcecode

  2. Untar the download into its own directory then install: ./configure && make && make test && sudo make install

  3. This installs the the zsh binary at /usr/local/bin/zsh.

  4. You can now use the shell by loading up a new terminal and executing the binary directly, but you'll want to make it your default shell...

  5. To make it your default shell you must first edit /etc/shells and add the new path. Then you can either run chsh -s /usr/local/bin/zsh or go to System Preferences > Users & Groups > right click your user > Advanced Options... > and then change "Login shell".

  6. Load up a terminal and check you're now in the correct version with echo $ZSH_VERSION. (I wasn't at first, and it took me a while to figure out I'd configured iTerm to use a specific shell instead of the system default).

Converting NSString to NSDictionary / JSON

Use this code where str is your JSON string:

NSError *err = nil;
NSArray *arr = 
 [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] 
                                 options:NSJSONReadingMutableContainers 
                                   error:&err];
// access the dictionaries
NSMutableDictionary *dict = arr[0];
for (NSMutableDictionary *dictionary in arr) {
  // do something using dictionary
}

When and why to 'return false' in JavaScript?

Often, in event handlers, such as onsubmit, returning false is a way to tell the event to not actually fire. So, say, in the onsubmit case, this would mean that the form is not submitted.

PHP - cannot use a scalar as an array warning

Also make sure that you don't declare it an array and then try to assign something else to the array like a string, float, integer. I had that problem. If you do some echos of output I was seeing what I wanted the first time, but not after another pass of the same code.

How do I use Node.js Crypto to create a HMAC-SHA1 hash?

A few years ago it was said that update() and digest() were legacy methods and the new streaming API approach was introduced. Now the docs say that either method can be used. For example:

var crypto    = require('crypto');
var text      = 'I love cupcakes';
var secret    = 'abcdeg'; //make this your secret!!
var algorithm = 'sha1';   //consider using sha256
var hash, hmac;

// Method 1 - Writing to a stream
hmac = crypto.createHmac(algorithm, secret);    
hmac.write(text); // write in to the stream
hmac.end();       // can't read from the stream until you call end()
hash = hmac.read().toString('hex');    // read out hmac digest
console.log("Method 1: ", hash);

// Method 2 - Using update and digest:
hmac = crypto.createHmac(algorithm, secret);
hmac.update(text);
hash = hmac.digest('hex');
console.log("Method 2: ", hash);

Tested on node v6.2.2 and v7.7.2

See https://nodejs.org/api/crypto.html#crypto_class_hmac. Gives more examples for using the streaming approach.

Clear form after submission with jQuery

Better way to reset your form with jQuery is Simply trigger a reset event on your form.

$("#btn1").click(function () {
        $("form").trigger("reset");
    });

How to get back Lost phpMyAdmin Password, XAMPP

You want to edit this file: "\xampp\phpMyAdmin\config.inc.php"

change this line:

$cfg['Servers'][$i]['password'] = 'WhateverPassword';

to whatever your password is. If you don't remember your password, then run this command in the Shell:

mysqladmin.exe -u root password WhateverPassword

where 'WhateverPassword' is your new password.

Pass props in Link react-router

Route:

<Route state={this.state} exact path="/customers/:id" render={(props) => <PageCustomer {...props} state={this.state} />} />

And then can access params in your PageCustomer component like this: this.props.match.params.id.

For example an api call in PageCustomer component:

axios({
   method: 'get',
   url: '/api/customers/' + this.props.match.params.id,
   data: {},
   headers: {'X-Requested-With': 'XMLHttpRequest'}
 })

MySQL WHERE: how to write "!=" or "not equals"?

The != operator most certainly does exist! It is an alias for the standard <> operator.

Perhaps your fields are not actually empty strings, but instead NULL?

To compare to NULL you can use IS NULL or IS NOT NULL or the null safe equals operator <=>.

Is it possible to focus on a <div> using JavaScript focus() function?

You can use tabindex

<div tabindex="-1"  id="tries"></div>

The tabindex value can allow for some interesting behaviour.

  • If given a value of "-1", the element can't be tabbed to but focus can be given to the element programmatically (using element.focus()).
  • If given a value of 0, the element can be focused via the keyboard and falls into the tabbing flow of the document. Values greater than 0 create a priority level with 1 being the most important.

jQuery removing '-' character from string

$mylabel.text( $mylabel.text().replace('-', '') );

Since text() gets the value, and text( "someValue" ) sets the value, you just place one inside the other.

Would be the equivalent of doing:

var newValue = $mylabel.text().replace('-', '');
$mylabel.text( newValue );

EDIT:

I hope I understood the question correctly. I'm assuming $mylabel is referencing a DOM element in a jQuery object, and the string is in the content of the element.

If the string is in some other variable not part of the DOM, then you would likely want to call the .replace() function against that variable before you insert it into the DOM.

Like this:

var someVariable = "-123456";
$mylabel.text( someVariable.replace('-', '') );

or a more verbose version:

var someVariable = "-123456";
someVariable = someVariable.replace('-', '');
$mylabel.text( someVariable );

Push existing project into Github

As of 7/29/2019, Github presents users with the instructions for accomplishing this task when a repo is created, offering several options:

create a new repository on the command line

git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/user/repo.git
git push -u origin master

push an existing repository from the command line

git remote add origin https://github.com/user/repo.git
git push -u origin master

import code from another repository

press import button to initialize process.

For the visual learners out there:

enter image description here

is there any PHP function for open page in new tab

This is a trick,

function OpenInNewTab(url) {

  var win = window.open(url, '_blank');
  win.focus();
}

In most cases, this should happen directly in the onclick handler for the link to prevent pop-up blockers, and the default "new window" behavior. You could do it this way, or by adding an event listener to your DOM object.

<div onclick="OpenInNewTab();">Something To Click On</div>