Programs & Examples On #Continuous

A random variable X is called continuous if its set of possible values is uncountable, and the chance that it takes any particular value is zero (P(X=x)=0 for every real number x). A random variable is continuous if and only if its cumulative probability distribution function is a continuous function.

Splitting a continuous variable into equal sized groups

try this:

split(das, cut(das$anim, 3))

if you want to split based on the value of wt, then

library(Hmisc) # cut2
split(das, cut2(das$wt, g=3))

anyway, you can do that by combining cut, cut2 and split.

UPDATED

if you want a group index as an additional column, then

das$group <- cut(das$anim, 3)

if the column should be index like 1, 2, ..., then

das$group <- as.numeric(cut(das$anim, 3))

UPDATED AGAIN

try this:

> das$wt2 <- as.numeric(cut2(das$wt, g=3))
> das
   anim    wt wt2
1     1 181.0   1
2     2 179.0   1
3     3 180.5   1
4     4 201.0   2
5     5 201.5   2
6     6 245.0   2
7     7 246.4   3
8     8 189.3   1
9     9 301.0   3
10   10 354.0   3
11   11 369.0   3
12   12 205.0   2
13   13 199.0   1
14   14 394.0   3
15   15 231.3   2

Jenkins not executing jobs (pending - waiting for next executor)

In my case, I had the following set in my JenkinsFile

node('node'){ ... }

There was no node called 'node', only master (the value had been left in there after following some basic tutorials). Changing the value to 'master' got the build working.

How to define an empty object in PHP

I want to point out that in PHP there is no such thing like empty object in sense:

$obj = new stdClass();
var_dump(empty($obj)); // bool(false)

but of course $obj will be empty.

On other hand empty array mean empty in both cases

$arr = array();
var_dump(empty($arr));

Quote from changelog function empty

Objects with no properties are no longer considered empty.

Adding attribute in jQuery

This could be more helpfull....

$("element").prop("id", "modifiedId");
//for boolean
$("element").prop("disabled", true);
//also you can remove attribute
$('#someid').removeProp('disabled');

How to extract the decimal part from a floating point number in C?

Try this:

int main() {
  double num = 23.345;
  int intpart = (int)num;
  double decpart = num - intpart;
  printf("Num = %f, intpart = %d, decpart = %f\n", num, intpart, decpart);
}

For me, it produces:

Num = 23.345000, intpart = 23, decpart = 0.345000

Which appears to be what you're asking for.

What's the difference between the atomic and nonatomic attributes?

To simplify the entire confusion, let us understand mutex lock.

Mutex lock, as per the name, locks the mutability of the object. So if the object is accessed by a class, no other class can access the same object.

In iOS, @sychronise also provides the mutex lock .Now it serves in FIFO mode and ensures the flow is not affected by two classes sharing the same instance. However, if the task is on main thread, avoid accessing object using atomic properties as it may hold your UI and degrade the performance.

Making an svg image object clickable with onclick, avoiding absolute positioning

You could use following code:

<style>
    .svgwrapper {
        position: relative;
    }
    .svgwrapper {
        position: absolute;
        z-index: -1;
    }
</style>

<div class="svgwrapper" onClick="function();">
    <object src="blah" />
</div>

b3ng0 wrote similar code but it does not work. z-index of parent must be auto.

Laravel Request::all() Should Not Be Called Statically

also it happens when you import following library to api.php file. this happens by some IDE's suggestion to import it for not finding the Route Class.

just remove it and everything going to work fine.

use Illuminate\Routing\Route;

update:

seems if you add this library it wont lead to error

use Illuminate\Support\Facades\Route;

Powershell folder size of folders without listing Subdirectories

You need to get the total contents size of each directory recursively to output. Also, you need to specify that the contents you're grabbing to measure are not directories, or you risk errors (as directories do not have a Length parameter).

Here's your script modified for the output you're looking for:

$colItems = Get-ChildItem $startFolder | Where-Object {$_.PSIsContainer -eq $true} | Sort-Object
foreach ($i in $colItems)
{
    $subFolderItems = Get-ChildItem $i.FullName -recurse -force | Where-Object {$_.PSIsContainer -eq $false} | Measure-Object -property Length -sum | Select-Object Sum
    $i.FullName + " -- " + "{0:N2}" -f ($subFolderItems.sum / 1MB) + " MB"
}

How to create an Array, ArrayList, Stack and Queue in Java?

Just a small correction to the first answer in this thread.

Even for Stack, you need to create new object with generics if you are using Stack from java util packages.

Right usage:
    Stack<Integer> s = new Stack<Integer>();
    Stack<String> s1 = new Stack<String>();

    s.push(7);
    s.push(50);

    s1.push("string");
    s1.push("stack");

if used otherwise, as mentioned in above post, which is:

    /*
    Stack myStack = new Stack();
    // add any type of elements (String, int, etc..)
    myStack.push("Hello");
    myStack.push(1);
    */

Although this code works fine, has unsafe or unchecked operations which results in error.

Get model's fields in Django

Another way is add functions to the model and when you want to override the date you can call the function.

class MyModel(models.Model):
    name = models.CharField(max_length=256)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    def set_created_date(self, created_date):
        field = self._meta.get_field('created')
        field.auto_now_add = False
        self.created = created_date

    def set_modified_date(self, modified_date):
        field = self._meta.get_field('modified')
        field.auto_now = False
        self.modified = modified_date

my_model = MyModel(name='test')
my_model.set_modified_date(new_date)
my_model.set_created_date(new_date)
my_model.save()

mysql data directory location

If you install MySQL via homebrew on MacOS, you might need to delete your old data directory /usr/local/var/mysql. Otherwise, it will fail during the initialization process with the following error:

==> /usr/local/Cellar/mysql/8.0.16/bin/mysqld --initialize-insecure --user=hohoho --basedir=/usr/local/Cellar/mysql/8.0.16 --datadir=/usr/local/var/mysql --tmpdir=/tmp
2019-07-17T16:30:51.828887Z 0 [System] [MY-013169] [Server] /usr/local/Cellar/mysql/8.0.16/bin/mysqld (mysqld 8.0.16) initializing of server in progress as process 93487
2019-07-17T16:30:51.830375Z 0 [ERROR] [MY-010457] [Server] --initialize specified but the data directory has files in it. Aborting.
2019-07-17T16:30:51.830381Z 0 [ERROR] [MY-013236] [Server] Newly created data directory /usr/local/var/mysql/ is unusable. You can safely remove it.
2019-07-17T16:30:51.830410Z 0 [ERROR] [MY-010119] [Server] Aborting
2019-07-17T16:30:51.830540Z 0 [System] [MY-010910] [Server] /usr/local/Cellar/mysql/8.0.16/bin/mysqld: Shutdown complete (mysqld 8.0.16)  Homebrew.

Transport endpoint is not connected

Now this answer is for those lost souls that got here with this problem because they force-unmounted the drive but their hard drive is NTFS Formatted. Assuming you have ntfs-3g installed (sudo apt-get install ntfs-3g).

sudo ntfs-3g /dev/hdd /mnt/mount_point -o force

Where hdd is the hard drive in question and the "/mnt/mount_point" directory exists.

NOTES: This fixed the issue on an Ubuntu 18.04 machine using NTFS drives that had their journal files reset through sudo ntfsfix /dev/hdd and unmounted by force using sudo umount -l /mnt/mount_point

Leaving my answer here in case this fix can aid anyone!

Trying to get the average of a count resultset

You just can put your query as a subquery:

SELECT avg(count)
  FROM 
    (
    SELECT COUNT (*) AS Count
      FROM Table T
     WHERE T.Update_time =
               (SELECT MAX (B.Update_time )
                  FROM Table B
                 WHERE (B.Id = T.Id))
    GROUP BY T.Grouping
    ) as counts

Edit: I think this should be the same:

SELECT count(*) / count(distinct T.Grouping)
  FROM Table T
 WHERE T.Update_time =
           (SELECT MAX (B.Update_time)
              FROM Table B
             WHERE (B.Id = T.Id))

How to find the process id of a running Java process on Windows? And how to kill the process alone?

This is specific to Windows. I was facing the same issue where I have to kill one specific java program using taskkill. When I run the java program, tasklist was showing the same program with Image name set as java.exe. But killing it using taskkill /F java.exe will stop all other java applications other than intended one which is not required.

So I run the same java program using:

start "MyProgramName" java java-program..

Here start command will open a new window and run the java program with window's title set to MyProgramName.

Now to kill this java-program use the following taskkill command:

taskkill /fi "MyProgramName"

Your Java program will be killed only. Rest will be unaffected.

What is the difference between a symbolic link and a hard link?

Symbolic links give another name to a file, in a way similar to hard links. But a file can be deleted even if there are remaining symbolic links.

Replace transparency in PNG images with white background

this creates an image just placing the 1st with transparency on top of the 2nd

composite -gravity center ImgWithTransp.png BackgroundSameSizeOfImg.png ResultImg.png

originally found the tip on this post

Background image jumps when address bar hides iOS/Android/Mobile Chrome

The problem can be solved with a media query and some math. Here's a solution for a portait orientation:

@media (max-device-aspect-ratio: 3/4) {
  height: calc(100vw * 1.333 - 9%);
}
@media (max-device-aspect-ratio: 2/3) {
  height: calc(100vw * 1.5 - 9%);
}
@media (max-device-aspect-ratio: 10/16) {
  height: calc(100vw * 1.6 - 9%);
}
@media (max-device-aspect-ratio: 9/16) {
  height: calc(100vw * 1.778 - 9%);
}

Since vh will change when the url bar dissapears, you need to determine the height another way. Thankfully, the width of the viewport is constant and mobile devices only come in a few different aspect ratios; if you can determine the width and the aspect ratio, a little math will give you the viewport height exactly as vh should work. Here's the process

1) Create a series of media queries for aspect ratios you want to target.

  • use device-aspect-ratio instead of aspect-ratio because the latter will resize when the url bar dissapears

  • I added 'max' to the device-aspect-ratio to target any aspect ratios that happen to follow in between the most popular. THey won't be as precise, but they will be only for a minority of users and will still be pretty close to the proper vh.

  • remember the media query using horizontal/vertical , so for portait you'll need to flip the numbers

2) for each media query multiply whatever percentage of vertical height you want the element to be in vw by the reverse of the aspect ratio.

  • Since you know the width and the ratio of width to height, you just multiply the % you want (100% in your case) by the ratio of height/width.

3) You have to determine the url bar height, and then minus that from the height. I haven't found exact measurements, but I use 9% for mobile devices in landscape and that seems to work fairly well.

This isn't a very elegant solution, but the other options aren't very good either, considering they are:

  • Having your website seem buggy to the user,

  • having improperly sized elements, or

  • Using javascript for some basic styling,

The drawback is some devices may have different url bar heights or aspect ratios than the most popular. However, using this method if only a small number of devices suffer the addition/subtraction of a few pixels, that seems much better to me than everyone having a website resize when swiping.

To make it easier, I also created a SASS mixin:

@mixin vh-fix {
  @media (max-device-aspect-ratio: 3/4) {
    height: calc(100vw * 1.333 - 9%);
  }
  @media (max-device-aspect-ratio: 2/3) {
    height: calc(100vw * 1.5 - 9%);
  }
  @media (max-device-aspect-ratio: 10/16) {
    height: calc(100vw * 1.6 - 9%);
  }
  @media (max-device-aspect-ratio: 9/16) {
    height: calc(100vw * 1.778 - 9%);
  }
}

How to make clang compile to llvm IR

Did you read clang documentation ? You're probably looking for -emit-llvm.

Android Button click go to another xml page

Change your FirstyActivity to:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn_go=(Button)findViewById(R.id.YOUR_BUTTON_ID);
            btn_go.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                  Log.i("clicks","You Clicked B1");
              Intent i=new Intent(
                     MainActivity.this,
                     MainActivity2.class);
              startActivity(i);
            }
        }
    });

}

Hope it will help you.

Cross domain POST request is not sending cookie Ajax Jquery

There have been a slew of recent changes in this arena, so I thought a fresh answer would be helpful.

To have a cookie sent by the browser to another site during a request the following criteria must be met:

A lot of people find their way to this post trying to do local development against a remote endpoint, which is possible if the above criteria are met.

What is the most efficient/elegant way to parse a flat table into a tree?

Now that MySQL 8.0 supports recursive queries, we can say that all popular SQL databases support recursive queries in standard syntax.

WITH RECURSIVE MyTree AS (
    SELECT * FROM MyTable WHERE ParentId IS NULL
    UNION ALL
    SELECT m.* FROM MyTABLE AS m JOIN MyTree AS t ON m.ParentId = t.Id
)
SELECT * FROM MyTree;

I tested recursive queries in MySQL 8.0 in my presentation Recursive Query Throwdown in 2017.

Below is my original answer from 2008:


There are several ways to store tree-structured data in a relational database. What you show in your example uses two methods:

  • Adjacency List (the "parent" column) and
  • Path Enumeration (the dotted-numbers in your name column).

Another solution is called Nested Sets, and it can be stored in the same table too. Read "Trees and Hierarchies in SQL for Smarties" by Joe Celko for a lot more information on these designs.

I usually prefer a design called Closure Table (aka "Adjacency Relation") for storing tree-structured data. It requires another table, but then querying trees is pretty easy.

I cover Closure Table in my presentation Models for Hierarchical Data with SQL and PHP and in my book SQL Antipatterns: Avoiding the Pitfalls of Database Programming.

CREATE TABLE ClosureTable (
  ancestor_id   INT NOT NULL REFERENCES FlatTable(id),
  descendant_id INT NOT NULL REFERENCES FlatTable(id),
  PRIMARY KEY (ancestor_id, descendant_id)
);

Store all paths in the Closure Table, where there is a direct ancestry from one node to another. Include a row for each node to reference itself. For example, using the data set you showed in your question:

INSERT INTO ClosureTable (ancestor_id, descendant_id) VALUES
  (1,1), (1,2), (1,4), (1,6),
  (2,2), (2,4),
  (3,3), (3,5),
  (4,4),
  (5,5),
  (6,6);

Now you can get a tree starting at node 1 like this:

SELECT f.* 
FROM FlatTable f 
  JOIN ClosureTable a ON (f.id = a.descendant_id)
WHERE a.ancestor_id = 1;

The output (in MySQL client) looks like the following:

+----+
| id |
+----+
|  1 | 
|  2 | 
|  4 | 
|  6 | 
+----+

In other words, nodes 3 and 5 are excluded, because they're part of a separate hierarchy, not descending from node 1.


Re: comment from e-satis about immediate children (or immediate parent). You can add a "path_length" column to the ClosureTable to make it easier to query specifically for an immediate child or parent (or any other distance).

INSERT INTO ClosureTable (ancestor_id, descendant_id, path_length) VALUES
  (1,1,0), (1,2,1), (1,4,2), (1,6,1),
  (2,2,0), (2,4,1),
  (3,3,0), (3,5,1),
  (4,4,0),
  (5,5,0),
  (6,6,0);

Then you can add a term in your search for querying the immediate children of a given node. These are descendants whose path_length is 1.

SELECT f.* 
FROM FlatTable f 
  JOIN ClosureTable a ON (f.id = a.descendant_id)
WHERE a.ancestor_id = 1
  AND path_length = 1;

+----+
| id |
+----+
|  2 | 
|  6 | 
+----+

Re comment from @ashraf: "How about sorting the whole tree [by name]?"

Here's an example query to return all nodes that are descendants of node 1, join them to the FlatTable that contains other node attributes such as name, and sort by the name.

SELECT f.name
FROM FlatTable f 
JOIN ClosureTable a ON (f.id = a.descendant_id)
WHERE a.ancestor_id = 1
ORDER BY f.name;

Re comment from @Nate:

SELECT f.name, GROUP_CONCAT(b.ancestor_id order by b.path_length desc) AS breadcrumbs
FROM FlatTable f 
JOIN ClosureTable a ON (f.id = a.descendant_id) 
JOIN ClosureTable b ON (b.descendant_id = a.descendant_id) 
WHERE a.ancestor_id = 1 
GROUP BY a.descendant_id 
ORDER BY f.name

+------------+-------------+
| name       | breadcrumbs |
+------------+-------------+
| Node 1     | 1           |
| Node 1.1   | 1,2         |
| Node 1.1.1 | 1,2,4       |
| Node 1.2   | 1,6         |
+------------+-------------+

A user suggested an edit today. SO moderators approved the edit, but I am reversing it.

The edit suggested that the ORDER BY in the last query above should be ORDER BY b.path_length, f.name, presumably to make sure the ordering matches the hierarchy. But this doesn't work, because it would order "Node 1.1.1" after "Node 1.2".

If you want the ordering to match the hierarchy in a sensible way, that is possible, but not simply by ordering by the path length. For example, see my answer to MySQL Closure Table hierarchical database - How to pull information out in the correct order.

Populate dropdown select with array using jQuery

You can also do this:

var list = $('#items')[0]; // HTMLSelectElement
$.each(numbers, function(index, text) { 
    list.options[list.options.length] = new Option(index, text);
}); 

getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)

in activity used ContextCompat

ContextCompat.getColor(context, R.color.color_name)

in Adaper

private Context context;


context.getResources().getColor()

What's the difference between "static" and "static inline" function?

inline instructs the compiler to attempt to embed the function content into the calling code instead of executing an actual call.

For small functions that are called frequently that can make a big performance difference.

However, this is only a "hint", and the compiler may ignore it, and most compilers will try to "inline" even when the keyword is not used, as part of the optimizations, where its possible.

for example:

static int Inc(int i) {return i+1};
.... // some code
int i;
.... // some more code
for (i=0; i<999999; i = Inc(i)) {/*do something here*/};

This tight loop will perform a function call on each iteration, and the function content is actually significantly less than the code the compiler needs to put to perform the call. inline will essentially instruct the compiler to convert the code above into an equivalent of:

 int i;
 ....
 for (i=0; i<999999; i = i+1) { /* do something here */};

Skipping the actual function call and return

Obviously this is an example to show the point, not a real piece of code.

static refers to the scope. In C it means that the function/variable can only be used within the same translation unit.

Can't install APK from browser downloads

It shouldn't be HTTP headers if the file has been downloaded successfully and it's the same file that you can open from OI.

A shot in the dark, but could it be that you are not allowing installation from unknown sources, and that OI is somehow bypassing that?

Settings > Applications > Unknown sources...

Edit

Answer extracted from comments which worked. Ensure the Content-Type is set to application/vnd.android.package-archive

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

In my case use VS 2013, and It's not support MVC 3 natively (even of you change ./Views/web.config): https://stackoverflow.com/a/28155567/1536197

How to make an unaware datetime timezone aware in python

In the format of unutbu's answer; I made a utility module that handles things like this, with more intuitive syntax. Can be installed with pip.

import datetime
import saturn

unaware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0)
now_aware = saturn.fix_naive(unaware)

now_aware_madrid = saturn.fix_naive(unaware, 'Europe/Madrid')

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

The keypress event might be different across browsers.

I created a Jsfiddle to compare keyboard events (using the JQuery shortcuts) on Chrome and Firefox. Depending on the browser you're using a keypress event will be triggered or not -- backspace will trigger keydown/keypress/keyup on Firefox but only keydown/keyup on Chrome.

Single keyclick events triggered

on Chrome

  • keydown/keypress/keyup when browser registers a keyboard input (keypress is fired)

  • keydown/keyup if no keyboard input (tested with alt, shift, backspace, arrow keys)

  • keydown only for tab?

on Firefox

  • keydown/keypress/keyup when browser registers a keyboard input but also for backspace, arrow keys, tab (so here keypress is fired even with no input)

  • keydown/keyup for alt, shift


This shouldn't be surprising because according to https://api.jquery.com/keypress/:

Note: as the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.

The use of the keypress event type is deprecated by W3C (http://www.w3.org/TR/DOM-Level-3-Events/#event-type-keypress)

The keypress event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type. When in editing contexts, authors can subscribe to the beforeinput event instead.


Finally, to answer your question, you should use keyup or keydown to detect a backspace across Firefox and Chrome.


Try it out on here:

_x000D_
_x000D_
$(".inputTxt").bind("keypress keyup keydown", function (event) {_x000D_
    var evtType = event.type;_x000D_
    var eWhich = event.which;_x000D_
    var echarCode = event.charCode;_x000D_
    var ekeyCode = event.keyCode;_x000D_
_x000D_
    switch (evtType) {_x000D_
        case 'keypress':_x000D_
            $("#log").html($("#log").html() + "<b>" + evtType + "</b>" + " keycode: " + ekeyCode + " charcode: " + echarCode + " which: " + eWhich + "<br>");_x000D_
            break;_x000D_
        case 'keyup':_x000D_
            $("#log").html($("#log").html() + "<b>" + evtType + "</b>" + " keycode: " + ekeyCode + " charcode: " + echarCode + " which: " + eWhich + "<p>");_x000D_
            break;_x000D_
        case 'keydown':_x000D_
            $("#log").html($("#log").html() + "<b>" + evtType + "</b>" + " keycode: " + ekeyCode + " charcode: " + echarCode + " which: " + eWhich + "<br>");_x000D_
            break;_x000D_
        default:_x000D_
            break;_x000D_
    }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<input class="inputTxt" type="text" />_x000D_
<div id="log"></div>
_x000D_
_x000D_
_x000D_

Storyboard doesn't contain a view controller with identifier

Cleaning all things and closing Xcode doesn't solved the issue for me.

I had to delete the viewController and create a new one with new identifier.

How to SUM two fields within an SQL query

Just a reminder on adding columns. If one of the values is NULL the total of those columns becomes NULL. Thus why some posters have recommended coalesce with the second parameter being 0

I know this was an older posting but wanted to add this for completeness.

java build path problems

Here's a good discussion on this:

Basically you should

  1. Download and install the 1.5 JDK. (download link)
  2. In Eclipse, Go to Window ? Preferences ? Java ? Installed JREs.
  3. Add the 1.5 JDK to the list.
  4. Select 1.5 as Compiler Compliance Level.

get string value from HashMap depending on key name

Suppose you declared HashMap as :-

HashMap<Character,Integer> hs = new HashMap<>();

Then,key in map is of type Character data type and value of int type.Now,to get value corresponding to key irrespective of type of key,value type, syntax is :-

    char temp = 'a';
    if(hs.containsKey(temp)){
`       int val = hs.get(temp); //val is the value corresponding to key temp
    }

So, according to your question you want to get string value corresponding to a key.For this, just declare HashMap as HashMap<"datatype of key","datatype of value" hs = new HashMap<>(); Using this will make your code cleaner and also you don't have to convert the result of hs.get("my_code") to string as by default it returns value of string if at entry time one has kept value as a string.

Initialize a string variable in Python: "" or None?

Since both None and "" are false, you can do both. See 6.1. Truth Value Testing.

Edit

To answer the question in your edit: No, you can assign a different type.

>>> a = ""
>>> type(a)
<type 'str'>
>>> a = 1
>>> type(a)
<type 'int'>

Javascript replace with reference to matched group?

"hello _there_".replace(/_(.*?)_/, function(a, b){
    return '<div>' + b + '</div>';
})

Oh, or you could also:

"hello _there_".replace(/_(.*?)_/, "<div>$1</div>")

EDIT by Liran H: For six other people including myself, $1 did not work, whereas \1 did.

Using "word-wrap: break-word" within a table

table-layout: fixed will get force the cells to fit the table (and not the other way around), e.g.:

<table style="border: 1px solid black; width: 100%; word-wrap:break-word;
              table-layout: fixed;">
  <tr>
    <td>
        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
    </td>
  </tr>
</table>

What good are SQL Server schemas?

At an ORACLE shop I worked at for many years, schemas were used to encapsulate procedures (and packages) that applied to different front-end applications. A different 'API' schema for each application often made sense as the use cases, users, and system requirements were quite different. For example, one 'API' schema was for a development/configuration application only to be used by developers. Another 'API' schema was for accessing the client data via views and procedures (searches). Another 'API' schema encapsulated code that was used for synchronizing development/configuration and client data with an application that had it's own database. Some of these 'API' schemas, under the covers, would still share common procedures and functions with eachother (via other 'COMMON' schemas) where it made sense.

I will say that not having a schema is probably not the end of the world, though it can be very helpful. Really, it is the lack of packages in SQL Server that really creates problems in my mind... but that is a different topic.

How to insert a column in a specific position in oracle without dropping and recreating the table?

Although this is somewhat old I would like to add a slightly improved version that really changes column order. Here are the steps (assuming we have a table TAB1 with columns COL1, COL2, COL3):

  1. Add new column to table TAB1:
alter table TAB1 add (NEW_COL number);
  1. "Copy" table to temp name while changing the column order AND rename the new column:
create table tempTAB1 as select NEW_COL as COL0, COL1, COL2, COL3 from TAB1;
  1. drop existing table:
drop table TAB1;
  1. rename temp tablename to just dropped tablename:
rename tempTAB1 to TAB1;

Simple JavaScript problem: onClick confirm not preventing default action

I use this, works like a charm. No need to have any functions, just inline with your link(s)

onclick="javascript:return confirm('Are you sure you want to delete this comment?')"

applying css to specific li class

The CSS you have applies color #c1c1c1 to all <a> elements.

And it also applies color #c1c1c1 to the first <li> element.

Perhaps the code you posted is missing something because I don't see any other colors being defined.

How to change maven logging level to display only warning and errors?

If you are using Logback, just put this logback-test.xml file into src/test/resources directory:

<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
</appender>
<root level="INFO">
    <appender-ref ref="STDOUT" />
</root>
</configuration>

Console app arguments, how arguments are passed to Main method

All answers are awesome and explained everything very well

but I just want to point out different way for passing args to main method

in visual studio

  1. right click on Project then choose Properties
  2. go to Debug tab then on the Start Options section provide the app with your args

like this image

Properties window

and happy knowing secrets

Count with IF condition in MySQL query

This should work:

count(if(ccc_news_comments.id = 'approved', ccc_news_comments.id, NULL))

count() only check if the value exists or not. 0 is equivalent to an existent value, so it counts one more, while NULL is like a non-existent value, so is not counted.

Select element by exact match of its content

The .first() will help here

$('p:contains("hello")').first().css('font-weight', 'bold');

What is __declspec and when do I need to use it?

Another example to illustrate the __declspec keyword:

When you are writing a Windows Kernel Driver, sometimes you want to write your own prolog/epilog code sequences using inline assembler code, so you could declare your function with the naked attribute.

__declspec( naked ) int func( formal_parameters ) {}

Or

#define Naked __declspec( naked )
Naked int func( formal_parameters ) {}

Please refer to naked (C++)

How to display an image from a path in asp.net MVC 4 and Razor view?

you can also try with this answer :

 <img src="~/Content/img/@Html.DisplayFor(model =>model.ImagePath)" style="height:200px;width:200px;"/>

HTML entity for check mark

Something like this?

if so, type the HTML &#10004;

And &#10003; gives a lighter one:

Generate an integer that is not among four billion given ones

If we assume that the range of numbers will always be 2^n (an even power of 2), then exclusive-or will work (as shown by another poster). As far as why, let's prove it:

The Theory

Given any 0 based range of integers that has 2^n elements with one element missing, you can find that missing element by simply xor-ing the known values together to yield the missing number.

The Proof

Let's look at n = 2. For n=2, we can represent 4 unique integers: 0, 1, 2, 3. They have a bit pattern of:

  • 0 - 00
  • 1 - 01
  • 2 - 10
  • 3 - 11

Now, if we look, each and every bit is set exactly twice. Therefore, since it is set an even number of times, and exclusive-or of the numbers will yield 0. If a single number is missing, the exclusive-or will yield a number that when exclusive-ored with the missing number will result in 0. Therefore, the missing number, and the resulting exclusive-ored number are exactly the same. If we remove 2, the resulting xor will be 10 (or 2).

Now, let's look at n+1. Let's call the number of times each bit is set in n, x and the number of times each bit is set in n+1 y. The value of y will be equal to y = x * 2 because there are x elements with the n+1 bit set to 0, and x elements with the n+1 bit set to 1. And since 2x will always be even, n+1 will always have each bit set an even number of times.

Therefore, since n=2 works, and n+1 works, the xor method will work for all values of n>=2.

The Algorithm For 0 Based Ranges

This is quite simple. It uses 2*n bits of memory, so for any range <= 32, 2 32 bit integers will work (ignoring any memory consumed by the file descriptor). And it makes a single pass of the file.

long supplied = 0;
long result = 0;
while (supplied = read_int_from_file()) {
    result = result ^ supplied;
}
return result;

The Algorithm For Arbitrary Based Ranges

This algorithm will work for ranges of any starting number to any ending number, as long as the total range is equal to 2^n... This basically re-bases the range to have the minimum at 0. But it does require 2 passes through the file (the first to grab the minimum, the second to compute the missing int).

long supplied = 0;
long result = 0;
long offset = INT_MAX;
while (supplied = read_int_from_file()) {
    if (supplied < offset) {
        offset = supplied;
    }
}
reset_file_pointer();
while (supplied = read_int_from_file()) {
    result = result ^ (supplied - offset);
}
return result + offset;

Arbitrary Ranges

We can apply this modified method to a set of arbitrary ranges, since all ranges will cross a power of 2^n at least once. This works only if there is a single missing bit. It takes 2 passes of an unsorted file, but it will find the single missing number every time:

long supplied = 0;
long result = 0;
long offset = INT_MAX;
long n = 0;
double temp;
while (supplied = read_int_from_file()) {
    if (supplied < offset) {
        offset = supplied;
    }
}
reset_file_pointer();
while (supplied = read_int_from_file()) {
    n++;
    result = result ^ (supplied - offset);
}
// We need to increment n one value so that we take care of the missing 
// int value
n++
while (n == 1 || 0 != (n & (n - 1))) {
    result = result ^ (n++);
}
return result + offset;

Basically, re-bases the range around 0. Then, it counts the number of unsorted values to append as it computes the exclusive-or. Then, it adds 1 to the count of unsorted values to take care of the missing value (count the missing one). Then, keep xoring the n value, incremented by 1 each time until n is a power of 2. The result is then re-based back to the original base. Done.

Here's the algorithm I tested in PHP (using an array instead of a file, but same concept):

function find($array) {
    $offset = min($array);
    $n = 0;
    $result = 0;
    foreach ($array as $value) {
        $result = $result ^ ($value - $offset);
        $n++;
    }
    $n++; // This takes care of the missing value
    while ($n == 1 || 0 != ($n & ($n - 1))) {
        $result = $result ^ ($n++);
    }
    return $result + $offset;
}

Fed in an array with any range of values (I tested including negatives) with one inside that range which is missing, it found the correct value each time.

Another Approach

Since we can use external sorting, why not just check for a gap? If we assume the file is sorted prior to the running of this algorithm:

long supplied = 0;
long last = read_int_from_file();
while (supplied = read_int_from_file()) {
    if (supplied != last + 1) {
        return last + 1;
    }
    last = supplied;
}
// The range is contiguous, so what do we do here?  Let's return last + 1:
return last + 1;

How to run single test method with phpunit?

I am late to the party though. But as personal I hate to write the whole line.

Instead, I use the following shortcuts in the .bash_profile file make sure to source .bash_profile the file after adding any new alias else it won't work.

alias pa="php artisan"
alias pu="vendor/bin/phpunit" 
alias puf="vendor/bin/phpunit --filter"

Usage:

puf function_name

puf filename

If you use Visual Studio Code you can use the following package to make your tests breeze.

Package Name: Better PHPUnit
Link: https://marketplace.visualstudio.com/items?itemName=calebporzio.better-phpunit

You can then set the keybinding in the settings. I use Command + T binding in my MAC.

Now once you place your cursor on any function and then use the key binding then it will automatically run that single test.

If you need to run the whole class then place the cursor on top of the class and then use the key binding.

If you have any other things then always tweek with the Terminal

Happy Coding!

How to hide app title in android?

You can do it programatically:

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;

public class ActivityName extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // remove title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);
    }
}

Or you can do it via your AndroidManifest.xml file:

<activity android:name=".ActivityName"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen">
</activity>

Edit: I added some lines so that you can show it in fullscreen, as it seems that's what you want.

Check if string contains only digits

how about

let isnum = /^\d+$/.test(val);

ALTER TABLE DROP COLUMN failed because one or more objects access this column

I had the same problem and this was the script that worked for me with a table with a two part name separated by a period ".".

USE [DATABASENAME] GO ALTER TABLE [TableNamePart1].[TableNamePart2] DROP CONSTRAINT [DF__ TableNamePart1D__ColumnName__5AEE82B9] GO ALTER TABLE [TableNamePart1].[ TableNamePart1] DROP COLUMN [ColumnName] GO

C++ unordered_map using a custom class type as the key

Most basic possible copy/paste complete runnable example of using a custom class as the key for an unordered_map (basic implementation of a sparse matrix):

// UnorderedMapObjectAsKey.cpp

#include <iostream>
#include <vector>
#include <unordered_map>

struct Pos
{
  int row;
  int col;

  Pos() { }
  Pos(int row, int col)
  {
    this->row = row;
    this->col = col;
  }

  bool operator==(const Pos& otherPos) const
  {
    if (this->row == otherPos.row && this->col == otherPos.col) return true;
    else return false;
  }

  struct HashFunction
  {
    size_t operator()(const Pos& pos) const
    {
      size_t rowHash = std::hash<int>()(pos.row);
      size_t colHash = std::hash<int>()(pos.col) << 1;
      return rowHash ^ colHash;
    }
  };
};

int main(void)
{
  std::unordered_map<Pos, int, Pos::HashFunction> umap;

  // at row 1, col 2, set value to 5
  umap[Pos(1, 2)] = 5;

  // at row 3, col 4, set value to 10
  umap[Pos(3, 4)] = 10;

  // print the umap
  std::cout << "\n";
  for (auto& element : umap)
  {
    std::cout << "( " << element.first.row << ", " << element.first.col << " ) = " << element.second << "\n";
  }
  std::cout << "\n";

  return 0;
}

In Matplotlib, what does the argument mean in fig.add_subplot(111)?

The answer from Constantin is spot on but for more background this behavior is inherited from Matlab.

The Matlab behavior is explained in the Figure Setup - Displaying Multiple Plots per Figure section of the Matlab documentation.

subplot(m,n,i) breaks the figure window into an m-by-n matrix of small subplots and selects the ithe subplot for the current plot. The plots are numbered along the top row of the figure window, then the second row, and so forth.

Sending "User-agent" using Requests library in Python

The user-agent should be specified as a field in the header.

Here is a list of HTTP header fields, and you'd probably be interested in request-specific fields, which includes User-Agent.

If you're using requests v2.13 and newer

The simplest way to do what you want is to create a dictionary and specify your headers directly, like so:

import requests

url = 'SOME URL'

headers = {
    'User-Agent': 'My User Agent 1.0',
    'From': '[email protected]'  # This is another valid field
}

response = requests.get(url, headers=headers)

If you're using requests v2.12.x and older

Older versions of requests clobbered default headers, so you'd want to do the following to preserve default headers and then add your own to them.

import requests

url = 'SOME URL'

# Get a copy of the default headers that requests would use
headers = requests.utils.default_headers()

# Update the headers with your custom ones
# You don't have to worry about case-sensitivity with
# the dictionary keys, because default_headers uses a custom
# CaseInsensitiveDict implementation within requests' source code.
headers.update(
    {
        'User-Agent': 'My User Agent 1.0',
    }
)

response = requests.get(url, headers=headers)

How may I align text to the left and text to the right in the same line?

An answer using css flex layout and justify-content

_x000D_
_x000D_
p {
  display: flex;
  justify-content: space-between;
}
_x000D_
<p>
  <span>This text is left aligned</span>
  <span>This text is right aligned</span>
</p>
_x000D_
_x000D_
_x000D_

Value cannot be null. Parameter name: source

I got this error when I had an invalid Type for an entity property.

public Type ObjectType {get;set;}

When I removed the property the error stopped occurring.

Difference between Width:100% and width:100vw?

vw and vh stand for viewport width and viewport height respectively.

The difference between using width: 100vw instead of width: 100% is that while 100% will make the element fit all the space available, the viewport width has a specific measure, in this case the width of the available screen, including the document margin.

If you set the style body { margin: 0 }, 100vw should behave the same as 100%.

Additional notes

Using vw as unit for everything in your website, including font sizes and heights, will make it so that the site is always displayed proportionally to the device's screen width regardless of it's resolution. This makes it super easy to ensure your website is displayed properly in both workstation and mobile.

You can set font-size: 1vw (or whatever size suits your project) in your body CSS and everything specified in rem units will automatically scale according to the device screen, so it's easy to port existing projects and even frameworks (such as Bootstrap) to this concept.

Convert string to number field

Within Crystal, you can do it by creating a formula that uses the ToNumber function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:

If NumericText ({field}) then ToNumber ({field}) else 0

Alternatively, you might find it easier to convert the field's datatype within the query used in the report.

How do I display a MySQL error in PHP for a long query that depends on the user input?

I use the following to turn all error reporting on for MySQLi

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

*NOTE: don't use this in a production environment.

R - Concatenate two dataframes?

you can use the function

bind_rows(a,b)

from the dplyr library

jQuery if statement to check visibility

You can use .is(':visible') to test if something is visible and .is(':hidden') to test for the opposite:

$('#offers').toggle(!$('#column-left form').is(':visible')); // or:
$('#offers').toggle($('#column-left form').is(':hidden'));

Reference:

How to access your website through LAN in ASP.NET

You may also need to enable the World Wide Web Service inbound firewall rule.

On Windows 7: Start -> Control Panel -> Windows Firewall -> Advanced Settings -> Inbound Rules

Find World Wide Web Services (HTTP Traffic-In) in the list and select to enable the rule. Change is pretty much immediate.

compare differences between two tables in mysql

Based on Haim's answer I created a PHP code to test and display all the differences between two databases. This will also display if a table is present in source or test databases. You have to change with your details the <> variables content.

<?php

    $User = "<DatabaseUser>";
    $Pass = "<DatabasePassword>";
    $SourceDB = "<SourceDatabase>";
    $TestDB = "<DatabaseToTest>";

    $link = new mysqli( "p:". "localhost", $User, $Pass, "" );

    if ( mysqli_connect_error() ) {

        die('Connect Error ('. mysqli_connect_errno() .') '. mysqli_connect_error());

    }

    mysqli_set_charset( $link, "utf8" );
    mb_language( "uni" );
    mb_internal_encoding( "UTF-8" );

    $sQuery = 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA="'. $SourceDB .'";';

    $SourceDB_Content = query( $link, $sQuery );

    if ( !is_array( $SourceDB_Content) ) {

        echo "Table $SourceDB cannot be accessed";
        exit(0);

    }

    $sQuery = 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA="'. $TestDB .'";';

    $TestDB_Content = query( $link, $sQuery );

    if ( !is_array( $TestDB_Content) ) {

        echo "Table $TestDB cannot be accessed";
        exit(0);

    }

    $SourceDB_Tables = array();
    foreach( $SourceDB_Content as $item ) {
        $SourceDB_Tables[] = $item["TABLE_NAME"];
    }

    $TestDB_Tables = array();
    foreach( $TestDB_Content as $item ) {
        $TestDB_Tables[] = $item["TABLE_NAME"];
    }
    //var_dump( $SourceDB_Tables, $TestDB_Tables );
    $LookupTables = array_merge( $SourceDB_Tables, $TestDB_Tables );
    $NoOfDiscrepancies = 0;
    echo "

    <table border='1' width='100%'>
    <tr>
        <td>Table</td>
        <td>Found in $SourceDB (". count( $SourceDB_Tables ) .")</td>
        <td>Found in $TestDB (". count( $TestDB_Tables ) .")</td>
        <td>Test result</td>
    <tr>

    ";

    foreach( $LookupTables as $table ) {

        $FoundInSourceDB = in_array( $table, $SourceDB_Tables ) ? 1 : 0;
        $FoundInTestDB = in_array( $table, $TestDB_Tables ) ? 1 : 0;
        echo "

    <tr>
        <td>$table</td>
        <td><input type='checkbox' ". ($FoundInSourceDB == 1 ? "checked" : "") ."></td> 
        <td><input type='checkbox' ". ($FoundInTestDB == 1 ? "checked" : "") ."></td>   
        <td>". compareTables( $SourceDB, $TestDB, $table ) ."</td>  
    </tr>   
        ";

    }

    echo "

    </table>
    <br><br>
    No of discrepancies found: $NoOfDiscrepancies
    ";


    function query( $link, $q ) {

        $result = mysqli_query( $link, $q );

        $errors = mysqli_error($link);
        if ( $errors > "" ) {

            echo $errors;
            exit(0);

        }

        if( $result == false ) return false;
        else if ( $result === true ) return true;
        else {

            $rset = array();

            while ( $row = mysqli_fetch_assoc( $result ) ) {

                $rset[] = $row;

            }

            return $rset;

        }

    }

    function compareTables( $source, $test, $table ) {

        global $link;
        global $NoOfDiscrepancies;

        $sQuery = "

    SELECT column_name,ordinal_position,data_type,column_type FROM
    (
        SELECT
            column_name,ordinal_position,
            data_type,column_type,COUNT(1) rowcount
        FROM information_schema.columns
        WHERE
        (
            (table_schema='$source' AND table_name='$table') OR
            (table_schema='$test' AND table_name='$table')
        )
        AND table_name IN ('$table')
        GROUP BY
            column_name,ordinal_position,
            data_type,column_type
        HAVING COUNT(1)=1
    ) A;    

        ";

        $result = query( $link, $sQuery );

        $data = "";
        if( is_array( $result ) && count( $result ) > 0 ) {

            $NoOfDiscrepancies++;
            $data = "<table><tr><td>column_name</td><td>ordinal_position</td><td>data_type</td><td>column_type</td></tr>";

            foreach( $result as $item ) {

                $data .= "<tr><td>". $item["column_name"] ."</td><td>". $item["ordinal_position"] ."</td><td>". $item["data_type"] ."</td><td>". $item["column_type"] ."</td></tr>";

            }

            $data .= "</table>";

            return $data;

        }
        else {

            return "Checked but no discrepancies found!";

        }

    }

?>

Excel formula to get cell color

As commented, just in case the link I posted there broke, try this:

Add a Name(any valid name) in Excel's Name Manager under Formula tab in the Ribbon.
Then assign a formula using GET.CELL function.

=GET.CELL(63,INDIRECT("rc",FALSE))

63 stands for backcolor.
Let's say we name it Background so in any cell with color type:

=Background

Result:
enter image description here

Notice that Cells A2, A3 and A4 returns 3, 4, and 5 respectively which equates to the cells background color index. HTH.
BTW, here's a link on Excel's Color Index

How to create/make rounded corner buttons in WPF?

You can try this...........

 <Border BorderBrush="Black" Name="MyBorder"  
            Height="78" 
            Background="Red" 
            Width="74" 
            CornerRadius="3">
        <Button Width="{Binding MyBorder.Width}" 
                Height="{Binding MyBorder.Height}" 
                Content="Hi" Background="Red"/>
    </Border>

ImportError: No module named _ssl

Since --with-ssl is not recognized anymore I just installed the libssl-dev. For debian based systems:

sudo apt-get install libssl-dev 

For CentOS and RHEL

sudo yum install openssl-devel

To restart the make first clean up by:

make clean

Then start again and execute the following commands one after the other:

./configure
make
make test
make install

For further information on OpenSSL visit the Ubuntu Help Page on OpenSSL.

Making a Bootstrap table column fit to content

Kind of an old question, but I arrived here looking for this. I wanted the table to be as small as possible, fitting to it's contents. The solution was to simply set the table width to an arbitrary small number (1px for example). I even created a CSS class to handle it:

.table-fit {
    width: 1px;
}

And use it like so:

<table class="table table-fit">

Example: JSFiddle

Magento - Retrieve products with a specific attribute value

To Get TEXT attributes added from admin to front end on product listing page.

Thanks Anita Mourya

I have found there is two methods. Let say product attribute called "na_author" is added from backend as text field.

METHOD 1

on list.phtml

<?php $i=0; foreach ($_productCollection as $_product): ?>

FOR EACH PRODUCT LOAD BY SKU AND GET ATTRIBUTE INSIDE FOREACH

<?php
$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$_product->getSku());
$author = $product['na_author'];
?>

<?php
if($author!=""){echo "<br /><span class='home_book_author'>By ".$author ."</span>";} else{echo "";}
?>

METHOD 2

Mage/Catalog/Block/Product/List.phtml OVER RIDE and set in 'local folder'

i.e. Copy From

Mage/Catalog/Block/Product/List.phtml

and PASTE TO

app/code/local/Mage/Catalog/Block/Product/List.phtml

change the function by adding 2 lines shown in bold below.

protected function _getProductCollection()
{
       if (is_null($this->_productCollection)) {
           $layer = Mage::getSingleton('catalog/layer');
           /* @var $layer Mage_Catalog_Model_Layer */
           if ($this->getShowRootCategory()) {
               $this->setCategoryId(Mage::app()->getStore()->getRootCategoryId());
           }

           // if this is a product view page
           if (Mage::registry('product')) {
               // get collection of categories this product is associated with
               $categories = Mage::registry('product')->getCategoryCollection()
                   ->setPage(1, 1)
                   ->load();
               // if the product is associated with any category
               if ($categories->count()) {
                   // show products from this category
                   $this->setCategoryId(current($categories->getIterator()));
               }
           }

           $origCategory = null;
           if ($this->getCategoryId()) {
               $category = Mage::getModel('catalog/category')->load($this->getCategoryId());

               if ($category->getId()) {
                   $origCategory = $layer->getCurrentCategory();
                   $layer->setCurrentCategory($category);
               }
           }
           $this->_productCollection = $layer->getProductCollection();

           $this->prepareSortableFieldsByCategory($layer->getCurrentCategory());

           if ($origCategory) {
               $layer->setCurrentCategory($origCategory);
           }
       }
       **//CMI-PK added na_author to filter on product listing page//
       $this->_productCollection->addAttributeToSelect('na_author');**
       return $this->_productCollection;

}

and you will be happy to see it....!!

java comparator, how to sort by integer?

public class DogAgeComparator implements Comparator<Dog> {
    public int compare(Dog o1, Dog o2) {
        return Integer.compare(o1.getAge(), o2.getId());
    }
}

How to send a "multipart/form-data" with requests in python?

Here is the simple code snippet to upload a single file with additional parameters using requests:

url = 'https://<file_upload_url>'
fp = '/Users/jainik/Desktop/data.csv'

files = {'file': open(fp, 'rb')}
payload = {'file_id': '1234'}

response = requests.put(url, files=files, data=payload, verify=False)

Please note that you don't need to explicitly specify any content type.

NOTE: Wanted to comment on one of the above answers but could not because of low reputation so drafted a new response here.

Redirecting to a page after submitting form in HTML

You need to use the jQuery AJAX or XMLHttpRequest() for post the data to the server. After data posting you can redirect your page to another page by window.location.href.

Example:

 var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      window.location.href = 'https://website.com/my-account';
    }
  };
  xhttp.open("POST", "demo_post.asp", true);
  xhttp.send();

how to POST/Submit an Input Checkbox that is disabled?

If you're happy using JQuery then remove the disabled attribute when submitting the form:

$("form").submit(function() {
    $("input").removeAttr("disabled");
});

How to monitor SQL Server table changes by using c#?

Be careful using SqlDependency class - it has problems with memory leaks.

Just use a cross-platform, .NET 3.5, .NET Core compatible and open source solution - SqlDependencyEx. You can get notifications as well as data that was changed (you can access it through properties in notification event object). You can also tack DELETE\UPDATE\INSERT operations separately or together.

Here is an example of how easy it is to use SqlDependencyEx:

int changesReceived = 0;
using (SqlDependencyEx sqlDependency = new SqlDependencyEx(
          TEST_CONNECTION_STRING, TEST_DATABASE_NAME, TEST_TABLE_NAME)) 
{
    sqlDependency.TableChanged += (o, e) => changesReceived++;
    sqlDependency.Start();

    // Make table changes.
    MakeTableInsertDeleteChanges(changesCount);

    // Wait a little bit to receive all changes.
    Thread.Sleep(1000);
}

Assert.AreEqual(changesCount, changesReceived);

Please follow the links for details. This component was tested in many enterprise-level applications and proven to be reliable. Hope this helps.

AngularJS resource promise

If you want to use asynchronous method you need to use callback function by $promise, here is example:

var Regions = $resource('mocks/regions.json');

$scope.regions = Regions.query();
$scope.regions.$promise.then(function (result) {
    $scope.regions = result;
});

How can I send and receive WebSocket messages on the server side?

C# Implementation

Browser -> Server

    private String DecodeMessage(Byte[] bytes)
    {
        String incomingData = String.Empty;
        Byte secondByte = bytes[1];
        Int32 dataLength = secondByte & 127;
        Int32 indexFirstMask = 2;
        if (dataLength == 126)
            indexFirstMask = 4;
        else if (dataLength == 127)
            indexFirstMask = 10;

        IEnumerable<Byte> keys = bytes.Skip(indexFirstMask).Take(4);
        Int32 indexFirstDataByte = indexFirstMask + 4;

        Byte[] decoded = new Byte[bytes.Length - indexFirstDataByte];
        for (Int32 i = indexFirstDataByte, j = 0; i < bytes.Length; i++, j++)
        {
            decoded[j] = (Byte)(bytes[i] ^ keys.ElementAt(j % 4));
        }

        return incomingData = Encoding.UTF8.GetString(decoded, 0, decoded.Length);
    }

Server -> Browser

    private static Byte[] EncodeMessageToSend(String message)
    {
        Byte[] response;
        Byte[] bytesRaw = Encoding.UTF8.GetBytes(message);
        Byte[] frame = new Byte[10];

        Int32 indexStartRawData = -1;
        Int32 length = bytesRaw.Length;

        frame[0] = (Byte)129;
        if (length <= 125)
        {
            frame[1] = (Byte)length;
            indexStartRawData = 2;
        }
        else if (length >= 126 && length <= 65535)
        {
            frame[1] = (Byte)126;
            frame[2] = (Byte)((length >> 8) & 255);
            frame[3] = (Byte)(length & 255);
            indexStartRawData = 4;
        }
        else
        {
            frame[1] = (Byte)127;
            frame[2] = (Byte)((length >> 56) & 255);
            frame[3] = (Byte)((length >> 48) & 255);
            frame[4] = (Byte)((length >> 40) & 255);
            frame[5] = (Byte)((length >> 32) & 255);
            frame[6] = (Byte)((length >> 24) & 255);
            frame[7] = (Byte)((length >> 16) & 255);
            frame[8] = (Byte)((length >> 8) & 255);
            frame[9] = (Byte)(length & 255);

            indexStartRawData = 10;
        }

        response = new Byte[indexStartRawData + length];

        Int32 i, reponseIdx = 0;

        //Add the frame bytes to the reponse
        for (i = 0; i < indexStartRawData; i++)
        {
            response[reponseIdx] = frame[i];
            reponseIdx++;
        }

        //Add the data bytes to the response
        for (i = 0; i < length; i++)
        {
            response[reponseIdx] = bytesRaw[i];
            reponseIdx++;
        }

        return response;
    }

How to access Spring MVC model object in javascript file?

JavaScript is run on the client side. Your model does not exist on the client side, it only exists on the server side while you are rendering your .jsp.

If you want data from the model to be available to client side code (ie. javascript), you will need to store it somewhere in the rendered page. For example, you can use your Jsp to write JavaScript assigning your model to JavaScript variables.

Update:

A simple example

<%-- SomeJsp.jsp --%>
<script>var paramOne =<c:out value="${paramOne}"/></script>

Sound effects in JavaScript / HTML5

You can always try AudioContext it has limited support but it's a part of the web audio api working draft. It might be worth it if you are planing to release something in the future. And if you are only programing for chrome and Firefox you're golden.

Angular2 RC6: '<component> is not a known element'

In your planner component, you must be missing import HeaderAreaComponent like this-

import { HeaderAreaComponent } from '../header-area.component'; 
//change path according your project

Also, make sure - All the components and pipes must be declared via an NgModule.

See if this helps.

What is the meaning of <> in mysql query?

<> means not equal to, != also means not equal to.

Documentation

Log4j output not displayed in Eclipse console

Configuring with BasicConfigurator.configure(); sets up a basic console appender set at debug. A project with the setup above and no other code (except for a test) should produce three lines of logging in the console. I cannot say anything else than "it works for me".

Have you tried creating an empty project with just log4j and junit, with only the code above and ran it?

Also, in order to get the @Beforemethod running:

@Test
public void testname() throws Exception {
    assertTrue(true);
}

EDIT:

If you run more than one test at one time, each of them will call init before running.

In this case, if you had two tests, the first would have one logger and the second test would call init again, making it log twice (try it) - you should get 9 lines of logging in console with two tests.

You might want to use a static init method annotated with @BeforeClass to avoid this. Though this also happens across files, you might want to have a look at documentation on TestSuites in JUnit 4. And/or call BasicConfigurator.resetConfiguration(); in an @AfterClass annotated class, to remove all loggers after each test class / test suite.

Also, the root logger is reused, so that if you set the root logger's level in a test method that runs early, it will keep this setting for all other tests that are run later, even if they are in different files. (will not happen when resetting configuration).

Testcase - this will cause 9 lines of logging:

import static org.junit.Assert.assertTrue;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;

public class SampleTest
{
   private static final Logger LOGGER = Logger.getLogger(SampleTest.class);

   @Before
   public void init() throws Exception
   {
       // Log4J junit configuration.
       BasicConfigurator.configure();
   }

   @Test
    public void testOne() throws Exception {
       LOGGER.info("INFO TEST");
       LOGGER.debug("DEBUG TEST");
       LOGGER.error("ERROR TEST");

       assertTrue(true);
    }

   @Test
   public void testTwo() throws Exception {
       LOGGER.info("INFO TEST");
       LOGGER.debug("DEBUG TEST");
       LOGGER.error("ERROR TEST");

       assertTrue(true);
   }
}

Changing the init method reduces to the excepted six lines:

@BeforeClass
public static void init() throws Exception
{
    // Log4J junit configuration.
    BasicConfigurator.configure();
}

Your problem is probably caused in some other test class or test suite where the logging level of the root logger is set to ERROR, and not reset.

You could also test this out by resetting in the @BeforeClass method, before setting logging up.

Be advised that these changes might break expected logging for other test cases until it is fixed at all places. I suggest trying out how this works in a separate workspace/project to get a feel for how it works.

How do I reflect over the members of dynamic object?

In the case of ExpandoObject, the ExpandoObject class actually implements IDictionary<string, object> for its properties, so the solution is as trivial as casting:

IDictionary<string, object> propertyValues = (IDictionary<string, object>)s;

Note that this will not work for general dynamic objects. In these cases you will need to drop down to the DLR via IDynamicMetaObjectProvider.

Stop mouse event propagation

Adding false after function will stop event propagation

<a (click)="foo(); false">click with stop propagation</a>

Check if element is visible on screen

--- Shameless plug ---
I have added this function to a library I created vanillajs-browser-helpers: https://github.com/Tokimon/vanillajs-browser-helpers/blob/master/inView.js
-------------------------------

Well BenM stated, you need to detect the height of the viewport + the scroll position to match up with your top position. The function you are using is ok and does the job, though its a bit more complex than it needs to be.

If you don't use jQuery then the script would be something like this:

function posY(elm) {
    var test = elm, top = 0;

    while(!!test && test.tagName.toLowerCase() !== "body") {
        top += test.offsetTop;
        test = test.offsetParent;
    }

    return top;
}

function viewPortHeight() {
    var de = document.documentElement;

    if(!!window.innerWidth)
    { return window.innerHeight; }
    else if( de && !isNaN(de.clientHeight) )
    { return de.clientHeight; }
    
    return 0;
}

function scrollY() {
    if( window.pageYOffset ) { return window.pageYOffset; }
    return Math.max(document.documentElement.scrollTop, document.body.scrollTop);
}

function checkvisible( elm ) {
    var vpH = viewPortHeight(), // Viewport Height
        st = scrollY(), // Scroll Top
        y = posY(elm);
    
    return (y > (vpH + st));
}

Using jQuery is a lot easier:

function checkVisible( elm, evalType ) {
    evalType = evalType || "visible";

    var vpH = $(window).height(), // Viewport Height
        st = $(window).scrollTop(), // Scroll Top
        y = $(elm).offset().top,
        elementHeight = $(elm).height();

    if (evalType === "visible") return ((y < (vpH + st)) && (y > (st - elementHeight)));
    if (evalType === "above") return ((y < (vpH + st)));
}

This even offers a second parameter. With "visible" (or no second parameter) it strictly checks whether an element is on screen. If it is set to "above" it will return true when the element in question is on or above the screen.

See in action: http://jsfiddle.net/RJX5N/2/

I hope this answers your question.

-- IMPROVED VERSION--

This is a lot shorter and should do it as well:

function checkVisible(elm) {
  var rect = elm.getBoundingClientRect();
  var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
  return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
}

with a fiddle to prove it: http://jsfiddle.net/t2L274ty/1/

And a version with threshold and mode included:

function checkVisible(elm, threshold, mode) {
  threshold = threshold || 0;
  mode = mode || 'visible';

  var rect = elm.getBoundingClientRect();
  var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
  var above = rect.bottom - threshold < 0;
  var below = rect.top - viewHeight + threshold >= 0;

  return mode === 'above' ? above : (mode === 'below' ? below : !above && !below);
}

and with a fiddle to prove it: http://jsfiddle.net/t2L274ty/2/

Does calling clone() on an array also clone its contents?

The clone is a shallow copy of the array.

This test code prints:

[1, 2] / [1, 2]
[100, 200] / [100, 2]

because the MutableInteger is shared in both arrays as objects[0] and objects2[0], but you can change the reference objects[1] independently from objects2[1].

import java.util.Arrays;                                                                                                                                 

public class CloneTest {                                                                                                                                 
    static class MutableInteger {                                                                                                                        
        int value;                                                                                                                                       
        MutableInteger(int value) {                                                                                                                      
            this.value = value;                                                                                                                          
        }                                                                                                                                                
        @Override                                                                                                                                        
        public String toString() {                                                                                                                       
            return Integer.toString(value);                                                                                                              
        }                                                                                                                                                
    }                                                                                                                                                    
    public static void main(String[] args) {                                                                                                             
        MutableInteger[] objects = new MutableInteger[] {
                new MutableInteger(1), new MutableInteger(2) };                                                
        MutableInteger[] objects2 = objects.clone();                                                                                                     
        System.out.println(Arrays.toString(objects) + " / " + 
                            Arrays.toString(objects2));                                                                
        objects[0].value = 100;                                                                                                                          
        objects[1] = new MutableInteger(200);                                                                                                            
        System.out.println(Arrays.toString(objects) + " / " + 
                            Arrays.toString(objects2));                                                               
    }                                                                                                                                                    
}                                                                                                                                                        

How to upgrade docker-compose to latest version

use this from command line: sudo curl -L "https://github.com/docker/compose/releases/download/1.22.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

Write down the latest release version

Apply executable permissions to the binary:

sudo chmod +x /usr/local/bin/docker-compose

Then test version:

$ docker-compose --version

Evaluate empty or null JSTL c tags

Here's an example of how to validate a int and a String that you pass from the Java Controller to the JSP file.

MainController.java:

@RequestMapping(value="/ImportJavaToJSP")
public ModelAndView getImportJavaToJSP() {
    ModelAndView model2= new ModelAndView("importJavaToJSPExamples");

    int someNumberValue=6;
    String someStringValue="abcdefg";
    //model2.addObject("someNumber", someNumberValue);
    model2.addObject("someString", someStringValue);

    return model2;
}

importJavaToJSPExamples.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<p>${someNumber}</p>
<c:if test="${not empty someNumber}">
    <p>someNumber is Not Empty</p>
</c:if>
<c:if test="${empty someNumber}">
    <p>someNumber is Empty</p>
</c:if>
<p>${someString}</p>
<c:if test="${not empty someString}">
    <p>someString is Not Empty</p>
</c:if>
<c:if test="${empty someString}">
    <p>someString is Empty</p>
</c:if>

Why is php not running?

One big gotcha is that PHP is disabled in user home directories by default, so if you are testing from ~/public_html it doesn't work. Check /etc/apache2/mods-enabled/php5.conf

# Running PHP scripts in user directories is disabled by default
# 
# To re-enable PHP in user directories comment the following lines
# (from <IfModule ...> to </IfModule>.) Do NOT set it to On as it
# prevents .htaccess files from disabling it.
#<IfModule mod_userdir.c>
#    <Directory /home/*/public_html>
#        php_admin_flag engine Off
#    </Directory>
#</IfModule>

Other than that installing in Ubuntu is real easy, as all the stuff you used to have to put in httpd.conf is done automatically.

Table with fixed header and fixed column on pure css

Here is another solution I have just build with css grids based on the answers in here:

https://codesandbox.io/s/sweet-resonance-m733i

Can Windows' built-in ZIP compression be scripted?

Just for clarity: GZip is not an MS-only algorithm as suggested by Guy Starbuck in his comment from August. The GZipStream in System.IO.Compression uses the Deflate algorithm, just the same as the zlib library, and many other zip tools. That class is fully interoperable with unix utilities like gzip.

The GZipStream class is not scriptable from the commandline or VBScript, to produce ZIP files, so it alone would not be an answer the original poster's request.

The free DotNetZip library does read and produce zip files, and can be scripted from VBScript or Powershell. It also includes command-line tools to produce and read/extract zip files.

Here's some code for VBScript:

dim filename 
filename = "C:\temp\ZipFile-created-from-VBScript.zip"

WScript.echo("Instantiating a ZipFile object...")
dim zip 
set zip = CreateObject("Ionic.Zip.ZipFile")

WScript.echo("using AES256 encryption...")
zip.Encryption = 3

WScript.echo("setting the password...")
zip.Password = "Very.Secret.Password!"

WScript.echo("adding a selection of files...")
zip.AddSelectedFiles("*.js")
zip.AddSelectedFiles("*.vbs")

WScript.echo("setting the save name...")
zip.Name = filename

WScript.echo("Saving...")
zip.Save()

WScript.echo("Disposing...")
zip.Dispose()

WScript.echo("Done.")

Here's some code for Powershell:

[System.Reflection.Assembly]::LoadFrom("c:\\dinoch\\bin\\Ionic.Zip.dll");

$directoryToZip = "c:\\temp";
$zipfile =  new-object Ionic.Zip.ZipFile;
$e= $zipfile.AddEntry("Readme.txt", "This is a zipfile created from within powershell.")
$e= $zipfile.AddDirectory($directoryToZip, "home")
$zipfile.Save("ZipFiles.ps1.out.zip");

In a .bat or .cmd file, you can use the zipit.exe or unzip.exe tools. Eg:

zipit NewZip.zip  -s "This is string content for an entry"  Readme.txt  src 

how to set ulimit / file descriptor on docker container the image tag is phusion/baseimage-docker

The latest docker supports setting ulimits through the command line and the API. For instance, docker run takes --ulimit <type>=<soft>:<hard> and there can be as many of these as you like. So, for your nofile, an example would be --ulimit nofile=262144:262144

Get image data url in JavaScript?

Note: This only works if the image is from the same domain as the page, or has the crossOrigin="anonymous" attribute and the server supports CORS. It's also not going to give you the original file, but a re-encoded version. If you need the result to be identical to the original, see Kaiido's answer.


You will need to create a canvas element with the correct dimensions and copy the image data with the drawImage function. Then you can use the toDataURL function to get a data: url that has the base-64 encoded image. Note that the image must be fully loaded, or you'll just get back an empty (black, transparent) image.

It would be something like this. I've never written a Greasemonkey script, so you might need to adjust the code to run in that environment.

function getBase64Image(img) {
    // Create an empty canvas element
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    // Get the data-URL formatted image
    // Firefox supports PNG and JPEG. You could check img.src to
    // guess the original format, but be aware the using "image/jpg"
    // will re-encode the image.
    var dataURL = canvas.toDataURL("image/png");

    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

Getting a JPEG-formatted image doesn't work on older versions (around 3.5) of Firefox, so if you want to support that, you'll need to check the compatibility. If the encoding is not supported, it will default to "image/png".

Check string for palindrome

Amazing how many different solutions to such a simple problem exist! Here's another one.

private static boolean palindrome(String s){
    String revS = "";
    String checkS = s.toLowerCase();
    String[] checkSArr = checkS.split("");

    for(String e : checkSArr){
        revS = e + revS;
    }

    return (checkS.equals(revS)) ? true : false;
}

Select top 10 records for each category

If you are using SQL 2005 you can do something like this...

SELECT rs.Field1,rs.Field2 
    FROM (
        SELECT Field1,Field2, Rank() 
          over (Partition BY Section
                ORDER BY RankCriteria DESC ) AS Rank
        FROM table
        ) rs WHERE Rank <= 10

If your RankCriteria has ties then you may return more than 10 rows and Matt's solution may be better for you.

How to skip to next iteration in jQuery.each() util?

jQuery.noop() can help

$(".row").each( function() {
    if (skipIteration) {
        $.noop()
    }
    else{doSomething}
});

How to use Git Revert

Use git revert like so:

git revert <insert bad commit hash here>

git revert creates a new commit with the changes that are rolled back. git reset erases your git history instead of making a new commit.

The steps after are the same as any other commit.

How to send data to COM PORT using JAVA?

An alternative to javax.comm is the rxtx library which supports more platforms than javax.comm.

How to add images in select list?

For a two color image, you can use Fontello, and import any custom glyph you want to use. Just make your image in Illustrator, save to SVG, and drop it onto the Fontello site, then download your custom font ready to import. No JavaScript!

Run CRON job everyday at specific time

Cron utility is an effective way to schedule a routine background job at a specific time and/or day on an on-going basis.

Linux Crontab Format

MIN HOUR DOM MON DOW CMD

enter image description here

Example::Scheduling a Job For a Specific Time

The basic usage of cron is to execute a job in a specific time as shown below. This will execute the Full backup shell script (full-backup) on 10th June 08:30 AM.

Please note that the time field uses 24 hours format. So, for 8 AM use 8, and for 8 PM use 20.

30 08 10 06 * /home/yourname/full-backup
  • 30 – 30th Minute
  • 08 – 08 AM
  • 10 – 10th Day
  • 06 – 6th Month (June)
  • *– Every day of the week

In your case, for 2.30PM,

30 14 * * * YOURCMD
  1. 30 – 30th Minute
  2. 14 – 2PM
  3. *– Every day
  4. *– Every month
  5. *– Every day of the week

To know more about cron, visit this website.

socket.error: [Errno 48] Address already in use

Just in case above solutions didn't work:

  1. Get the port your process is listening to:

    $ ps ax | grep python

  2. Kill the Process

    $ kill PROCESS_NAME

how to align text vertically center in android

just use like this to make anything to center

 android:layout_gravity="center"
 android:gravity="center"

updated :

android:layout_gravity="center|right"
android:gravity="center|right"

Updated : Just remove MarginBottom from your textview.. Do like this.. for your textView

<LinearLayout
        android:id="@+id/linearLayout5"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"  >

        <TextView
            android:id="@+id/textView2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center" 
            android:gravity="center|right"
            android:text="hello" 
            android:textSize="20dp" />
    </LinearLayout>

maxFileSize and acceptFileTypes in blueimp file upload plugin do not work. Why?

Had the same problem, and the blueimp guy says "maxFileSize and acceptFileTypes are only supported by the UI version" and has provided a (broken) link to incorporate the _validate and _hasError methods.

So without knowing how to incorporate those methods without messing up the script I wrote this little function. It seems to work for me.

Just add this

add: function(e, data) {
        var uploadErrors = [];
        var acceptFileTypes = /^image\/(gif|jpe?g|png)$/i;
        if(data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) {
            uploadErrors.push('Not an accepted file type');
        }
        if(data.originalFiles[0]['size'].length && data.originalFiles[0]['size'] > 5000000) {
            uploadErrors.push('Filesize is too big');
        }
        if(uploadErrors.length > 0) {
            alert(uploadErrors.join("\n"));
        } else {
            data.submit();
        }
},

at the start of the .fileupload options as shown in your code here

$(document).ready(function () {
    'use strict';

    $('#fileupload').fileupload({
        add: function(e, data) {
                var uploadErrors = [];
                var acceptFileTypes = /^image\/(gif|jpe?g|png)$/i;
                if(data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) {
                    uploadErrors.push('Not an accepted file type');
                }
                if(data.originalFiles[0]['size'].length && data.originalFiles[0]['size'] > 5000000) {
                    uploadErrors.push('Filesize is too big');
                }
                if(uploadErrors.length > 0) {
                    alert(uploadErrors.join("\n"));
                } else {
                    data.submit();
                }
        },
        dataType: 'json',
        autoUpload: false,
        // acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
        // maxFileSize: 5000000,
        done: function (e, data) {
            $.each(data.result.files, function (index, file) {
                $('<p style="color: green;">' + file.name + '<i class="elusive-ok" style="padding-left:10px;"/> - Type: ' + file.type + ' - Size: ' + file.size + ' byte</p>')
                .appendTo('#div_files');
            });
        },
        fail: function (e, data) {
            $.each(data.messages, function (index, error) {
                $('<p style="color: red;">Upload file error: ' + error + '<i class="elusive-remove" style="padding-left:10px;"/></p>')
                .appendTo('#div_files');
            });
        },
        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);

            $('#progress .bar').css('width', progress + '%');
        }
    });
});

You'll notice I added a filesize function in there as well because that will also only work in the UI version.

Updated to get past issue suggested by @lopsided: Added data.originalFiles[0]['type'].length and data.originalFiles[0]['size'].length in the queries to make sure they exist and are not empty first before testing for errors. If they don't exist, no error will be shown and it will only rely on your server side error testing.

Reset push notification settings for app

I have wondered about this in the past and came to the conclusion that it was not actually a valid test case for my code. I don't think your application code can actually tell the difference between somebody declining notifications the first time or later disabling it from the iPhone notification settings. It is true that the user experience is different but that is hidden inside the call to registerForRemoteNotificationTypes.

Calling unregisterForRemoteNotifications does not completely remove the application from the notifications settings - though it does remove the contents of the settings for that application. So this still will not cause the dialog to be presented a second time to the user the next time the app runs (at least not on v3.1.3 that I am currently testing with). But as I say above you probably should not be worrying about that.

How do I add a newline to a TextView in Android?

I just solve the same problem, put below attributes in xml

android:lines="2" android:maxLines="4" android:singleLine="false"

work.Html.fromHtml("text1 <br> text2").toString() also work.

Reloading module giving NameError: name 'reload' is not defined

For >= Python3.4:

import importlib
importlib.reload(module)

For <= Python3.3:

import imp
imp.reload(module)

For Python2.x:

Use the in-built reload() function.

reload(module)

How to execute an oracle stored procedure?

Both 'is' and 'as' are valid syntax. Output is disabled by default. Try a procedure that also enables output...

create or replace procedure temp_proc is
begin
  DBMS_OUTPUT.ENABLE(1000000);
  DBMS_OUTPUT.PUT_LINE('Test');
end;

...and call it in a PLSQL block...

begin
  temp_proc;
end;

...as SQL is non-procedural.

JAXB: how to marshall map into <key>value</key>

the code provided didn't work for me. I found another way to Map :

MapElements :

package com.cellfish.mediadb.rest.lucene;

import javax.xml.bind.annotation.XmlElement;

class MapElements
{
  @XmlElement public String  key;
  @XmlElement public Integer value;

  private MapElements() {} //Required by JAXB

  public MapElements(String key, Integer value)
  {
    this.key   = key;
    this.value = value;
  }
}

MapAdapter :

import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.annotation.adapters.XmlAdapter;

class MapAdapter extends XmlAdapter<MapElements[], Map<String, Integer>> {
    public MapElements[] marshal(Map<String, Integer> arg0) throws Exception {
        MapElements[] mapElements = new MapElements[arg0.size()];
        int i = 0;
        for (Map.Entry<String, Integer> entry : arg0.entrySet())
            mapElements[i++] = new MapElements(entry.getKey(), entry.getValue());

        return mapElements;
    }

    public Map<String, Integer> unmarshal(MapElements[] arg0) throws Exception {
        Map<String, Integer> r = new HashMap<String, Integer>();
        for (MapElements mapelement : arg0)
            r.put(mapelement.key, mapelement.value);
        return r;
    }
}

The rootElement :

import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlRootElement
public class Root {

    private Map<String, Integer> mapProperty;

    public Root() {
        mapProperty = new HashMap<String, Integer>();
    }

    @XmlJavaTypeAdapter(MapAdapter.class)
    public Map<String, Integer> getMapProperty() {
        return mapProperty;
    }

    public void setMapProperty(Map<String, Integer> map) {
        this.mapProperty = map;
    }

}

I found the code in this website : http://www.developpez.net/forums/d972324/java/general-java/xml/hashmap-jaxb/

Deep copy vs Shallow Copy

Deep copy literally performs a deep copy. It means, that if your class has some fields that are references, their values will be copied, not references themselves. If, for example you have two instances of a class, A & B with fields of reference type, and perform a deep copy, changing a value of that field in A won't affect a value in B. And vise-versa. Things are different with shallow copy, because only references are copied, therefore, changing this field in a copied object would affect the original object.

What type of a copy does a copy constructor does?

It is implementation - dependent. This means that there are no strict rules about that, you can implement it like a deep copy or shallow copy, however as far as i know it is a common practice to implement a deep copy in a copy constructor. A default copy constructor performs a shallow copy though.

Stashing only staged changes in git - is it possible?

Is it absolutely necessary to work on several bugs at once? And by "at once," I mean "having files edited for multiple bugs at the same time." Because unless you absolutely need that, I'd only work on one bug at a time in your environment. That way you can use local branches & rebase, which I find far easier than managing a complex stash/stage.

Let's say master is at commit B. Now work on bug #1.

git checkout -b bug1

Now you're on branch bug1. Make some changes, commit, wait for code review. This is local, so you're not affecting anyone else, and it should be easy enough to make a patch from git diffs.

A-B < master
   \
    C < bug1

Now you're working on bug2. Go back to master with git checkout master. Make a new branch, git checkout -b bug2. Make changes, commit, wait for code review.

    D < bug2
   /
A-B < master
   \
    C < bug1

Let's pretend that someone else commits E & F on master while you're waiting on review.

    D < bug2
   /
A-B-E-F < master
   \
    C < bug1

When your code has been approved, you can rebase it on to master with the following steps:

git checkout bug1
git rebase master
git checkout master
git merge bug1

This will result in the following:

    D < bug2
   /
A-B-E-F-C' < master, bug1

Then you can push, delete your local bug1 branch, and off you go. One bug at a time in your workspace, but with using local branches your repository can handle multiple bugs. And this avoids a complicated stage/stash dance.

Answer to ctote's question in the comments:

Well, you can go back to stashing for each bug, and only work with one bug at a time. Atleast that saves you the staging issue. But having tried this, I personally find it troublesome. Stashes are a bit messy in a git log graph. And more importantly, if you screw something up you can't revert. If you have a dirty working directory and you pop a stash, you can't "undo" that pop. It's much harder to screw up already existing commits.

So git rebase -i.

When you rebase one branch onto another, you can do it interactively (the -i flag). When you do this, you have the option to pick what you want to do with each commit. Pro Git is an awesome book which is also online in HTML format, and has a nice section on rebasing & squashing:

http://git-scm.com/book/ch6-4.html

I'll steal their example verbatim for convenience. Pretend you have the following commit history, and you want to rebase & squash bug1 onto master:

    F < bug2
   /
A-B-G-H < master
   \
    C-D-E < bug1

Here's what you will see when you type git rebase -i master bug1

pick f7f3f6d changed my name a bit
pick 310154e updated README formatting and added blame
pick a5f4a0d added cat-file
#
# Commands:
#  p, pick = use commit
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#
# If you remove a line here THAT COMMIT WILL BE LOST.
# However, if you remove everything, the rebase will be aborted.
#

To squash all commits of a branch down into a single commit, keep the first commit as "pick" and replace all subsequent "pick" entries with "squash" or simply "s". You will get the opportunity to change the commit message, too.

pick f7f3f6d changed my name a bit
s 310154e updated README formatting and added blame
s a5f4a0d added cat-file
#
# Commands:
#  p, pick = use commit
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit

So yeah, squashing is a bit of a pain, but I would still recommend it over heavy use of stashes.

Remove header and footer from window.print()

So basic idea is to have a div (with display none) containing items to print. Now on click of a button do not print to entire body but just that particular div. Faced lots of issues while printing a div (part of HTML) using window.print(). Used below method and it works seamlessly in edge, chrome and Mozilla for me, let see if it help you too.

function printDiv(id) {
      var contents = document.getElementById(id).innerHTML;
        var frame1 = document.createElement('iframe');
        frame1.name = "frame1";
        frame1.style.position = "absolute";
        frame1.style.top = "-1000000px";
        document.body.appendChild(frame1);
        var frameDoc = frame1.contentWindow ? frame1.contentWindow : frame1.contentDocument.document ? frame1.contentDocument.document : frame1.contentDocument;
        frameDoc.document.open();
        frameDoc.document.write("<html><head>\n\n                " +
            "<style type=\"text/css\" media=\"print\">\n                       " +
            "@@page\n                    {\n                        " +
            "size:  auto;   /* auto is the initial value */\n                        " +
            "margin: 10mm;  /* this affects the margin in the printer settings */\n    " +
            "                }\n\n                    html\n                    {\n    " +
            "                    background-color: #FFFFFF;\n         " +
            "           }\n\n                    body\n                " +
            "    {   font-family:\"Times New Roman\", Times, serif;\n             " +
            "           border: none ;\n                  " +
            "      margin: 0; /* margin you want for the content */\n                " +
            "    }\n                   .table {\n                    width: 100%;\n      " +
            "              max-width: 100%;\n                    margin-bottom: 20px;\n        " +
            "            border-collapse: collapse;\n                 " +
            "   background-color: transparent;\n                    display: table;\n        " +
            "        }\n                .table-bordered {\n                 " +
            "   border: 1px solid #ccc;\n                }\n                tr {\n            " +
            "        display: table-row;\n                    vertical-align: inherit;\n              " +
            "      border-color: inherit;\n                    padding:15px;\n                }\n      " +
            "          .table-bordered tr td {border: 1px solid #ccc!important; padding:15px!important;}\n   " +
            "             </style><title></title></head><body>".concat(contents, "</body>"));
        frameDoc.document.close();
        setTimeout(function () {
            window.frames["frame1"].focus();
            window.frames["frame1"].print();
            document.body.removeChild(frame1);
        }, 500);
        return false;
}

Call this like

<a href="#" onclick="javascript:printDiv('divwithcontenttoprint')"> Print </a>

How to update /etc/hosts file in Docker image during "docker build"

Complete Answer

  1. Prepare your own hosts file you wish to add to docker container;
1.2.3.4 abc.tv
5.6.7.8 domain.xyz
1.3.5.7 odd.org
2.4.6.8 even.net
  1. COPY your hosts file into the container by adding the following line in the Dockerfile
COPY hosts /etc/hosts_extra
  1. If you know how to use ENTRYPOINT or CMD or CRON job then incorporate the following command line into it or at least run this inside the running container:
cat /etc/hosts_extra >> etc/hosts;
  1. You cannot add the following in the Dockerfile because the modification will be lost:
RUN cat /etc/hosts_extra >> etc/hosts;

How to concatenate two MP4 files using FFmpeg?

Here is a script I made to concatenate several GoPro mp4's into a 720p mp4. Hope it's of help.

#!/bin/sh
cmd="( "
for i; do
    cmd="${cmd}ffmpeg -i $i -ab 256000 -vb 10000000 -mbd rd -trellis 2 -cmp 2 -subcmp 2 -g 100 -f mpeg -; "
done
cmd="${cmd} ) | ffmpeg -i - -vb 10000000 -ab 256000 -s 1280x720 -y out-`date +%F-%H%M.%S`.mp4"
echo "${cmd}"
eval ${cmd}

How to find index position of an element in a list when contains returns true

Here is an example:

List<String> names;
names.add("toto");
names.add("Lala");
names.add("papa");
int index = names.indexOf("papa"); // index = 2

Prompt for user input in PowerShell

Place this at the top of your script. It will cause the script to prompt the user for a password. The resulting password can then be used elsewhere in your script via $pw.

   Param(
     [Parameter(Mandatory=$true, Position=0, HelpMessage="Password?")]
     [SecureString]$password
   )

   $pw = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))

If you want to debug and see the value of the password you just read, use:

   write-host $pw

std::wstring VS std::string

I frequently use std::string to hold utf-8 characters without any problems at all. I heartily recommend doing this when interfacing with API's which use utf-8 as the native string type as well.

For example, I use utf-8 when interfacing my code with the Tcl interpreter.

The major caveat is the length of the std::string, is no longer the number of characters in the string.

How do I use hexadecimal color strings in Flutter?

You can click on Color Widget and it tells you in much deeper information how those letters stand for. You can also use Color.fromARGB() method to create custom colors which is much easier to me. Use Flutter Doctor Color Picker website to pick any color you want for your flutter application.

What are projection and selection?

Exactly.

Projection means choosing which columns (or expressions) the query shall return.

Selection means which rows are to be returned.

if the query is

select a, b, c from foobar where x=3;

then "a, b, c" is the projection part, "where x=3" the selection part.

How to Convert unsigned char* to std::string in C++?

You just needed to cast the unsigned char into a char as the string class doesn't have a constructor that accepts unsigned char:

unsigned char* uc;
std::string s( reinterpret_cast< char const* >(uc) ) ;

However, you will need to use the length argument in the constructor if your byte array contains nulls, as if you don't, only part of the array will end up in the string (the array up to the first null)

size_t len;
unsigned char* uc;
std::string s( reinterpret_cast<char const*>(uc), len ) ;

Call and receive output from Python script in Java?

The best way to achieve would be to use Apache Commons Exec as I use it for production without problems even for Java 8 environment because of the fact that it lets you execute any external process (including python, bash etc) in synchronous and asynchronous way by using watchdogs.

 CommandLine cmdLine = new CommandLine("python");
 cmdLine.addArgument("/my/python/script/script.py");
 DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

 ExecuteWatchdog watchdog = new ExecuteWatchdog(60*1000);
 Executor executor = new DefaultExecutor();
 executor.setExitValue(1);
 executor.setWatchdog(watchdog);
 executor.execute(cmdLine, resultHandler);

 // some time later the result handler callback was invoked so we
 // can safely request the exit value
 resultHandler.waitFor();

Complete source code for a small but complete POC is shared here that addresses another concern in this post;

https://github.com/raohammad/externalprocessfromjava.git

Where should I put <script> tags in HTML markup?

The best place to put <script> tag is before closing </body> tag, so the downloading and executing it doesn't block the browser to parse the html in document,

Also loading the js files externally has it's own advantages like it will be cached by browsers and can speed up page load times, it separates the HTML and JavaScript code and help to manage the code base better.

but modern browsers also support some other optimal ways like async and defer to load external javascript files.

Async and Defer

Normally HTML page execution starts line by line. When an external JavaScript element is encountered, HTML parsing is stopped until a JavaScript is download and ready for execution. This normal page execution can be changed using defer and async attribute.

Defer

When a defer attribute is used, JavaScript is downloaded parallelly with HTML parsing but will be execute only after full HTML parsing is done.

<script src="/local-js-path/myScript.js" defer></script>

Async

When async attribute is used, JavaScript is downloaded as soon as the script is encountered and after the download, it will be executed asynchronously (parallelly) along with HTML parsing.

<script src="/local-js-path/myScript.js" async></script>

When to use which attributes

  • If your script is independent of other scripts and is modular, use async.
  • If you are loading script1 and script2 with async, both will run
    parallelly along with HTML parsing, as soon as they are downloaded
    and available.
  • If your script depends on another script then use defer for both:
  • When script1 and script2 are loaded in that order with defer, then script1 is guaranteed to execute first,
  • Then script2 will execute after script1 is fully executed.
  • Must do this if script2 depends on script1.
  • If your script is small enough and is depended by another script of type async then use your script with no attributes and place it above all the async scripts.

reference:knowledgehills.com

Created Button Click Event c#

Create the Button and add it to Form.Controls list to display it on your form:

Button buttonOk = new Button();
buttonOk.Location = new Point(295, 45);  //or what ever position you want it to give
buttonOk.Text = "OK"; //or what ever you want to write over it
buttonOk.Click += new EventHandler(buttonOk_Click);
this.Controls.Add(buttonOk); //here you add it to the Form's Controls list

Create the button click method here:

void buttonOk_Click(object sender, EventArgs e)
        {
            MessageBox.Show("clicked");
            this.Close(); //all your choice to close it or remove this line
        }

What is a blob URL and why it is used?

This Javascript function purports to show the difference between the Blob File API and the Data API to download a JSON file in the client browser:

_x000D_
_x000D_
/**_x000D_
 * Save a text as file using HTML <a> temporary element and Blob_x000D_
 * @author Loreto Parisi_x000D_
 */_x000D_
_x000D_
var saveAsFile = function(fileName, fileContents) {_x000D_
    if (typeof(Blob) != 'undefined') { // Alternative 1: using Blob_x000D_
        var textFileAsBlob = new Blob([fileContents], {type: 'text/plain'});_x000D_
        var downloadLink = document.createElement("a");_x000D_
        downloadLink.download = fileName;_x000D_
        if (window.webkitURL != null) {_x000D_
            downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);_x000D_
        } else {_x000D_
            downloadLink.href = window.URL.createObjectURL(textFileAsBlob);_x000D_
            downloadLink.onclick = document.body.removeChild(event.target);_x000D_
            downloadLink.style.display = "none";_x000D_
            document.body.appendChild(downloadLink);_x000D_
        }_x000D_
        downloadLink.click();_x000D_
    } else { // Alternative 2: using Data_x000D_
        var pp = document.createElement('a');_x000D_
        pp.setAttribute('href', 'data:text/plain;charset=utf-8,' +_x000D_
            encodeURIComponent(fileContents));_x000D_
        pp.setAttribute('download', fileName);_x000D_
        pp.onclick = document.body.removeChild(event.target);_x000D_
        pp.click();_x000D_
    }_x000D_
} // saveAsFile_x000D_
_x000D_
/* Example */_x000D_
var jsonObject = {"name": "John", "age": 30, "car": null};_x000D_
saveAsFile('out.json', JSON.stringify(jsonObject, null, 2));
_x000D_
_x000D_
_x000D_

The function is called like saveAsFile('out.json', jsonString);. It will create a ByteStream immediately recognized by the browser that will download the generated file directly using the File API URL.createObjectURL.

In the else, it is possible to see the same result obtained via the href element plus the Data API, but this has several limitations that the Blob API has not.

AngularJS - $http.post send data as json

Consider explicitly setting the header in the $http.post (I put application/json, as I am not sure which of the two versions in your example is the working one, but you can use application/x-www-form-urlencoded if it's the other one):

$http.post("/customer/data/autocomplete", {term: searchString}, {headers: {'Content-Type': 'application/json'} })
        .then(function (response) {
            return response;
        });

How to expire a cookie in 30 minutes using jQuery?

If you're using jQuery Cookie (https://plugins.jquery.com/cookie/), you can use decimal point or fractions.

As one day is 1, one minute would be 1 / 1440 (there's 1440 minutes in a day).

So 30 minutes is 30 / 1440 = 0.02083333.

Final code:

$.cookie("example", "foo", { expires: 30 / 1440, path: '/' });

I've added path: '/' so that you don't forget that the cookie is set on the current path. If you're on /my-directory/ the cookie is only set for this very directory.

Stop MySQL service windows

For Windows there's a couple of tricks to take care of...

(Assuming you've installed MySQL from Oracle's site but maybe have chosen not to run the service at startup)...

  1. To use "mysqld stop" from the command line for WinVista/Win7 you must right click on Start -> All Programs -> Accessories -> Command Prompt -> Run As Administrator

  2. Now that you have local OS admin access you can use "mysqld stop" (which will simply return)

IF YOU SEE THE FOLLOWING YOU ARE TRYING IT WITH A USER/COMMAND PROMPT THAT DOES NOT HAVE THE CORRECT PRIVILEGES:

121228 11:54:50 [Warning] Can't create test file c:\Program Files\MySQL\MySQL Server 5.5\data\hpdv7.lower-test
121228 11:54:50 [Warning] Can't create test file c:\Program Files\MySQL\MySQL Server 5.5\data\hpdv7.lower-test
121228 11:54:50 [Note] Plugin 'FEDERATED' is disabled.
121228 11:54:50 InnoDB: The InnoDB memory heap is disabled
121228 11:54:50 InnoDB: Mutexes and rw_locks use Windows interlocked functions
121228 11:54:50 InnoDB: Compressed tables use zlib 1.2.3
121228 11:54:50 InnoDB: Initializing buffer pool, size = 128.0M
121228 11:54:50 InnoDB: Completed initialization of buffer pool
121228 11:54:50  InnoDB: Operating system error number 5 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory. It may also be you have created a subdirectory
InnoDB: of the same name as a data file.
InnoDB: File name .\ibdata1
InnoDB: File operation call: 'create'.
InnoDB: Cannot continue operation.

If mysqld does not appear as a known system command, try adding it to your class path

  1. Right click on My Computer
  2. Advanced System Settings
  3. Environment Variables
  4. System variables
  5. look for and left click select the variable named path
  6. click on "Edit" and copy out the string to notepad and append at the end the full path to your MySQL bin directory , e.g.

    %SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;c:\Program Files\MySQL\MySQL Server 5.5\bin

C# - insert values from file into two arrays

var Text = File.ReadAllLines("Path"); foreach (var i in Text) {    var SplitText = i.Split().Where(x=> x.Lenght>1).ToList();    //@Array1 add SplitText[0]    //@Array2 add SpliteText[1]   }  

How to convert milliseconds to seconds with precision

Why don't you simply try

System.out.println(1500/1000.0);
System.out.println(500/1000.0);

How do I install Keras and Theano in Anaconda Python on Windows?

I use macOS and used to have the same problem.
Running the following command in the terminal saved me:

conda install -c conda-forge keras tensorflow

Hope it helps.

Can't stop rails server

When the rails server does not start it means that it is already running then you can start by using new port eg.

rails s -p 3001

or it starts and stops in that case you want to delete temp folder in rails directory structure it starts the rails server.

Making a POST call instead of GET using urllib2

it should be sending a POST if you provide a data parameter (like you are doing):

from the docs: "the HTTP request will be a POST instead of a GET when the data parameter is provided"

so.. add some debug output to see what's up from the client side.

you can modify your code to this and try again:

import urllib
import urllib2

url = 'http://myserver/post_service'
opener = urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1))
data = urllib.urlencode({'name' : 'joe',
                         'age'  : '10'})
content = opener.open(url, data=data).read()

Decoding UTF-8 strings in Python

You need to properly decode the source text. Most likely the source text is in UTF-8 format, not ASCII.

Because you do not provide any context or code for your question it is not possible to give a direct answer.

I suggest you study how unicode and character encoding is done in Python:

http://docs.python.org/2/howto/unicode.html

WPF: simple TextBox data binding

Name2 is a field. WPF binds only to properties. Change it to:

public string Name2 { get; set; }

Be warned that with this minimal implementation, your TextBox won't respond to programmatic changes to Name2. So for your timer update scenario, you'll need to implement INotifyPropertyChanged:

partial class Window1 : Window, INotifyPropertyChanged
{
  public event PropertyChangedEventHandler PropertyChanged;

  protected void OnPropertyChanged(string propertyName)
  {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  }

  private string _name2;

  public string Name2
  {
    get { return _name2; }
    set
    {
      if (value != _name2)
      {
         _name2 = value;
         OnPropertyChanged("Name2");
      }
    }
  }
}

You should consider moving this to a separate data object rather than on your Window class.

How to change TIMEZONE for a java.util.Calendar/Date

  1. The class Date/Timestamp represents a specific instant in time, with millisecond precision, since January 1, 1970, 00:00:00 GMT. So this time difference (from epoch to current time) will be same in all computers across the world with irrespective of Timezone.

  2. Date/Timestamp doesn't know about the given time is on which timezone.

  3. If we want the time based on timezone we should go for the Calendar or SimpleDateFormat classes in java.

  4. If you try to print a Date/Timestamp object using toString(), it will convert and print the time with the default timezone of your machine.

  5. So we can say (Date/Timestamp).getTime() object will always have UTC (time in milliseconds)

  6. To conclude Date.getTime() will give UTC time, but toString() is on locale specific timezone, not UTC.

Now how will I create/change time on specified timezone?

The below code gives you a date (time in milliseconds) with specified timezones. The only problem here is you have to give date in string format.

   DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
   dateFormatLocal.setTimeZone(timeZone);
   java.util.Date parsedDate = dateFormatLocal.parse(date);

Use dateFormat.format for taking input Date (which is always UTC), timezone and return date as String.

How to store UTC/GMT time in DB:

If you print the parsedDate object, the time will be in default timezone. But you can store the UTC time in DB like below.

        Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
        Timestamp tsSchedStartTime = new Timestamp (parsedDate.getTime());
        if (tsSchedStartTime != null) {
            stmt.setTimestamp(11, tsSchedStartTime, calGMT );
        } else {
            stmt.setNull(11, java.sql.Types.DATE);
        }

Error while trying to retrieve text for error ORA-01019

I have the same issue. My solution was delete one of the oracle path in environment variable. I also changed the inventory.xml and point to the oracle home version which is in my environment path variable.

Incorrect string value: '\xF0\x9F\x8E\xB6\xF0\x9F...' MySQL

According to the create table statement, the default charset of the table is already utf8mb4. It seems that you have a wrong connection charset.

In Java, set the datasource url like this: jdbc:mysql://127.0.0.1:3306/testdb?useUnicode=true&characterEncoding=utf-8.

"?useUnicode=true&characterEncoding=utf-8" is necessary for using utf8mb4.

It works for my application.

MySQL query String contains

Use:

SELECT *
  FROM `table`
 WHERE INSTR(`column`, '{$needle}') > 0

Reference:

What does "export" do in shell programming?

Well, it generally depends on the shell. For bash, it marks the variable as "exportable" meaning that it will show up in the environment for any child processes you run.

Non-exported variables are only visible from the current process (the shell).

From the bash man page:

export [-fn] [name[=word]] ...
export -p

The supplied names are marked for automatic export to the environment of subsequently executed commands.

If the -f option is given, the names refer to functions. If no names are given, or if the -p option is supplied, a list of all names that are exported in this shell is printed.

The -n option causes the export property to be removed from each name.

If a variable name is followed by =word, the value of the variable is set to word.

export returns an exit status of 0 unless an invalid option is encountered, one of the names is not a valid shell variable name, or -f is supplied with a name that is not a function.

You can also set variables as exportable with the typeset command and automatically mark all future variable creations or modifications as such, with set -a.

App.Config file in console application C#

You can add a reference to System.Configuration in your project and then:

using System.Configuration;

then

string sValue = ConfigurationManager.AppSettings["BatchFile"];

with an app.config file like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <appSettings>
       <add key="BatchFile" value="blah.bat" />
   </appSettings>
</configuration>

How to save a new sheet in an existing excel file, using Pandas?

#This program is to read from excel workbook to fetch only the URL domain names and write to the existing excel workbook in a different sheet..
#Developer - Nilesh K
import pandas as pd
from openpyxl import load_workbook #for writting to the existing workbook

df = pd.read_excel("urlsearch_test.xlsx")

#You can use the below for the relative path.
# r"C:\Users\xyz\Desktop\Python\

l = [] #To make a list in for loop

#begin
#loop starts here for fetching http from a string and iterate thru the entire sheet. You can have your own logic here.
for index, row in df.iterrows():
    try: 
        str = (row['TEXT']) #string to read and iterate
        y = (index)
        str_pos = str.index('http') #fetched the index position for http
        str_pos1 = str.index('/', str.index('/')+2) #fetched the second 3rd position of / starting from http
        str_op = str[str_pos:str_pos1] #Substring the domain name
        l.append(str_op) #append the list with domain names

    #Error handling to skip the error rows and continue.
    except ValueError:
            print('Error!')
print(l)
l = list(dict.fromkeys(l)) #Keep distinct values, you can comment this line to get all the values
df1 = pd.DataFrame(l,columns=['URL']) #Create dataframe using the list
#end

#Write using openpyxl so it can be written to same workbook
book = load_workbook('urlsearch_test.xlsx')
writer = pd.ExcelWriter('urlsearch_test.xlsx',engine = 'openpyxl')
writer.book = book
df1.to_excel(writer,sheet_name = 'Sheet3')
writer.save()
writer.close()

#The below can be used to write to a different workbook without using openpyxl
#df1.to_excel(r"C:\Users\xyz\Desktop\Python\urlsearch1_test.xlsx",index='false',sheet_name='sheet1')

Spring RestTemplate timeout

I had a similar scenario, but was also required to set a Proxy. The simplest way I could see to do this was to extend the SimpleClientHttpRequestFactory for the ease of setting the proxy (different proxies for non-prod vs prod). This should still work even if you don't require the proxy though. Then in my extended class I override the openConnection(URL url, Proxy proxy) method, using the same as the source, but just setting the timeouts before returning.

@Override
protected HttpURLConnection openConnection(URL url, Proxy proxy) throws IOException {
    URLConnection urlConnection = proxy != null ? url.openConnection(proxy) : url.openConnection();
    Assert.isInstanceOf(HttpURLConnection.class, urlConnection);
    urlConnection.setConnectTimeout(5000);
    urlConnection.setReadTimeout(5000);
    return (HttpURLConnection) urlConnection;
}

Loop through an array in JavaScript

It's not 100% identical, but similar:

_x000D_
_x000D_
   var myStringArray = ['Hello', 'World']; // The array uses [] not {}
    for (var i in myStringArray) {
        console.log(i + ' -> ' + myStringArray[i]); // i is the index/key, not the item
    }
_x000D_
_x000D_
_x000D_

IsNullOrEmpty with Object

object MyObject = null;

if (MyObject != null && !string.IsNullOrEmpty(MyObject.ToString())) { ... }

Import PEM into Java Key Store

In my case I had a pem file which contained two certificates and an encrypted private key to be used in mutual SSL authentication. So my pem file looked like this:

-----BEGIN CERTIFICATE-----

...

-----END CERTIFICATE-----

-----BEGIN RSA PRIVATE KEY-----

Proc-Type: 4,ENCRYPTED

DEK-Info: DES-EDE3-CBC,C8BF220FC76AA5F9

...

-----END RSA PRIVATE KEY-----

-----BEGIN CERTIFICATE-----

...

-----END CERTIFICATE-----

Here is what I did

Split the file into three separate files, so that each one contains just one entry, starting with ---BEGIN.. and ending with ---END.. lines. Lets assume we now have three files: cert1.pem, cert2.pem, and pkey.pem.

Convert pkey.pem into DER format using openssl and the following syntax:

openssl pkcs8 -topk8 -nocrypt -in pkey.pem -inform PEM -out pkey.der -outform DER

Note, that if the private key is encrypted you need to supply a password( obtain it from the supplier of the original pem file ) to convert to DER format, openssl will ask you for the password like this: "enter a passphrase for pkey.pem: ".

If conversion is successful, you will get a new file called pkey.der.

Create a new java keystore and import the private key and the certificates:

String keypass = "password";  // this is a new password, you need to come up with to protect your java key store file
String defaultalias = "importkey";
KeyStore ks = KeyStore.getInstance("JKS", "SUN");

// this section does not make much sense to me, 
// but I will leave it intact as this is how it was in the original example I found on internet:   
ks.load( null, keypass.toCharArray());
ks.store( new FileOutputStream ( "mykeystore"  ), keypass.toCharArray());
ks.load( new FileInputStream ( "mykeystore" ),    keypass.toCharArray());
// end of section..


// read the key file from disk and create a PrivateKey

FileInputStream fis = new FileInputStream("pkey.der");
DataInputStream dis = new DataInputStream(fis);
byte[] bytes = new byte[dis.available()];
dis.readFully(bytes);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);

byte[] key = new byte[bais.available()];
KeyFactory kf = KeyFactory.getInstance("RSA");
bais.read(key, 0, bais.available());
bais.close();

PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec ( key );
PrivateKey ff = kf.generatePrivate (keysp);


// read the certificates from the files and load them into the key store:

Collection  col_crt1 = CertificateFactory.getInstance("X509").generateCertificates(new FileInputStream("cert1.pem"));
Collection  col_crt2 = CertificateFactory.getInstance("X509").generateCertificates(new FileInputStream("cert2.pem"));

Certificate crt1 = (Certificate) col_crt1.iterator().next();
Certificate crt2 = (Certificate) col_crt2.iterator().next();
Certificate[] chain = new Certificate[] { crt1, crt2 };

String alias1 = ((X509Certificate) crt1).getSubjectX500Principal().getName();
String alias2 = ((X509Certificate) crt2).getSubjectX500Principal().getName();

ks.setCertificateEntry(alias1, crt1);
ks.setCertificateEntry(alias2, crt2);

// store the private key
ks.setKeyEntry(defaultalias, ff, keypass.toCharArray(), chain );

// save the key store to a file         
ks.store(new FileOutputStream ( "mykeystore" ),keypass.toCharArray());

(optional) Verify the content of your new key store:

$ keytool -list -keystore mykeystore -storepass password

Keystore type: JKS Keystore provider: SUN

Your keystore contains 3 entries:

  • cn=...,ou=...,o=.., Sep 2, 2014, trustedCertEntry, Certificate fingerprint (SHA1): 2C:B8: ...

  • importkey, Sep 2, 2014, PrivateKeyEntry, Certificate fingerprint (SHA1): 9C:B0: ...

  • cn=...,o=...., Sep 2, 2014, trustedCertEntry, Certificate fingerprint (SHA1): 83:63: ...

(optional) Test your certificates and private key from your new key store against your SSL server: ( You may want to enable debugging as an VM option: -Djavax.net.debug=all )

        char[] passw = "password".toCharArray();
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        ks.load(new FileInputStream ( "mykeystore" ), passw );

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passw);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        TrustManager[] tm = tmf.getTrustManagers();

        SSLContext sclx = SSLContext.getInstance("TLS");
        sclx.init( kmf.getKeyManagers(), tm, null);

        SSLSocketFactory factory = sclx.getSocketFactory();
        SSLSocket socket = (SSLSocket) factory.createSocket( "192.168.1.111", 443 );
        socket.startHandshake();

        //if no exceptions are thrown in the startHandshake method, then everything is fine..

Finally register your certificates with HttpsURLConnection if plan to use it:

        char[] passw = "password".toCharArray();
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        ks.load(new FileInputStream ( "mykeystore" ), passw );

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passw);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        TrustManager[] tm = tmf.getTrustManagers();

        SSLContext sclx = SSLContext.getInstance("TLS");
        sclx.init( kmf.getKeyManagers(), tm, null);

        HostnameVerifier hv = new HostnameVerifier()
        {
            public boolean verify(String urlHostName, SSLSession session)
            {
                if (!urlHostName.equalsIgnoreCase(session.getPeerHost()))
                {
                    System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'.");
                }
                return true;
            }
        };

        HttpsURLConnection.setDefaultSSLSocketFactory( sclx.getSocketFactory() );
        HttpsURLConnection.setDefaultHostnameVerifier(hv);

Remove a data connection from an Excel 2010 spreadsheet in compatibility mode

Excel 2010: On the File/Info page, go to 'Related Documents' and click break links => warning will appear that all linked values will be converted to their data values => click ok => done

How to find which git branch I am on when my disk is mounted on other server

git branch with no arguments displays the current branch marked with an asterisk in front of it:

user@host:~/gittest$ git branch
* master
  someotherbranch

In order to not have to type this all the time, I can recommend git prompt:

https://github.com/git/git/blob/master/contrib/completion/git-prompt.sh

In the AIX box how I can see that I am using master or inside a particular branch. What changes inside .git that drives which branch I am on?

Git stores the HEAD in the file .git/HEAD. If you're on the master branch, it could look like this:

$ cat .git/HEAD
ref: refs/heads/master

How to get a date in YYYY-MM-DD format from a TSQL datetime field?

As string processing is expensive, and FORMAT more so, I am surprised that Asher/Aaron Dietz response is not higher, if not top; the question is seeking ISO 8601 date, and isn't specifically requesting it as a string type.

The most efficient method would be any of these (I've included the answer Asher/Aaron Dietz have already suggested for completeness):

All versions

select  cast(getdate() as date)
select  convert(date, getdate())

2008 and higher

select  convert(date, current_timestamp)

ANSI SQL equivalent 2008 and higher

select  cast(current_timestamp as date)

References:

https://sqlperformance.com/2015/06/t-sql-queries/format-is-nice-and-all-but

https://en.wikipedia.org/wiki/ISO_8601

https://www.w3schools.com/sql/func_sqlserver_current_timestamp.asp

https://docs.microsoft.com/en-us/sql/t-sql/functions/current-timestamp-transact-sql?view=sql-server-ver15

How to print all session variables currently set?

session_start();
echo '<pre>';var_dump($_SESSION);echo '</pre>';
// or
echo '<pre>';print_r($_SESSION);echo '</pre>';

NOTE: session_start(); line is must then only you will able to print the value $_SESSION

Change the mouse pointer using JavaScript

document.body.style.cursor = 'cursorurl';

Java SecurityException: signer information does not match

If you added all the jars from bouncycastle.org (in my case from crypto-159.zip), just remove the ones for the JDKs that do not apply to you. There are redundancies. You probably only need the "jdk15on" jars.

Simple DateTime sql query

This has worked for me in both SQL Server 2005 and 2008:

SELECT * from TABLE
WHERE FIELDNAME > {ts '2013-02-01 15:00:00.001'}
  AND FIELDNAME < {ts '2013-08-05 00:00:00.000'}

Including non-Python files with setup.py

create MANIFEST.in in the project root with recursive-include to the required directory or include with the file name.

include LICENSE
include README.rst
recursive-include package/static *
recursive-include package/templates *

documentation can be found here

Possible reasons for timeout when trying to access EC2 instance

If you've just created a new instance and can't connect to it, I was able to solve the issue by terminating that one and creating a new one. Of course this will only work if it's a new instance and you haven't done any more work on it.

map vs. hash_map in C++

hash_map was a common extension provided by many library implementations. That is exactly why it was renamed to unordered_map when it was added to the C++ standard as part of TR1. map is generally implemented with a balanced binary tree like a red-black tree (implementations vary of course). hash_map and unordered_map are generally implemented with hash tables. Thus the order is not maintained. unordered_map insert/delete/query will be O(1) (constant time) where map will be O(log n) where n is the number of items in the data structure. So unordered_map is faster, and if you don't care about the order of the items should be preferred over map. Sometimes you want to maintain order (ordered by the key) and for that map would be the choice.

Float to String format specifier

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

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

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

Group by & count function in sqlalchemy

You can also count on multiple groups and their intersection:

self.session.query(func.count(Table.column1),Table.column1, Table.column2).group_by(Table.column1, Table.column2).all()

The query above will return counts for all possible combinations of values from both columns.

jQuery adding 2 numbers from input fields

<script type="text/javascript">
    $(document).ready(function () {
        $('#btnadd').on('click', function () {
            var n1 = parseInt($('#txtn1').val());
            var n2 = parseInt($('#txtn2').val());
            var r = n1 + n2;
            alert("sum of 2 No= " + r);
            return false;
        });
        $('#btnclear').on('click', function () {
            $('#txtn1').val('');
            $('#txtn2').val('');
            $('#txtn1').focus();
            return false;
        });
    });
</script>

Android design support library for API 28 (P) not working

You can either use the previous API packages version of artifacts or the new Androidx, never both.

If you wanna use the previous version, replace your dependencies with

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'
    implementation 'com.android.support.constraint:constraint-layout:1.1.1'

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    implementation 'com.android.support:design:28.0.0-alpha3'
    implementation 'com.android.support:cardview-v7:28.0.0-alpha3'
}

if you want to use Androidx:

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.0.0-alpha3'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.1'

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.0-alpha3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha3'

    implementation 'com.google.android.material:material:1.0.0-alpha3'
    implementation 'androidx.cardview:cardview:1.0.0-alpha3'
}

Convert date time string to epoch in Bash

For Linux Run this command

date -d '06/12/2012 07:21:22' +"%s"

For mac OSX run this command

date -j -u -f "%a %b %d %T %Z %Y" "Tue Sep 28 19:35:15 EDT 2010" "+%s"

Command copy exited with code 4 when building - Visual Studio restart solves it

Error code 4 can mean a lot of things, so I recommend reading the other answers as well until you find a solution that works for you AND you understand WHY it works (some solutions only disable error handling, which may only mask the problem but not solve it).

This can be a file locking issue related to parallel building. A workaround is to not use parallel building. This is the default behavior, but if you are using the -m option, then projects will be built in parallel. The following variations should not build projects in parallel, so you will not run into the file locking problem.

msbuild -m:1
msbuild -maxcpucount:1
msbuild

Note that, contrary to what has been said here, this even happens with the "latest" version of MSBuild (from Build Tools for Visual Studio 2019).

The best solution is probably to make sure you don't need to copy files in a post-build step. In some situations, you can also disable post-build steps when building with MSBuild on a build server: https://stackoverflow.com/a/55899347/2279059

SQL GROUP BY CASE statement with aggregate function

My guess is that you don't really want to GROUP BY some_product.

The answer to: "Is there a way to GROUP BY a column alias such as some_product in this case, or do I need to put this in a subquery and group on that?" is: You can not GROUP BY a column alias.

The SELECT clause, where column aliases are assigned, is not processed until after the GROUP BY clause. An inline view or common table expression (CTE) could be used to make the results available for grouping.

Inline view:

select ...
from (select ... , CASE WHEN col1 > col2 THEN SUM(col3*col4) ELSE 0 END AS some_product
   from ...
   group by col1, col2 ... ) T
group by some_product ...

CTE:

with T as (select ... , CASE WHEN col1 > col2 THEN SUM(col3*col4) ELSE 0 END AS some_product
   from ...
   group by col1, col2 ... )
select ...
from T
group by some_product ... 

How to fix git error: RPC failed; curl 56 GnuTLS

I met the same question, and solved it by using SSH protocol.

git clone [email protected]:micro/micro.git

(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

Try writing the file path as "C:\\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener" i.e with double backslash after the drive as opposed to "C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener"

How to get the path of current worksheet in VBA?

Always nice to have:

Dim myPath As String     
Dim folderPath As String 

folderPath = Application.ActiveWorkbook.Path    
myPath = Application.ActiveWorkbook.FullName

Date constructor returns NaN in IE, but works in Firefox and Chrome

I tried all the above solution but nothing worked for me. I did some brainstorming and found this and worked fine in IE11 as well.

_x000D_
_x000D_
value="2020-08-10 05:22:44.0";
var date=new Date(value.replace(" ","T")).$format("d/m/yy h:i:s");
console.log(date);
_x000D_
_x000D_
_x000D_

if $format is not working for you use format only.

What is the difference between an interface and abstract class?

The shortest way to sum it up is that an interface is:

  1. Fully abstract, apart from default and static methods; while it has definitions (method signatures + implementations) for default and static methods, it only has declarations (method signatures) for other methods.
  2. Subject to laxer rules than classes (a class can implement multiple interfaces, and an interface can inherit from multiple interfaces). All variables are implicitly constant, whether specified as public static final or not. All members are implicitly public, whether specified as such or not.
  3. Generally used as a guarantee that the implementing class will have the specified features and/or be compatible with any other class which implements the same interface.

Meanwhile, an abstract class is:

  1. Anywhere from fully abstract to fully implemented, with a tendency to have one or more abstract methods. Can contain both declarations and definitions, with declarations marked as abstract.
  2. A full-fledged class, and subject to the rules that govern other classes (can only inherit from one class), on the condition that it cannot be instantiated (because there's no guarantee that it's fully implemented). Can have non-constant member variables. Can implement member access control, restricting members as protected, private, or private package (unspecified).
  3. Generally used either to provide as much of the implementation as can be shared by multiple subclasses, or to provide as much of the implementation as the programmer is able to supply.

Or, if we want to boil it all down to a single sentence: An interface is what the implementing class has, but an abstract class is what the subclass is.

Anaconda site-packages

I installed miniconda and found all the installed packages in /miniconda3/pkgs

How to use Javascript to read local text file and read line by line?

Using ES6 the javascript becomes a little cleaner

handleFiles(input) {

    const file = input.target.files[0];
    const reader = new FileReader();

    reader.onload = (event) => {
        const file = event.target.result;
        const allLines = file.split(/\r\n|\n/);
        // Reading line by line
        allLines.forEach((line) => {
            console.log(line);
        });
    };

    reader.onerror = (event) => {
        alert(event.target.error.name);
    };

    reader.readAsText(file);
}

How can a web application send push notifications to iOS devices?

Check out Xtify Web Push notifications. http://getreactor.xtify.com/ This tool allows you to push content onto a webpage and target visitors as well as trigger messages based on browser DOM events. It's designed specifically with mobile in mind.

Send JSON data with jQuery

You need to set the correct content type and stringify your object.

var arr = {City:'Moscow', Age:25};
$.ajax({
    url: "Ajax.ashx",
    type: "POST",
    data: JSON.stringify(arr),
    dataType: 'json',
    async: false,
    contentType: 'application/json; charset=utf-8',
    success: function(msg) {
        alert(msg);
    }
});

How to install mscomct2.ocx file from .cab file (Excel User Form and VBA)

You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.

  1. Just extract the .ocx file from the .cab file (it is similar to a zip)
  2. Copy to the system folder (c:\windows\sysWOW64 for 64 bit systems and c:\windows\system32 for 32 bit)
  3. Use regsvr32 through the command prompt to register the file (e.g. "regsvr32 c:\windows\sysWOW64\mscomct2.ocx")

References

Troubleshooting "Warning: session_start(): Cannot send session cache limiter - headers already sent"

You will find I have added the session_start() at the very top of the page. I have also removed the session_start() call later in the page. This page should work fine.

<?php
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="style.css" rel="stylesheet" type="text/css" />
<title>Welcome</title>


<script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
$(document).ready(function () { 

    $('#nav li').hover(
        function () {
            //show its submenu
            $('ul', this).slideDown(100);

        }, 
        function () {
            //hide its submenu
            $('ul', this).slideUp(100);         
        }
    );

});
    </script>

</head>

<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td class="header">&nbsp;</td>
  </tr>
  <tr>
    <td class="menu"><table align="center" cellpadding="0" cellspacing="0" width="80%">
    <tr>
    <td>

    <ul id="nav">
    <li><a href="#">Catalog</a>
    <ul><li><a href="#">Products</a></li>
        <li><a href="#">Bulk Upload</a></li>
        </ul>
        <div class="clear"></div>
        </li>


    <li><a href="#">Purchase  </a>

    </li>
    <li><a href="#">Customer Service</a>
    <ul>
        <li><a href="#">Contact Us</a></li>
        <li><a href="#">CS Panel</a></li>

    </ul>           
        <div class="clear"></div>
    </li>
    <li><a href="#">All Reports</a></li>
    <li><a href="#">Configuration</a>
    <ul> <li><a href="#">Look and Feel </a></li>
         <li><a href="#">Business Details</a></li>
         <li><a href="#">CS Details</a></li>
         <li><a href="#">Emaqil Template</a></li>
         <li><a href="#">Domain and Analytics</a></li>
         <li><a href="#">Courier</a></li>
         </ul>
    <div class="clear"></div>
    </li>
    <li><a href="#">Accounts</a>
    <ul><li><a href="#">Ledgers</a></li>
        <li><a href="#">Account Details</a></li>
        </ul>
         <div class="clear"></div></li>

</ul></td></tr></table></td>
  </tr>
  <tr>
    <td valign="top"><table width="80%" border="0" align="center" cellpadding="0" cellspacing="0">
      <tr>
        <td valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="2">
          <tr>
            <td width="22%" height="327" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="2">
              <tr>
                <td>&nbsp;</td>
                </tr>
              <tr>
                <td height="45"><strong>-&gt; Products</strong></td>
                </tr>
              <tr>
                <td height="61"><strong>-&gt; Categories</strong></td>
                </tr>
              <tr>
                <td height="48"><strong>-&gt; Sub Categories</strong></td>
                </tr>
            </table></td>
            <td width="78%" valign="top"><table width="100%" border="0" cellpadding="0" cellspacing="0">
              <tr>
                <td>&nbsp;</td>
                </tr>
              <tr>
                <td>
                  <table width="90%" border="0" cellspacing="0" cellpadding="0">
                    <tr>
                      <td width="26%">&nbsp;</td>
                      <td width="74%"><h2>Manage Categories</h2></td>
                    </tr>
                  </table></td>
                </tr>
              <tr>
                <td height="30">&nbsp;

                </td>
                </tr>
              <tr>
                <td>


</td>
                </tr>

                <tr>
                <td>
                <table width="49%" align="center" cellpadding="0" cellspacing="0">
                <tr><td>




<?php


                if (isset($_SESSION['error']))

                {

                    echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";

                    unset($_SESSION['error']);

                }

                ?>

                <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">

                <p>
                 <label class="style4">Category Name</label>

                   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="categoryname" /><br /><br />

                    <label class="style4">Category Image</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

                    <input type="file" name="image" /><br />

                    <input type="hidden" name="MAX_FILE_SIZE" value="100000" />

                   <br />
<br />
 <input type="submit" id="submit" value="UPLOAD" />

                </p>

                </form>




                             <?php


require("includes/conn.php");


function is_valid_type($file)

{

    $valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png");



    if (in_array($file['type'], $valid_types))

        return 1;

    return 0;
}

function showContents($array)

{

    echo "<pre>";

    print_r($array);

    echo "</pre>";
}


$TARGET_PATH = "images/category";

$cname = $_POST['categoryname'];

$image = $_FILES['image'];

$cname = mysql_real_escape_string($cname);

$image['name'] = mysql_real_escape_string($image['name']);

$TARGET_PATH .= $image['name'];

if ( $cname == "" || $image['name'] == "" )

{

    $_SESSION['error'] = "All fields are required";

    header("Location: managecategories.php");

    exit;

}

if (!is_valid_type($image))

{

    $_SESSION['error'] = "You must upload a jpeg, gif, or bmp";

    header("Location: managecategories.php");

    exit;

}




if (file_exists($TARGET_PATH))

{

    $_SESSION['error'] = "A file with that name already exists";

    header("Location: managecategories.php");

    exit;

}


if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))

{



    $sql = "insert into Categories (CategoryName, FileName) values ('$cname', '" . $image['name'] . "')";

    $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());

  header("Location: mangaecategories.php");

    exit;

}

else

{





    $_SESSION['error'] = "Could not upload file.  Check read/write persmissions on the directory";

    header("Location: mangagecategories.php");

    exit;

}

?> 

How do I set response headers in Flask?

We can set the response headers in Python Flask application using Flask application context using flask.g

This way of setting response headers in Flask application context using flask.g is thread safe and can be used to set custom & dynamic attributes from any file of application, this is especially helpful if we are setting custom/dynamic response headers from any helper class, that can also be accessed from any other file ( say like middleware, etc), this flask.g is global & valid for that request thread only.

Say if i want to read the response header from another api/http call that is being called from this app, and then extract any & set it as response headers for this app.

Sample Code: file: helper.py

import flask
from flask import request, g
from multidict import CIMultiDict
from asyncio import TimeoutError as HttpTimeout
from aiohttp import ClientSession

    def _extract_response_header(response)
      """
      extracts response headers from response object 
      and stores that required response header in flask.g app context
      """
      headers = CIMultiDict(response.headers)
      if 'my_response_header' not in g:
        g.my_response_header= {}
        g.my_response_header['x-custom-header'] = headers['x-custom-header']


    async def call_post_api(post_body):
      """
      sample method to make post api call using aiohttp clientsession
      """
      try:
        async with ClientSession() as session:
          async with session.post(uri, headers=_headers, json=post_body) as response:
            responseResult = await response.read()
            _extract_headers(response, responseResult)
            response_text = await response.text()
      except (HttpTimeout, ConnectionError) as ex:
        raise HttpTimeout(exception_message)

file: middleware.py

import flask
from flask import request, g

class SimpleMiddleWare(object):
    """
    Simple WSGI middleware
    """

    def __init__(self, app):
        self.app = app
        self._header_name = "any_request_header"

    def __call__(self, environ, start_response):
        """
        middleware to capture request header from incoming http request
        """
        request_id_header = environ.get(self._header_name)
        environ[self._header_name] = request_id_header

        def new_start_response(status, response_headers, exc_info=None):
            """
            set custom response headers
            """
            # set the request header as response header
            response_headers.append((self._header_name, request_id_header))
            # this is trying to access flask.g values set in helper class & set that as response header
            values = g.get(my_response_header, {})
            if values.get('x-custom-header'):
                response_headers.append(('x-custom-header', values.get('x-custom-header')))
            return start_response(status, response_headers, exc_info)

        return self.app(environ, new_start_response)

Calling the middleware from main class

file : main.py

from flask import Flask
import asyncio
from gevent.pywsgi import WSGIServer
from middleware import SimpleMiddleWare

    app = Flask(__name__)
    app.wsgi_app = SimpleMiddleWare(app.wsgi_app)

How to send a POST request from node.js Express?

I use superagent, which is simliar to jQuery.

Here is the docs

And the demo like:

var sa = require('superagent');
sa.post('url')
  .send({key: value})
  .end(function(err, res) {
    //TODO
  });

Extract column values of Dataframe as List in Apache Spark

I know the answer given and asked for is assumed for Scala, so I am just providing a little snippet of Python code in case a PySpark user is curious. The syntax is similar to the given answer, but to properly pop the list out I actually have to reference the column name a second time in the mapping function and I do not need the select statement.

i.e. A DataFrame, containing a column named "Raw"

To get each row value in "Raw" combined as a list where each entry is a row value from "Raw" I simply use:

MyDataFrame.rdd.map(lambda x: x.Raw).collect()

Capture iframe load complete event

Step 1: Add iframe in template.

<iframe id="uvIFrame" src="www.google.com"></iframe>

Step 2: Add load listener in Controller.

document.querySelector('iframe#uvIFrame').addEventListener('load', function () {
  $scope.loading = false;
  $scope.$apply();
});

How to inspect FormData?

I use the formData.entries() method. I'm not sure about all browser support, but it works fine on Firefox.

Taken from https://developer.mozilla.org/en-US/docs/Web/API/FormData/entries

// Create a test FormData object
var formData = new FormData();
formData.append('key1','value1');
formData.append('key2','value2');

// Display the key/value pairs
for (var pair of formData.entries())
{
 console.log(pair[0]+ ', '+ pair[1]); 
}

There is also formData.get() and formData.getAll() with wider browser support, but they only bring up the Values and not the Key. See the link for more info.

How to convert a command-line argument to int?

Like that we can do....

int main(int argc, char *argv[]) {

    int a, b, c;
    *// Converting string type to integer type
    // using function "atoi( argument)"* 

    a = atoi(argv[1]);     
    b = atoi(argv[2]);
    c = atoi(argv[3]);

 }

Setting DIV width and height in JavaScript

If you remove the javascript: prefix and remove the parts for the unknown ids like 'black_fade' from your javascript code, this should work in firefox

Condensed example:

<html>
    <head>
        <script type="text/javascript">
            function show_update_profile() {
               document.getElementById('div_register').style.height= "500px";
               document.getElementById('div_register').style.width= "500px";
               document.getElementById('div_register').style.display='block';
               return true;
           }
        </script>
        <style>
           /* just to show dimensions of div */
           #div_register
           {
                background-color: #cfc;
           }
        </style>
    </head>
    <body>
        <div id="main">
            <input type="button" onclick="show_update_profile();" value="show"/>
        </div>
        <div id="div_register">
            <table>
                <tr>
                   <td>
                     welcome 
                   </td>
                </tr>
            </table>
        </div>
    </body>
</html>

log4net vs. Nlog

You might also consider Microsoft Enterprise Library Logging Block. It comes with nice designer.

How to replace an entire line in a text file by line number

# Replace the line of the given line number with the given replacement in the given file.
function replace-line-in-file() {
    local file="$1"
    local line_num="$2"
    local replacement="$3"

    # Escape backslash, forward slash and ampersand for use as a sed replacement.
    replacement_escaped=$( echo "$replacement" | sed -e 's/[\/&]/\\&/g' )

    sed -i "${line_num}s/.*/$replacement_escaped/" "$file"
}

Use jQuery to hide a DIV when the user clicks outside of it

So many answers, must be a right of passage to have added one... I didn't see a current (jQuery 3.1.1) answers - so:

$(function() {
    $('body').on('mouseup', function() {
        $('#your-selector').hide();
    });
});

How to filter Pandas dataframe using 'in' and 'not in' like in SQL

Alternative solution that uses .query() method:

In [5]: df.query("countries in @countries")
Out[5]:
  countries
1        UK
3     China

In [6]: df.query("countries not in @countries")
Out[6]:
  countries
0        US
2   Germany

jQuery - trapping tab select event

Simply use the on click event for tab shown.

$(document).on('shown.bs.tab', 'a[href="#tab"]', function (){
});

Deleting a local branch with Git

If you have created multiple worktrees with git worktree, you'll need to run git prune before you can delete the branch

Sleeping in a batch file

Using the ping method as outlined is how I do it when I can't (or don't want to) add more executables or install any other software.

You should be pinging something that isn't there, and using the -w flag so that it fails after that amount of time, not pinging something that is there (like localhost) -n times. This allows you to handle time less than a second, and I think it's slightly more accurate.

e.g.

(test that 1.1.1.1 isn't taken)

ECHO Waiting 15 seconds

PING 1.1.1.1 -n 1 -w 15000 > NUL
  or
PING -n 15 -w 1000 127.1 >NUL

fail to change placeholder color with Bootstrap 3

Bootstrap has 3 lines of CSS, within your bootstrap.css generated file that control the placeholder text color:

.form-control::-moz-placeholder {
  color: #999999;
  opacity: 1;
}
.form-control:-ms-input-placeholder {
  color: #999999;
}
.form-control::-webkit-input-placeholder {
  color: #999999;
}

Now if you add this to your own CSS file it won't override bootstrap's because it is less specific. So assmuning your form inside a then add that to your CSS:

form .form-control::-moz-placeholder {
  color: #fff;
  opacity: 1;
}
form .form-control:-ms-input-placeholder {
  color: #fff;
}
form .form-control::-webkit-input-placeholder {
  color: #fff;
}

Voila that will override bootstrap's CSS.

How can I install a .ipa file to my iPhone simulator

You can run the application file of project in simulator - not .ipa file.

You can get it from:

Libraries-->Applicationsupport-->iphone simulator-->4.3(its ur simulator version)-->applications-->then u can see many files like 0CD04F.... find out your application file through open it.

You can copy the file to your system(which system simulator u need run ) location Libraries-->Applicationsupport-->iphone simulator-->4.3(its your simulator version)-->applications-->

Then open the simulator 4.3 (its your simulator version where you pasted). You can see the application installed there.


Getting from other people:

Please tell them to find out Libraries-->Applicationsupport-->iphone simulator-->4.3(its ur simulator version)-->applications-->then you can see many files like 0CD04F.... from their system and receive that file from them.

After they have got the file, please copy and paste the file in to your system `Libraries-->Applicationsupport-->iphone simulator-->4.3(its your simulator version)-->applications-->(paste the file here).

Then you can see the app is installed in your system simulator and you can run it after clicking the file.

Connecting to remote MySQL server using PHP

This maybe not the answer to poster's question.But this may helpful to people whose face same situation with me:

The client have two network cards,a wireless one and a normal one. The ping to server can be succeed.However telnet serverAddress 3306 would fail. And would complain

Can't connect to MySQL server on 'xxx.xxx.xxx.xxx' (10060)

when try to connect to server.So I forbidden the normal network adapters. And tried telnet serverAddress 3306 it works.And then it work when connect to MySQL server.

count files in specific folder and display the number into 1 cel

Try below code :

Assign the path of the folder to variable FolderPath before running the below code.

Sub sample()

    Dim FolderPath As String, path As String, count As Integer
    FolderPath = "C:\Documents and Settings\Santosh\Desktop"

    path = FolderPath & "\*.xls"

    Filename = Dir(path)

    Do While Filename <> ""
       count = count + 1
        Filename = Dir()
    Loop

    Range("Q8").Value = count
    'MsgBox count & " : files found in folder"
End Sub

Validate IPv4 address in Java

There is also an undocumented utility class sun.net.util.IPAddressUtil, which you should not actually use, although it might be useful in a quick one-off, throw-away utility:

boolean isIP = IPAddressUtil.isIPv4LiteralAddress(ipAddressString);

Internally, this is the utility class InetAddress uses to parse IP addresses.

Note that this will return true for strings like "123", which, technically are valid IPv4 addresses, just not in dot-decimal notation.

Java: Literal percent sign in printf statement

The percent sign is escaped using a percent sign:

System.out.printf("%s\t%s\t%1.2f%%\t%1.2f%%\n",ID,pattern,support,confidence);

The complete syntax can be accessed in java docs. This particular information is in the section Conversions of the first link.

The reason the compiler is generating an error is that only a limited amount of characters may follow a backslash. % is not a valid character.

Get Selected value from Multi-Value Select Boxes by jquery-select2?

You should try this code.

 $("#multiple_Package_Ids_checkboxes").on('change', function (e) { 
        var totAmt = 0;
        $.each($(this).find(":selected"), function (i, item) { 
            totAmt += $(item).data("price");
            });
        $("#PackTotAmt").text(totAmt);
    }); 

What are the true benefits of ExpandoObject?

Interop with other languages founded on the DLR is #1 reason I can think of. You can't pass them a Dictionary<string, object> as it's not an IDynamicMetaObjectProvider. Another added benefit is that it implements INotifyPropertyChanged which means in the databinding world of WPF it also has added benefits beyond what Dictionary<K,V> can provide you.

How can I get my webapp's base URL in ASP.NET MVC?

add this function in static class in project like utility class:

utility.cs content:

public static class Utility
{
    public static string GetBaseUrl()
    {
        var request = HttpContext.Current.Request;
        var urlHelper = new UrlHelper(request.RequestContext);
        var baseUrl = $"{request.Url.Scheme}://{request.Url.Authority}{urlHelper.Content("~")}";
        return baseUrl;
    }
}

use this code any where and enjoy it:

var baseUrl = Utility.GetBaseUrl();

How to get all values from python enum class?

You can do the following:

[e.value for e in Color]

exec failed because the name not a valid identifier?

As was in my case if your sql is generated by concatenating or uses converts then sql at execute need to be prefixed with letter N as below

e.g.

Exec N'Select bla..' 

the N defines string literal is unicode.

Extract a subset of a dataframe based on a condition involving a field

Here are the two main approaches. I prefer this one for its readability:

bar <- subset(foo, location == "there")

Note that you can string together many conditionals with & and | to create complex subsets.

The second is the indexing approach. You can index rows in R with either numeric, or boolean slices. foo$location == "there" returns a vector of T and F values that is the same length as the rows of foo. You can do this to return only rows where the condition returns true.

foo[foo$location == "there", ]

Converting an OpenCV Image to Black and White

Approach 1

While converting a gray scale image to a binary image, we usually use cv2.threshold() and set a threshold value manually. Sometimes to get a decent result we opt for Otsu's binarization.

I have a small hack I came across while reading some blog posts.

  1. Convert your color (RGB) image to gray scale.
  2. Obtain the median of the gray scale image.
  3. Choose a threshold value either 33% above the median

enter image description here

Why 33%?

This is because 33% works for most of the images/data-set.

You can also work out the same approach by replacing median with the mean.

Approach 2

Another approach would be to take an x number of standard deviations (std) from the mean, either on the positive or negative side; and set a threshold. So it could be one of the following:

  • th1 = mean - (x * std)
  • th2 = mean + (x * std)

Note: Before applying threshold it is advisable to enhance the contrast of the gray scale image locally (See CLAHE).

grep regex whitespace behavior

This looks like a behavior difference in the handling of \s between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).

Note:

GNU grep 2.5.4
echo "foo bar" | grep "\s"
   (doesn't match)

whereas

GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar

Probably less trouble (as \s is not documented):

Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar

My advice is to avoid using \s ... use [ \t]* or [[:space:]] or something like it instead.