Programs & Examples On #Delphi 2006

Delphi 2006 is a specific version of Delphi. Use this tag for issues related specifically to development in Delphi 2006.

jQuery get specific option tag text

I was looking for getting val by internal field name instead of ID and came from google to this post which help but did not find the solution I need, but I got the solution and here it is:

So this might help somebody looking for selected value with field internal name instead of using long id for SharePoint lists:

var e = $('select[title="IntenalFieldName"] option:selected').text(); 

What is the difference between int, Int16, Int32 and Int64?

The only real difference here is the size. All of the int types here are signed integer values which have varying sizes

  • Int16: 2 bytes
  • Int32 and int: 4 bytes
  • Int64 : 8 bytes

There is one small difference between Int64 and the rest. On a 32 bit platform assignments to an Int64 storage location are not guaranteed to be atomic. It is guaranteed for all of the other types.

Typescript empty object for a typed variable

Note that using const user = {} as UserType just provides intellisense but at runtime user is empty object {} and has no property inside. that means user.Email will give undefined instead of ""

type UserType = {
    Username: string;
    Email: string;
}

So, use class with constructor for actually creating objects with default properties.

type UserType = {
  Username: string;
  Email: string;
};

class User implements UserType {
  constructor() {
    this.Username = "";
    this.Email = "";
  }

  Username: string;
  Email: string;
}

const myUser = new User();
console.log(myUser); // output: {Username: "", Email: ""}
console.log("val: "+myUser.Email); // output: ""

You can also use interface instead of type

interface UserType {
  Username: string;
  Email: string;
};

...and rest of code remains same.


Actually, you can even skip the constructor part and use it like this:

class User implements UserType {
      Username = ""; // will be added to new obj
      Email: string; // will not be added
}

const myUser = new User();
console.log(myUser); // output: {Username: ""}

Using the Web.Config to set up my SQL database connection string?

Add this to your web config and change the catalog name which is your database name:

  <connectionStrings>
    <add name="MyConnectionString" connectionString="Data Source=SERGIO-DESKTOP\SQLEXPRESS;Initial Catalog=YourDatabaseName;Integrated Security=True;"/></connectionStrings>

Reference System.Configuration assembly in your project.

Here is how you retrieve connection string from the config file:

System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

What is the hamburger menu icon called and the three vertical dots icon called?

Look at this photo, it says "Kebab Menu" is a correct answer:

enter image description here

per comment below, sourced from Luke Wroblewski: https://twitter.com/lukew/status/591296890030915585/photo/1

best practice font size for mobile

The whole thing to em is, that the size is relative to the base. So I would say you could keep the font sizes by altering the base.

Example: If you base is 16px, and p is .75em (which is 12px) you would have to raise the base to about 20px. In this case p would then equal about 15px which is the minimum I personally require for mobile phones.

PHP Session Destroy on Log Out Button

The folder being password protected has nothing to do with PHP!

The method being used is called "Basic Authentication". There are no cross-browser ways to "logout" from it, except to ask the user to close and then open their browser...

Here's how you you could do it in PHP instead (fully remove your Apache basic auth in .htaccess or wherever it is first):

login.php:

<?php
session_start();
//change 'valid_username' and 'valid_password' to your desired "correct" username and password
if (! empty($_POST) && $_POST['user'] === 'valid_username' && $_POST['pass'] === 'valid_password')
{
    $_SESSION['logged_in'] = true;
    header('Location: /index.php');
}
else
{
    ?>

    <form method="POST">
    Username: <input name="user" type="text"><br>
    Password: <input name="pass" type="text"><br><br>
    <input type="submit" value="submit">
    </form>

    <?php
}

index.php

<?php
session_start();
if (! empty($_SESSION['logged_in']))
{
    ?>

    <p>here is my super-secret content</p>
    <a href='logout.php'>Click here to log out</a>

    <?php
}
else
{
    echo 'You are not logged in. <a href="login.php">Click here</a> to log in.';
}

logout.php:

<?php
session_start();
session_destroy();
echo 'You have been logged out. <a href="/">Go back</a>';

Obviously this is a very basic implementation. You'd expect the usernames and passwords to be in a database, not as a hardcoded comparison. I'm just trying to give you an idea of how to do the session thing.

Hope this helps you understand what's going on.

How to Parse JSON Array with Gson

You can easily do this in Kotlin using the following code:

val fileData = "your_json_string"
val gson = GsonBuilder().create()
val packagesArray = gson.fromJson(fileData , Array<YourClass>::class.java).toList()

Basically, you only need to provide an Array of YourClass objects.

Angular HTML binding

You can use the Following two ways.

<div [innerHTML]="myVal"></div>

or

<div innerHTML="{{myVal}}"></div>

Allowed memory size of X bytes exhausted

This problem is happend because of php.ini defined limit was exided but have lot's of solution for this but simple one is to find your local servers folder and on that find the php folder and in that folder have php.ini file which have all declaration of these type setups. You just need to find one and change that value. But in this situation have one big problem once you change in your localhost file but what about server when you want to put your site on server it again produce same problem and you again follow the same for server. But you also know about .htaccess file this is one of the best and single place to do a lot's of things without changing core files. Like you change www routing, removing .php or other extentions from url or add one. Same like that you also difine default values of php.ini here like this - First you need to open the .htaccess file from your root directory or if you don't have this file so create one on root directory of your site and paste this code on it -

php_value upload_max_filesize 1000M
php_value post_max_size 99500M
php_value memory_limit 500M
php_value max_execution_time 300

after changes if you want to check the changes just run the php code

<?php phpinfo(); ?> 

it will show you the php cofigrations all details. So you find your changes.

Note: for defining unlimited just add -1 like php_value memory_limit -1 It's not good and most of the time slow down your server. But if you like to be limit less then this one option is also fit for you. If after refresh your page changes will not reflect you must restart your local server once for changes.

Good Luck. Hope it will help. Want to download the .htaccess file click this.

ant build.xml file doesn't exist

If you couldn't find the build.xml file in your project then you have to build it to be able to debug it and get your .apk

you can use this command-line to build:

android update project -p "project full path"

where "Project full path" -- Give your full path of your project location

after this you will find the build.xml then you can debug it.

Login to remote site with PHP cURL

I had let this go for a good while but revisited it later. Since this question is viewed regularly. This is eventually what I ended up using that worked for me.

define("DOC_ROOT","/path/to/html");
//username and password of account
$username = trim($values["email"]);
$password = trim($values["password"]);

//set the directory for the cookie using defined document root var
$path = DOC_ROOT."/ctemp";
//build a unique path with every request to store. the info per user with custom func. I used this function to build unique paths based on member ID, that was for my use case. It can be a regular dir.
//$path = build_unique_path($path); // this was for my use case

//login form action url
$url="https://www.example.com/login/action"; 
$postinfo = "email=".$username."&password=".$password;

$cookie_file_path = $path."/cookie.txt";

$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_NOBODY, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
//set the cookie the site has for certain features, this is optional
curl_setopt($ch, CURLOPT_COOKIE, "cookiename=0");
curl_setopt($ch, CURLOPT_USERAGENT,
    "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $_SERVER['REQUEST_URI']);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postinfo);
curl_exec($ch);

//page with the content I want to grab
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/page/");
//do stuff with the info with DomDocument() etc
$html = curl_exec($ch);
curl_close($ch);

Update: This code was never meant to be a copy and paste. It was to show how I used it for my specific use case. You should adapt it to your code as needed. Such as directories, vars etc

How can I declare optional function parameters in JavaScript?

Update

With ES6, this is possible in exactly the manner you have described; a detailed description can be found in the documentation.

Old answer

Default parameters in JavaScript can be implemented in mainly two ways:

function myfunc(a, b)
{
    // use this if you specifically want to know if b was passed
    if (b === undefined) {
        // b was not passed
    }
    // use this if you know that a truthy value comparison will be enough
    if (b) {
        // b was passed and has truthy value
    } else {
        // b was not passed or has falsy value
    }
    // use this to set b to a default value (using truthy comparison)
    b = b || "default value";
}

The expression b || "default value" evaluates the value AND existence of b and returns the value of "default value" if b either doesn't exist or is falsy.

Alternative declaration:

function myfunc(a)
{
    var b;

    // use this to determine whether b was passed or not
    if (arguments.length == 1) {
        // b was not passed
    } else {
        b = arguments[1]; // take second argument
    }
}

The special "array" arguments is available inside the function; it contains all the arguments, starting from index 0 to N - 1 (where N is the number of arguments passed).

This is typically used to support an unknown number of optional parameters (of the same type); however, stating the expected arguments is preferred!

Further considerations

Although undefined is not writable since ES5, some browsers are known to not enforce this. There are two alternatives you could use if you're worried about this:

b === void 0;
typeof b === 'undefined'; // also works for undeclared variables

How to create a DataFrame of random integers with Pandas?

The recommended way to create random integers with NumPy these days is to use numpy.random.Generator.integers. (documentation)

import numpy as np
import pandas as pd

rng = np.random.default_rng()
df = pd.DataFrame(rng.integers(0, 100, size=(100, 4)), columns=list('ABCD'))
df
----------------------
      A    B    C    D
 0   58   96   82   24
 1   21    3   35   36
 2   67   79   22   78
 3   81   65   77   94
 4   73    6   70   96
... ...  ...  ...  ...
95   76   32   28   51
96   33   68   54   77
97   76   43   57   43
98   34   64   12   57
99   81   77   32   50
100 rows × 4 columns

Checking oracle sid and database name

I presume SELECT user FROM dual; should give you the current user

and SELECT sys_context('userenv','instance_name') FROM dual; the name of the instance

I believe you can get SID as SELECT sys_context('USERENV', 'SID') FROM DUAL;

Taking multiple inputs from user in python

My first impression was that you were wanting a looping command-prompt with looping user-input inside of that looping command-prompt. (Nested user-input.) Maybe it's not what you wanted, but I already wrote this answer before I realized that. So, I'm going to post it in case other people (or even you) find it useful.

You just need nested loops with an input statement at each loop's level.

For instance,

data=""
while 1:
    data=raw_input("Command: ")
    if data in ("test", "experiment", "try"):
        data2=""
        while data2=="":
            data2=raw_input("Which test? ")
        if data2=="chemical":
            print("You chose a chemical test.")
        else:
            print("We don't have any " + data2 + " tests.")
    elif data=="quit":
        break
    else:
        pass

Remove all spaces from a string in SQL Server

Reference taken from this blog:

First, Create sample table and data:

CREATE TABLE tbl_RemoveExtraSpaces
(
     Rno INT
     ,Name VARCHAR(100)
)
GO

INSERT INTO tbl_RemoveExtraSpaces VALUES (1,'I    am     Anvesh   Patel')
INSERT INTO tbl_RemoveExtraSpaces VALUES (2,'Database   Research and     Development  ')
INSERT INTO tbl_RemoveExtraSpaces VALUES (3,'Database    Administrator     ')
INSERT INTO tbl_RemoveExtraSpaces VALUES (4,'Learning    BIGDATA    and       NOSQL ')
GO

Script to SELECT string without Extra Spaces:

SELECT
     [Rno]
    ,[Name] AS StringWithSpace
    ,LTRIM(RTRIM(REPLACE(REPLACE(REPLACE([Name],CHAR(32),'()'),')(',''),'()',CHAR(32)))) AS StringWithoutSpace
FROM tbl_RemoveExtraSpaces

Result:

Rno         StringWithSpace                                 StringWithoutSpace
----------- -----------------------------------------  ---------------------------------------------
1           I    am     Anvesh   Patel                      I am Anvesh Patel
2           Database   Research and     Development         Database Research and Development
3           Database    Administrator                       Database Administrator
4           Learning    BIGDATA    and       NOSQL          Learning BIGDATA and NOSQL

how to display a div triggered by onclick event

If you have the ID of the div, try this:

  <input type='submit' onclick='$("#div_id").show()'>

Is there a better way to compare dictionary values

Uhm, you are describing dict1 == dict2 ( check if boths dicts are equal )

But what your code does is all( dict1[k]==dict2[k] for k in dict1 ) ( check if all entries in dict1 are equal to those in dict2 )

Iterating over a 2 dimensional python list

Use zip and itertools.chain. Something like:

>>> from itertools import chain
>>> l = chain.from_iterable(zip(*l))
<itertools.chain object at 0x104612610>
>>> list(l)
['0,0', '1,0', '2,0', '0,1', '1,1', '2,1']

Is Safari on iOS 6 caching $.ajax results?

While adding cache-buster parameters to make the request look different seems like a solid solution, I would advise against it, as it would hurt any application that relies on actual caching taking place. Making the APIs output the correct headers is the best possible solution, even if that's slightly more difficult than adding cache busters to the callers.

Search an array for matching attribute

you can also use the Array.find feature of es6. the doc is here

return restaurants.find(item => {
   return item.restaurant.food == 'chicken'
})

Find duplicate values in R

A terser way, either with rev :

x[!(!duplicated(x) & rev(!duplicated(rev(x))))]

... rather than fromLast:

x[!(!duplicated(x) & !duplicated(x, fromLast = TRUE))]

... and as a helper function to provide either logical vector or elements from original vector :

duplicates <- function(x, as.bool = FALSE) {
    is.dup <- !(!duplicated(x) & rev(!duplicated(rev(x))))
    if (as.bool) { is.dup } else { x[is.dup] }
}

Treating vectors as data frames to pass to table is handy but can get difficult to read, and the data.table solution is fine but I'd prefer base R solutions for dealing with simple vectors like IDs.

psql: FATAL: Ident authentication failed for user "postgres"

If you've done all this and it still doesn't work, check the expiry for that user:

Postgres password authentication fails

Difference between onStart() and onResume()

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

How do I animate constraint changes?

// Step 1, update your constraint
self.myOutletToConstraint.constant = 50; // New height (for example)

// Step 2, trigger animation
[UIView animateWithDuration:2.0 animations:^{

    // Step 3, call layoutIfNeeded on your animated view's parent
    [self.view layoutIfNeeded];
}];

Export pictures from excel file into jpg using VBA

Here is another cool way to do it- using en external viewer that accepts command line switches (IrfanView in this case) : * I based the loop on what Michal Krzych has written above.

Sub ExportPicturesToFiles()
    Const saveSceenshotTo As String = "C:\temp\"
    Const pictureFormat As String = ".jpg"

    Dim pic As Shape
    Dim sFileName As String
    Dim i As Long

    i = 1

    For Each pic In ActiveSheet.Shapes
        pic.Copy
        sFileName = saveSceenshotTo & Range("A" & i).Text & pictureFormat

        Call ExportPicWithIfran(sFileName)

        i = i + 1
    Next
End Sub

Public Sub ExportPicWithIfran(sSaveAsPath As String)
    Const sIfranPath As String = "C:\Program Files\IrfanView\i_view32.exe"
    Dim sRunIfran As String

    sRunIfran = sIfranPath & " /clippaste /convert=" & _
                            sSaveAsPath & " /killmesoftly"

    ' Shell is no good here. If you have more than 1 pic, it will
    ' mess things up (pics will over run other pics, becuase Shell does
    ' not make vba wait for the script to finish).
    ' Shell sRunIfran, vbHide

    ' Correct way (it will now wait for the batch to finish):
    call MyShell(sRunIfran )
End Sub

Edit:

  Private Sub MyShell(strShell As String)
  ' based on:
    ' http://stackoverflow.com/questions/15951837/excel-vba-wait-for-shell-command-to-complete
   ' by Nate Hekman

    Dim wsh As Object
    Dim waitOnReturn As Boolean:
    Dim windowStyle As VbAppWinStyle

    Set wsh = VBA.CreateObject("WScript.Shell")
    waitOnReturn = True
    windowStyle = vbHide

    wsh.Run strShell, windowStyle, waitOnReturn
End Sub

How to identify unused CSS definitions from multiple CSS files in a project

Google Chrome Developer Tools has (a currently experimental) feature called CSS Overview which will allow you to find unused CSS rules.

To enable it follow these steps:

  1. Open up DevTools (Command+Option+I on Mac; Control+Shift+I on Windows)
  2. Head over to DevTool Settings (Function+F1 on Mac; F1 on Windows)
  3. Click open the Experiments section
  4. Enable the CSS Overview option

enter image description here

Split function equivalent in T-SQL?

here is the split function that u asked

CREATE FUNCTION [dbo].[split](
          @delimited NVARCHAR(MAX),
          @delimiter NVARCHAR(100)
        ) RETURNS @t TABLE (id INT IDENTITY(1,1), val NVARCHAR(MAX))
        AS
        BEGIN
          DECLARE @xml XML
          SET @xml = N'<t>' + REPLACE(@delimited,@delimiter,'</t><t>') + '</t>'

          INSERT INTO @t(val)
          SELECT  r.value('.','varchar(MAX)') as item
          FROM  @xml.nodes('/t') as records(r)
          RETURN
        END

execute the function like this

select * from dbo.split('1,2,3,4,5,6,7,8,9,10,11,12,13,14,15',',')

<div style display="none" > inside a table not working

Semantically what you are trying is invalid html, table element cannot have a div element as a direct child. What you can do is, get your div element inside a td element and than try to hide it

How to terminate script execution when debugging in Google Chrome?

If you are encountering this while using the debugger statement,

debugger;

... then I think the page will continue running forever until the js runtime yields, or the next break. Assuming you're in break-on-error mode (the pause-icon toggle), you can ensure a break happens by instead doing something like:

debugger;throw 1;

or maybe call a non-existent function:

debugger;z();

(Of course this doesn't help if you are trying to step through functions, though perhaps you could dynamically add in a throw 1 or z() or somesuch in the Sources panel, ctrl-S to save, and then ctrl-R to refresh... this may however skip one breakpoint, but may work if you're in a loop.)

If you are doing a loop and expect to trigger the debugger statement again, you could just type throw 1 instead.

throw 1;

Then when you hit ctrl-R, the next throw will be hit, and the page will refresh.

(tested with Chrome v38, circa Apr 2017)

Angularjs autocomplete from $http

the easiest way to do that in angular or angularjs without external modules or directives is using list and datalist HTML5. You just get a json and use ng-repeat for feeding the options in datalist. The json you can fetch it from ajax.

in this example:

  • ctrl.query is the query that you enter when you type.
  • ctrl.msg is the message that is showing in the placeholder
  • ctrl.dataList is the json fetched

then you can add filters and orderby in the ng-reapet

!! list and datalist id must have the same name !!

 <input type="text" list="autocompleList" ng-model="ctrl.query" placeholder={{ctrl.msg}}>
<datalist id="autocompleList">
        <option ng-repeat="Ids in ctrl.dataList value={{Ids}}  >
</datalist>

UPDATE : is native HTML5 but be carreful with the type browser and version. check it out : https://caniuse.com/#search=datalist.

Run function from the command line

Use the python-c tool (pip install python-c) and then simply write:

$ python-c foo 'hello()'

or in case you have no function name clashes in your python files:

$ python-c 'hello()'

Iterate through every file in one directory

Dir.new('/my/dir').each do |name|
  ...
end

What size should TabBar images be?

According to my practice, I use the 40 x 40 for standard iPad tab bar item icon, 80 X 80 for retina.

From the Apple reference. https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/BarIcons.html#//apple_ref/doc/uid/TP40006556-CH21-SW1

If you want to create a bar icon that looks like it's related to the iOS 7 icon family, use a very thin stroke to draw it. Specifically, a 2-pixel stroke (high resolution) works well for detailed icons and a 3-pixel stroke works well for less detailed icons.

Regardless of the icon’s visual style, create a toolbar or navigation bar icon in the following sizes:

About 44 x 44 pixels About 22 x 22 pixels (standard resolution) Regardless of the icon’s visual style, create a tab bar icon in the following sizes:

About 50 x 50 pixels (96 x 64 pixels maximum) About 25 x 25 pixels (48 x 32 pixels maximum) for standard resolution

Java - get index of key in HashMap?

If all you are trying to do is get the value out of the hashmap itself, you can do something like the following:

for (Object key : map.keySet()) {
    Object value = map.get(key);
    //TODO: this
}

Or, you can iterate over the entries of a map, if that is what you are interested in:

for (Map.Entry<Object, Object> entry : map.entrySet()) {
    Object key = entry.getKey();
    Object value = entry.getValue();
    //TODO: other cool stuff
}

As a community, we might be able to give you better/more appropriate answers if we had some idea why you needed the indexes or what you thought the indexes could do for you.

Update Git submodule to latest commit on origin

The git submodule update command actually tells Git that you want your submodules to each check out the commit already specified in the index of the superproject. If you want to update your submodules to the latest commit available from their remote, you will need to do this directly in the submodules.

So in summary:

# Get the submodule initially
git submodule add ssh://bla submodule_dir
git submodule init

# Time passes, submodule upstream is updated
# and you now want to update

# Change to the submodule directory
cd submodule_dir

# Checkout desired branch
git checkout master

# Update
git pull

# Get back to your project root
cd ..

# Now the submodules are in the state you want, so
git commit -am "Pulled down update to submodule_dir"

Or, if you're a busy person:

git submodule foreach git pull origin master

Ajax Success and Error function failure

I was having the same issue and fixed it by simply adding a dataType = "text" line to my ajax call. Make the dataType match the response you expect to get back from the server (your "insert successful" or "something went wrong" error message).

Deny all, allow only one IP through htaccess

Just in addition to @David Brown´s answer, if you want to block an IP, you must first allow all then block the IPs as such:

    <RequireAll>
      Require all granted
      Require not ip 10.0.0.0/255.0.0.0
      Require not ip 172.16.0.0/12
      Require not ip 192.168
    </RequireAll>

First line allows all
Second line blocks from 10.0.0.0 to 10.255.255.255
Third line blocks from 172.16.0.0 to 172.31.255.255
Fourth line blocks from 192.168.0.0 to 192.168.255.255

You may use any of the notations mentioned above to suit you CIDR needs.

How to install a Mac application using Terminal

Probably not exactly your issue..

Do you have any spaces in your package path? You should wrap it up in double quotes to be safe, otherwise it can be taken as two separate arguments

sudo installer -store -pkg "/User/MyName/Desktop/helloWorld.pkg" -target /

Java 8 Lambda Stream forEach with multiple statements

List<String> items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
items.add("D");
items.add("E");

//lambda
//Output : A,B,C,D,E
items.forEach(item->System.out.println(item));

//Output : C
items.forEach(item->{
    System.out.println(item);
    System.out.println(item.toLowerCase());
  }
});

Nullable DateTime conversion

Cast the null literal: (DateTime?)null or (Nullable<DateTime>)null.

You can also use default(DateTime?) or default(Nullable<DateTime>)

And, as other answers have noted, you can also apply the cast to the DateTime value rather than to the null literal.

EDIT (adapted from my comment to Prutswonder's answer):

The point is that the conditional operator does not consider the type of its assignment target, so it will only compile if there is an implicit conversion from the type of its second operand to the type of its third operand, or from the type of its third operand to the type of its second operand.

For example, this won't compile:

bool b = GetSomeBooleanValue();
object o = b ? "Forty-two" : 42;

Casting either the second or third operand to object, however, fixes the problem, because there is an implicit conversion from int to object and also from string to object:

object o = b ? "Forty-two" : (object)42;

or

object o = b ? (object)"Forty-two" : 42;

How to save MySQL query output to excel or .txt file?

You can write following codes to achieve this task:

SELECT ... FROM ... WHERE ... 
INTO OUTFILE 'textfile.csv'
FIELDS TERMINATED BY '|'

It export the result to CSV and then export it to excel sheet.

Is it possible to modify a registry entry via a .bat/.cmd script?

In addition to reg.exe, I highly recommend that you also check out powershell, its vastly more capable in its registry handling.

Printf long long int in C with GCC?

If you are on windows and using mingw, gcc uses the win32 runtime, where printf needs %I64d for a 64 bit integer. (and %I64u for an unsinged 64 bit integer)

For most other platforms you'd use %lld for printing a long long. (and %llu if it's unsigned). This is standarized in C99.

gcc doesn't come with a full C runtime, it defers to the platform it's running on - so the general case is that you need to consult the documentation for your particular platform - independent of gcc.

Pandas: rolling mean by time interval

I just had the same question but with irregularly spaced datapoints. Resample is not really an option here. So I created my own function. Maybe it will be useful for others too:

from pandas import Series, DataFrame
import pandas as pd
from datetime import datetime, timedelta
import numpy as np

def rolling_mean(data, window, min_periods=1, center=False):
    ''' Function that computes a rolling mean

    Parameters
    ----------
    data : DataFrame or Series
           If a DataFrame is passed, the rolling_mean is computed for all columns.
    window : int or string
             If int is passed, window is the number of observations used for calculating 
             the statistic, as defined by the function pd.rolling_mean()
             If a string is passed, it must be a frequency string, e.g. '90S'. This is
             internally converted into a DateOffset object, representing the window size.
    min_periods : int
                  Minimum number of observations in window required to have a value.

    Returns
    -------
    Series or DataFrame, if more than one column    
    '''
    def f(x):
        '''Function to apply that actually computes the rolling mean'''
        if center == False:
            dslice = col[x-pd.datetools.to_offset(window).delta+timedelta(0,0,1):x]
                # adding a microsecond because when slicing with labels start and endpoint
                # are inclusive
        else:
            dslice = col[x-pd.datetools.to_offset(window).delta/2+timedelta(0,0,1):
                         x+pd.datetools.to_offset(window).delta/2]
        if dslice.size < min_periods:
            return np.nan
        else:
            return dslice.mean()

    data = DataFrame(data.copy())
    dfout = DataFrame()
    if isinstance(window, int):
        dfout = pd.rolling_mean(data, window, min_periods=min_periods, center=center)
    elif isinstance(window, basestring):
        idx = Series(data.index.to_pydatetime(), index=data.index)
        for colname, col in data.iterkv():
            result = idx.apply(f)
            result.name = colname
            dfout = dfout.join(result, how='outer')
    if dfout.columns.size == 1:
        dfout = dfout.ix[:,0]
    return dfout


# Example
idx = [datetime(2011, 2, 7, 0, 0),
       datetime(2011, 2, 7, 0, 1),
       datetime(2011, 2, 7, 0, 1, 30),
       datetime(2011, 2, 7, 0, 2),
       datetime(2011, 2, 7, 0, 4),
       datetime(2011, 2, 7, 0, 5),
       datetime(2011, 2, 7, 0, 5, 10),
       datetime(2011, 2, 7, 0, 6),
       datetime(2011, 2, 7, 0, 8),
       datetime(2011, 2, 7, 0, 9)]
idx = pd.Index(idx)
vals = np.arange(len(idx)).astype(float)
s = Series(vals, index=idx)
rm = rolling_mean(s, window='2min')

How to download Google Play Services in an Android emulator?

I got it working by

  • Installing the Google Play Services through the Android SDK Manager
  • Using a Galaxy Nexus Device (4.65", 720 x 1280: xhdpi)
  • Targeting the Android 4.2.2 Google API Level 17

How do I cancel form submission in submit button onclick event?

Sometimes onsubmit wouldn't work with asp.net.

I solved it with very easy way.

if we have such a form

<form method="post" name="setting-form" >
   <input type="text" id="UserName" name="UserName" value="" 
      placeholder="user name" >
   <input type="password" id="Password" name="password" value="" placeholder="password" >
   <div id="remember" class="checkbox">
    <label>remember me</label>
    <asp:CheckBox ID="RememberMe" runat="server" />
   </div>
   <input type="submit" value="login" id="login-btn"/>
</form>

You can now catch get that event before the form postback and stop it from postback and do all the ajax you want using this jquery.

$(document).ready(function () {
            $("#login-btn").click(function (event) {
                event.preventDefault();
                alert("do what ever you want");
            });
 });

change values in array when doing foreach

You can try this if you want to override

var newArray= [444,555,666];
var oldArray =[11,22,33];
oldArray.forEach((name, index) => oldArray [index] = newArray[index]);
console.log(newArray);

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

My site configuration file is example.conf in sites-available folder So you can create a symbolic link as

ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/

enum to string in modern C++11 / C++14 / C++17 and future C++20

I have been frustrated by this problem for a long time too, along with the problem of getting a type converted to string in a proper way. However, for the last problem, I was surprised by the solution explained in Is it possible to print a variable's type in standard C++?, using the idea from Can I obtain C++ type names in a constexpr way?. Using this technique, an analogous function can be constructed for getting an enum value as string:

#include <iostream>
using namespace std;

class static_string
{
    const char* const p_;
    const std::size_t sz_;

public:
    typedef const char* const_iterator;

    template <std::size_t N>
    constexpr static_string(const char(&a)[N]) noexcept
        : p_(a)
        , sz_(N - 1)
    {}

    constexpr static_string(const char* p, std::size_t N) noexcept
        : p_(p)
        , sz_(N)
    {}

    constexpr const char* data() const noexcept { return p_; }
    constexpr std::size_t size() const noexcept { return sz_; }

    constexpr const_iterator begin() const noexcept { return p_; }
    constexpr const_iterator end()   const noexcept { return p_ + sz_; }

    constexpr char operator[](std::size_t n) const
    {
        return n < sz_ ? p_[n] : throw std::out_of_range("static_string");
    }
};

inline std::ostream& operator<<(std::ostream& os, static_string const& s)
{
    return os.write(s.data(), s.size());
}

/// \brief Get the name of a type
template <class T>
static_string typeName()
{
#ifdef __clang__
    static_string p = __PRETTY_FUNCTION__;
    return static_string(p.data() + 30, p.size() - 30 - 1);
#elif defined(_MSC_VER)
    static_string p = __FUNCSIG__;
    return static_string(p.data() + 37, p.size() - 37 - 7);
#endif

}

namespace details
{
    template <class Enum>
    struct EnumWrapper
    {
        template < Enum enu >
        static static_string name()
        {
#ifdef __clang__
            static_string p = __PRETTY_FUNCTION__;
            static_string enumType = typeName<Enum>();
            return static_string(p.data() + 73 + enumType.size(), p.size() - 73 - enumType.size() - 1);
#elif defined(_MSC_VER)
            static_string p = __FUNCSIG__;
            static_string enumType = typeName<Enum>();
            return static_string(p.data() + 57 + enumType.size(), p.size() - 57 - enumType.size() - 7);
#endif
        }
    };
}

/// \brief Get the name of an enum value
template <typename Enum, Enum enu>
static_string enumName()
{
    return details::EnumWrapper<Enum>::template name<enu>();
}

enum class Color
{
    Blue = 0,
    Yellow = 1
};


int main() 
{
    std::cout << "_" << typeName<Color>() << "_"  << std::endl;
    std::cout << "_" << enumName<Color, Color::Blue>() << "_"  << std::endl;
    return 0;
}

The code above has only been tested on Clang (see https://ideone.com/je5Quv) and VS2015, but should be adaptable to other compilers by fiddling a bit with the integer constants. Of course, it still uses macros under the hood, but at least one doesn't need access to the enum implementation.

Create Elasticsearch curl query for not null and not empty("")

You can do that with bool query and combination of must and must_not like this:

GET index/_search
{
    "query": {
        "bool": {
            "must": [
                {"exists": {"field": "field1"}}
            ],
            "must_not": [
                {"term": {"field1": ""}}
            ]
        }
    }
}

I tested this with Elasticsearch 5.6.5 in Kibana.

Convert RGBA PNG to RGB with PIL

import numpy as np
import PIL

def convert_image(image_file):
    image = Image.open(image_file) # this could be a 4D array PNG (RGBA)
    original_width, original_height = image.size

    np_image = np.array(image)
    new_image = np.zeros((np_image.shape[0], np_image.shape[1], 3)) 
    # create 3D array

    for each_channel in range(3):
        new_image[:,:,each_channel] = np_image[:,:,each_channel]  
        # only copy first 3 channels.

    # flushing
    np_image = []
    return new_image

How to read a text file into a string variable and strip newlines?

You could use:

with open('data.txt', 'r') as file:
    data = file.read().replace('\n', '')

Generate list of all possible permutations of a string

Here's a non-recursive version I came up with, in javascript. It's not based on Knuth's non-recursive one above, although it has some similarities in element swapping. I've verified its correctness for input arrays of up to 8 elements.

A quick optimization would be pre-flighting the out array and avoiding push().

The basic idea is:

  1. Given a single source array, generate a first new set of arrays which swap the first element with each subsequent element in turn, each time leaving the other elements unperturbed. eg: given 1234, generate 1234, 2134, 3214, 4231.

  2. Use each array from the previous pass as the seed for a new pass, but instead of swapping the first element, swap the second element with each subsequent element. Also, this time, don't include the original array in the output.

  3. Repeat step 2 until done.

Here is the code sample:

function oxe_perm(src, depth, index)
{
    var perm = src.slice();     // duplicates src.
    perm = perm.split("");
    perm[depth] = src[index];
    perm[index] = src[depth];
    perm = perm.join("");
    return perm;
}

function oxe_permutations(src)
{
    out = new Array();

    out.push(src);

    for (depth = 0; depth < src.length; depth++) {
        var numInPreviousPass = out.length;
        for (var m = 0; m < numInPreviousPass; ++m) {
            for (var n = depth + 1; n < src.length; ++n) {
                out.push(oxe_perm(out[m], depth, n));
            }
        }
    }

    return out;
}

Download and install an ipa from self hosted url on iOS

Answer for Enterprise account with Xcode8

  1. Export the .ipa by checking the "with manifest plist checkbox" and provide the links requested.

  2. Upload the .ipa file and .plist file to the same location of the server (which you provided when exporting .ipa/ which mentioned in the .plist file).

  3. Create the Download Link as given below. url should link to your .plist file location.

    itms-services://?action=download-manifest&url=https://yourdomainname.com/app.plist

  4. Copy this link and paste it in safari browser in your iphone. It will ask to install :D

Create a html button using this full url

In SSRS, why do I get the error "item with same key has already been added" , when I'm making a new report?

I had the same error in a report query. I had columns from different tables with the same name and the prefix for each table (eg: select a.description, b.description, c.description) that runs ok in Oracle, but for the report you must have an unique alias for each column so simply add alias to the fields with the same name (select a.description a_description, b.description b_description and so on)

Swift: How to get substring from start to last index of character

Swift 3, XCode 8

func lastIndexOfCharacter(_ c: Character) -> Int? {
    return range(of: String(c), options: .backwards)?.lowerBound.encodedOffset
}

Since advancedBy(Int) is gone since Swift 3 use String's method index(String.Index, Int). Check out this String extension with substring and friends:

public extension String {

    //right is the first encountered string after left
    func between(_ left: String, _ right: String) -> String? {
        guard let leftRange = range(of: left), let rightRange = range(of: right, options: .backwards)
        , leftRange.upperBound <= rightRange.lowerBound
            else { return nil }
    
        let sub = self.substring(from: leftRange.upperBound)
        let closestToLeftRange = sub.range(of: right)!
        return sub.substring(to: closestToLeftRange.lowerBound)
    }

    var length: Int {
        get {
            return self.characters.count
        }
    }

    func substring(to : Int) -> String {
        let toIndex = self.index(self.startIndex, offsetBy: to)
        return self.substring(to: toIndex)
    }

    func substring(from : Int) -> String {
        let fromIndex = self.index(self.startIndex, offsetBy: from)
        return self.substring(from: fromIndex)
    }

    func substring(_ r: Range<Int>) -> String {
        let fromIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
        let toIndex = self.index(self.startIndex, offsetBy: r.upperBound)
        return self.substring(with: Range<String.Index>(uncheckedBounds: (lower: fromIndex, upper: toIndex)))
    }

    func character(_ at: Int) -> Character {
        return self[self.index(self.startIndex, offsetBy: at)]
    }

    func lastIndexOfCharacter(_ c: Character) -> Int? {
        guard let index = range(of: String(c), options: .backwards)?.lowerBound else
        { return nil }
        return distance(from: startIndex, to: index)
    }
}

UPDATED extension for Swift 5

public extension String {
    
    //right is the first encountered string after left
    func between(_ left: String, _ right: String) -> String? {
        guard
            let leftRange = range(of: left), let rightRange = range(of: right, options: .backwards)
            , leftRange.upperBound <= rightRange.lowerBound
            else { return nil }
        
        let sub = self[leftRange.upperBound...]
        let closestToLeftRange = sub.range(of: right)!            
        return String(sub[..<closestToLeftRange.lowerBound])
    }
    
    var length: Int {
        get {
            return self.count
        }
    }
    
    func substring(to : Int) -> String {
        let toIndex = self.index(self.startIndex, offsetBy: to)
        return String(self[...toIndex])
    }
    
    func substring(from : Int) -> String {
        let fromIndex = self.index(self.startIndex, offsetBy: from)
        return String(self[fromIndex...])
    }
    
    func substring(_ r: Range<Int>) -> String {
        let fromIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
        let toIndex = self.index(self.startIndex, offsetBy: r.upperBound)
        let indexRange = Range<String.Index>(uncheckedBounds: (lower: fromIndex, upper: toIndex))
        return String(self[indexRange])
    }
    
    func character(_ at: Int) -> Character {
        return self[self.index(self.startIndex, offsetBy: at)]
    }
    
    func lastIndexOfCharacter(_ c: Character) -> Int? {
        guard let index = range(of: String(c), options: .backwards)?.lowerBound else
        { return nil }
        return distance(from: startIndex, to: index)
    }
}

Usage:

let text = "www.stackoverflow.com"
let at = text.character(3) // .
let range = text.substring(0..<3) // www
let from = text.substring(from: 4) // stackoverflow.com
let to = text.substring(to: 16) // www.stackoverflow
let between = text.between(".", ".") // stackoverflow
let substringToLastIndexOfChar = text.lastIndexOfCharacter(".") // 17

P.S. It's really odd that developers forced to deal with String.Index instead of plain Int. Why should we bother about internal String mechanics and not just have simple substring() methods?

Loading an image to a <img> from <input file>

Andy E is correct that there is no HTML-based way to do this*; but if you are willing to use Flash, you can do it. The following works reliably on systems that have Flash installed. If your app needs to work on iPhone, then of course you'll need a fallback HTML-based solution.

* (Update 4/22/2013: HTML does now support this, in HTML5. See the other answers.)

Flash uploading also has other advantages -- Flash gives you the ability to show a progress bar as the upload of a large file progresses. (I'm pretty sure that's how Gmail does it, by using Flash behind the scenes, although I may be wrong about that.)

Here is a sample Flex 4 app that allows the user to pick a file, and then displays it:

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
               xmlns:s="library://ns.adobe.com/flex/spark" 
               xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
               creationComplete="init()">
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
    <s:Button x="10" y="10" label="Choose file..." click="showFilePicker()" />
    <mx:Image id="myImage" x="9" y="44"/>
    <fx:Script>
        <![CDATA[
            private var fr:FileReference = new FileReference();

            // Called when the app starts.
            private function init():void
            {
                // Set up event handlers.
                fr.addEventListener(Event.SELECT, onSelect);
                fr.addEventListener(Event.COMPLETE, onComplete);
            }

            // Called when the user clicks "Choose file..."
            private function showFilePicker():void
            {
                fr.browse();
            }

            // Called when fr.browse() dispatches Event.SELECT to indicate
            // that the user has picked a file.
            private function onSelect(e:Event):void
            {
                fr.load(); // start reading the file
            }

            // Called when fr.load() dispatches Event.COMPLETE to indicate
            // that the file has finished loading.
            private function onComplete(e:Event):void
            {
                myImage.data = fr.data; // load the file's data into the Image
            }
        ]]>
    </fx:Script>
</s:Application>

What __init__ and self do in Python?

In short:

  1. self as it suggests, refers to itself- the object which has called the method. That is, if you have N objects calling the method, then self.a will refer to a separate instance of the variable for each of the N objects. Imagine N copies of the variable a for each object
  2. __init__ is what is called as a constructor in other OOP languages such as C++/Java. The basic idea is that it is a special method which is automatically called when an object of that Class is created

Location Services not working in iOS 8

To Access User Location in iOS 8 you will have to add,

NSLocationAlwaysUsageDescription in the Info.plist 

This will ask the user for the permission to get their current location.

ArithmeticException: "Non-terminating decimal expansion; no exact representable decimal result"

From the Java 11 BigDecimal docs:

When a MathContext object is supplied with a precision setting of 0 (for example, MathContext.UNLIMITED), arithmetic operations are exact, as are the arithmetic methods which take no MathContext object. (This is the only behavior that was supported in releases prior to 5.)

As a corollary of computing the exact result, the rounding mode setting of a MathContext object with a precision setting of 0 is not used and thus irrelevant. In the case of divide, the exact quotient could have an infinitely long decimal expansion; for example, 1 divided by 3.

If the quotient has a nonterminating decimal expansion and the operation is specified to return an exact result, an ArithmeticException is thrown. Otherwise, the exact result of the division is returned, as done for other operations.

To fix, you need to do something like this:

a.divide(b, 2, RoundingMode.HALF_UP)

where 2 is the scale and RoundingMode.HALF_UP is rounding mode

For more details see this blog post.

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

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

How to loop through an associative array and get the key?

I use the following loop to get the key and value from an associative array

foreach ($array as $key => $value)
{
  echo "<p>$key = $value</p>";
}

TOMCAT - HTTP Status 404

  1. Click on Window > Show view > Server or right click on the server in "Servers" view, select "Properties".
  2. In the "General" panel, click on the "Switch Location" button.
  3. The "Location: [workspace metadata]" should replace by something else.
  4. Open the Overview screen for the server by double clicking it.
  5. In the Server locations tab , select "Use Tomcat location".
  6. Save the configurations and restart the Server.

You may want to follow the steps above before starting the server. Because server location section goes grayed-unreachable.

server Locations in eclipse view

Implement paging (skip / take) functionality with this query

In order to do this in SQL Server, you must order the query by a column, so you can specify the rows you want.

Example:

select * from table order by [some_column] 
offset 10 rows
FETCH NEXT 10 rows only

And you can't use the "TOP" keyword when doing this.

You can learn more here: https://technet.microsoft.com/pt-br/library/gg699618%28v=sql.110%29.aspx

Time part of a DateTime Field in SQL

Try this in SQL Server 2008:

select *
from some_table t
where convert(time,t.some_datetime_column) = '5pm'

If you want take a random datetime value and adjust it so the time component is 5pm, then in SQL Server 2008 there are a number of ways. First you need start-of-day (e.g., 2011-09-30 00:00:00.000).

  • One technique that works for all versions of Microsoft SQL Server as well as all versions of Sybase is to use convert/3 to convert the datetime value to a varchar that lacks a time component and then back into a datetime value:

    select convert(datetime,convert(varchar,current_timestamp,112),112)
    

The above gives you start-of-day for the current day.

  • In SQL Server 2008, though, you can say something like this:

    select start_of_day =               t.some_datetime_column
                        - convert(time, t.some_datetime_column ) ,
    from some_table t
    

    which is likely faster.

Once you have start-of-day, getting to 5pm is easy. Just add 17 hours to your start-of-day value:

select five_pm = dateadd(hour,17, t.some_datetime_column
                   - convert(time,t.some_datetime_column)
                   )
from some_table t

Change image source in code behind - Wpf

You are all wrong! Why? Because all you need is this code to work:

(image View) / C# Img is : your Image box

Keep this as is, without change ("ms-appx:///) this is code not your app name Images is your folder in your project you can change it. dog.png is your file in your folder, as well as i do my folder 'Images' and file 'dog.png' So the uri is :"ms-appx:///Images/dog.png" and my code :


private void Button_Click(object sender, RoutedEventArgs e)
    {
         img.Source = new BitmapImage(new Uri("ms-appx:///Images/dog.png"));
    }

How to press/click the button using Selenium if the button does not have the Id?

use the text and value attributes instead of the id

driver.findElementByXpath("//input[@value='cancel'][@title='cancel']").click();

similarly for Next.

Setting background colour of Android layout element

Android studio 2.1.2 (or possibly earlier) will let you pick from a color wheel:

Color Wheel in Android Studio

I got this by adding the following to my layout:

android:background="#FFFFFF"

Then I clicked on the FFFFFF color and clicked on the lightbulb that appeared.

Set width to match constraints in ConstraintLayout

You can check your Adapter.

 1 - MyLayoutBinding binding = MyLayoutBinding.inflate(layoutInflater);
 2 - MyLayoutBinding binding = MyLayoutBinding.inflate(layoutInflater, viewGroup, false);

I had a same problem like you when I used 1. You can try 2.

Replace one character with another in Bash

In bash, you can do pattern replacement in a string with the ${VARIABLE//PATTERN/REPLACEMENT} construct. Use just / and not // to replace only the first occurrence. The pattern is a wildcard pattern, like file globs.

string='foo bar qux'
one="${string/ /.}"     # sets one to 'foo.bar qux'
all="${string// /.}"    # sets all to 'foo.bar.qux'

How do multiple clients connect simultaneously to one port, say 80, on a server?

Important:

I'm sorry to say that the response from "Borealid" is imprecise and somewhat incorrect - firstly there is no relation to statefulness or statelessness to answer this question, and most importantly the definition of the tuple for a socket is incorrect.

First remember below two rules:

  1. Primary key of a socket: A socket is identified by {SRC-IP, SRC-PORT, DEST-IP, DEST-PORT, PROTOCOL} not by {SRC-IP, SRC-PORT, DEST-IP, DEST-PORT} - Protocol is an important part of a socket's definition.

  2. OS Process & Socket mapping: A process can be associated with (can open/can listen to) multiple sockets which might be obvious to many readers.

Example 1: Two clients connecting to same server port means: socket1 {SRC-A, 100, DEST-X,80, TCP} and socket2{SRC-B, 100, DEST-X,80, TCP}. This means host A connects to server X's port 80 and another host B also connects to same server X to the same port 80. Now, how the server handles these two sockets depends on if the server is single threaded or multiple threaded (I'll explain this later). What is important is that one server can listen to multiple sockets simultaneously.

To answer the original question of the post:

Irrespective of stateful or stateless protocols, two clients can connect to same server port because for each client we can assign a different socket (as client IP will definitely differ). Same client can also have two sockets connecting to same server port - since such sockets differ by SRC-PORT. With all fairness, "Borealid" essentially mentioned the same correct answer but the reference to state-less/full was kind of unnecessary/confusing.

To answer the second part of the question on how a server knows which socket to answer. First understand that for a single server process that is listening to same port, there could be more than one sockets (may be from same client or from different clients). Now as long as a server knows which request is associated with which socket, it can always respond to appropriate client using the same socket. Thus a server never needs to open another port in its own node than the original one on which client initially tried to connect. If any server allocates different server-ports after a socket is bound, then in my opinion the server is wasting its resource and it must be needing the client to connect again to the new port assigned.

A bit more for completeness:

Example 2: It's a very interesting question: "can two different processes on a server listen to the same port". If you do not consider protocol as one of parameter defining socket then the answer is no. This is so because we can say that in such case, a single client trying to connect to a server-port will not have any mechanism to mention which of the two listening processes the client intends to connect to. This is the same theme asserted by rule (2). However this is WRONG answer because 'protocol' is also a part of the socket definition. Thus two processes in same node can listen to same port only if they are using different protocol. For example two unrelated clients (say one is using TCP and another is using UDP) can connect and communicate to the same server node and to the same port but they must be served by two different server-processes.

Server Types - single & multiple:

When a server's processes listening to a port that means multiple sockets can simultaneously connect and communicate with the same server-process. If a server uses only a single child-process to serve all the sockets then the server is called single-process/threaded and if the server uses many sub-processes to serve each socket by one sub-process then the server is called multi-process/threaded server. Note that irrespective of the server's type a server can/should always uses the same initial socket to respond back (no need to allocate another server-port).

Suggested Books and rest of the two volumes if you can.

A Note on Parent/Child Process (in response to query/comment of 'Ioan Alexandru Cucu')

Wherever I mentioned any concept in relation to two processes say A and B, consider that they are not related by parent child relationship. OS's (especially UNIX) by design allow a child process to inherit all File-descriptors (FD) from parents. Thus all the sockets (in UNIX like OS are also part of FD) that a process A listening to, can be listened by many more processes A1, A2, .. as long as they are related by parent-child relation to A. But an independent process B (i.e. having no parent-child relation to A) cannot listen to same socket. In addition, also note that this rule of disallowing two independent processes to listen to same socket lies on an OS (or its network libraries) and by far it's obeyed by most OS's. However, one can create own OS which can very well violate this restrictions.

How to add a tooltip to an svg graphic?

On svg, the right way to write the title

<svg>
  <title id="unique-id">Checkout</title>
</svg>

check here for more details https://css-tricks.com/svg-title-vs-html-title-attribute/

how to prevent this error : Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in ... on line 11

You don't need to prevent this error message!
Error messages are your friends!
Without error message you'd never know what is happened.
It's all right! Any working code supposed to throw out error messages.

Though error messages needs proper handling. Usually you don't have to to take any special actions to avoid such an error messages. Just leave your code intact. But if you don't want this error message to be shown to the user, just turn it off. Not error message itself but daislaying it to the user.

ini_set('display_errors',0);
ini_set('log_errors',1);

or even better at .htaccess/php.ini level
And user will never see any error messages. While you will be able still see it in the error log.
Please note that error_reporting should be at max in both cases.

To prevent this message you can check mysql_query result and run fetch_assoc only on success.
But usually nobody uses it as it may require too many nested if's.
But there can be solution too - exceptions!

But it is still not necessary. You can leave your code as is, because it is supposed to work without errors when done.

Using return is another method to avoid nested error messages. Here is a snippet from my database handling function:

  $res = mysql_query($query);
  if (!$res) {
    trigger_error("dbget: ".mysql_error()." in ".$query);
    return false;
  }
  if (!mysql_num_rows($res)) return NULL;

  //fetching goes here
  //if there was no errors only

Disabled form inputs do not appear in the request

Semantically this feels like the correct behaviour

I'd be asking myself "Why do I need to submit this value?"

If you have a disabled input on a form, then presumably you do not want the user changing the value directly

Any value that is displayed in a disabled input should either be

  1. output from a value on the server that produced the form, or
  2. if the form is dynamic, be calculable from the other inputs on the form

Assuming that the server processing the form is the same as the server serving it, all the information to reproduce the values of the disabled inputs should be available at processing

In fact, to preserve data integrity - even if the value of the disabled input was sent to the processing server, you should really be validating it. This validation would require the same level of information as you would need to reproduce the values anyway!

I'd almost argue that read-only inputs shouldn't be sent in the request either

Happy to be corrected, but all the use cases I can think of where read-only/disabled inputs need to be submitted are really just styling issues in disguise

How to get all options of a select using jQuery?

You can use following code for that:

var assignedRoleId = new Array();
$('#RolesListAssigned option').each(function(){
    assignedRoleId.push(this.value);
});

python save image from url

Anyone who is wondering how to get the image extension then you can try split method of string on image url:

str_arr = str(img_url).split('.')
img_ext = '.' + str_arr[3] #www.bigbasket.com/patanjali-atta.jpg (jpg is after 3rd dot so)
img_data = requests.get(img_url).content
with open(img_name + img_ext, 'wb') as handler:
    handler.write(img_data)

Python String and Integer concatenation

I did something else. I wanted to replace a word, in lists off lists, that contained phrases. I wanted to replace that sttring / word with a new word that will be a join between string and number, and that number / digit will indicate the position of the phrase / sublist / lists of lists.

That is, I replaced a string with a string and an incremental number that follow it.

    myoldlist_1=[[' myoldword'],[''],['tttt myoldword'],['jjjj ddmyoldwordd']]
        No_ofposition=[]
        mynewlist_2=[]
        for i in xrange(0,4,1):
            mynewlist_2.append([x.replace('myoldword', "%s" % i+"_mynewword") for x in myoldlist_1[i]])
            if len(mynewlist_2[i])>0:
                No_ofposition.append(i)
mynewlist_2
No_ofposition

What exactly is an instance in Java?

basically object and instance are the two words used interchangeably. A class is template for an object and an object is an instance of a class.

Javascript - Open a given URL in a new tab by clicking a button

Use window.open instead of window.location to open a new window or tab (depending on browser settings).

Your fiddle does not work because there is no button element to select. Try input[type=button] or give the button an id and use #buttonId.

Iterating over dictionaries using 'for' loops

This will print the output in sorted order by values in ascending order.

d = {'x': 3, 'y': 1, 'z': 2}

def by_value(item):
    return item[1]

for key, value in sorted(d.items(), key=by_value):
    print(key, '->', value)

Output:

y -> 1
z -> 2
x -> 3

PLS-00103: Encountered the symbol when expecting one of the following:

The problem is that the else and if are two operators here. Since you open a new 'if' you need a corresponding 'end if'.

Thus:

declare
mark number :=50;
begin
  mark :=& mark;
  if (mark between 85 and 100) then
    dbms_output.put_line('mark is A ');
  else 
    if (mark between 50 and 65) then
      dbms_output.put_line('mark is D ');
    else 
      if (mark between 66 and 75) then
        dbms_output.put_line('mark is C ');
      else 
        if (mark between 76 and 84) then
          dbms_output.put_line('mark is B');
        else 
          dbms_output.put_line('mark is F');
        end if;
      end if;
    end if;
  end if;
end;
/

Alternatively you can use elsif:

declare
mark number :=50;
begin
  mark :=& mark;
  if (mark between 85 and 100)
    then
    dbms_output.put_line('mark is A ');
  elsif (mark between 50 and 65) then
    dbms_output.put_line('mark is D ');
  elsif (mark between 66 and 75) then
    dbms_output.put_line('mark is C ');
  elsif (mark between 76 and 84) then
    dbms_output.put_line('mark is B');
  else 
    dbms_output.put_line('mark is F');
  end if;
end;
/

Check if a string is null or empty in XSLT

If a node has no value available in the input xml like below xpath,

<node>
    <ErrorCode/>
</node>

string() function converts into empty value. So this works fine:

string(/Node/ErrorCode) =''

jQuery Ajax simple call

You could also make the ajax call more generic, reusable, so you can call it from different CRUD(create, read, update, delete) tasks for example and treat the success cases from those calls.

makePostCall = function (url, data) { // here the data and url are not hardcoded anymore
   var json_data = JSON.stringify(data);

    return $.ajax({
        type: "POST",
        url: url,
        data: json_data,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    });
}

// and here a call example
makePostCall("index.php?action=READUSERS", {'city' : 'Tokio'})
    .success(function(data){
               // treat the READUSERS data returned
   })
    .fail(function(sender, message, details){
           alert("Sorry, something went wrong!");
  });

Android basics: running code in the UI thread

The answer by Pomber is acceptable, however I'm not a big fan of creating new objects repeatedly. The best solutions are always the ones that try to mitigate memory hog. Yes, there is auto garbage collection but memory conservation in a mobile device falls within the confines of best practice. The code below updates a TextView in a service.

TextViewUpdater textViewUpdater = new TextViewUpdater();
Handler textViewUpdaterHandler = new Handler(Looper.getMainLooper());
private class TextViewUpdater implements Runnable{
    private String txt;
    @Override
    public void run() {
        searchResultTextView.setText(txt);
    }
    public void setText(String txt){
        this.txt = txt;
    }

}

It can be used from anywhere like this:

textViewUpdater.setText("Hello");
        textViewUpdaterHandler.post(textViewUpdater);

find without recursion

I believe you are looking for -maxdepth 1.

Fastest way to add an Item to an Array

Not very clean but it works :)

Dim arr As Integer() = {1, 2, 3}
Dim newItem As Integer = 4

arr = arr.Concat({newItem}).ToArray

Regular Expression - 2 letters and 2 numbers in C#

This should get you for starting with two letters and ending with two numbers.

[A-Za-z]{2}(.*)[0-9]{2}

If you know it will always be just two and two you can

[A-Za-z]{2}[0-9]{2}

Force GUI update from UI Thread

I've just stumbled over the same problem and found some interesting information and I wanted to put in my two cents and add it here.

First of all, as others have already mentioned, long-running operations should be done by a thread, which can be a background worker, an explicit thread, a thread from the threadpool or (since .Net 4.0) a task: Stackoverflow 570537: update-label-while-processing-in-windows-forms, so that the UI keeps responsive.

But for short tasks there is no real need for threading although it doesn't hurt of course.

I have created a winform with one button and one label to analyze this problem:

System::Void button1_Click(System::Object^  sender, System::EventArgs^  e)
{
  label1->Text = "Start 1";
  label1->Update();
  System::Threading::Thread::Sleep(5000); // do other work
}

My analysis was stepping over the code (using F10) and seeing what happened. And after reading this article Multithreading in WinForms I have found something interesting. The article says at the bottom of the first page, that the UI thread can not repaint the UI until the currently executed function finishes and the window is marked by Windows as "not responding" instead after a while. I have also noticed that on my test application from above while stepping through it, but only in certain cases.

(For the following test it is important to not have Visual Studio set to fullscreen, you must be able to see your little application window at the same time next to it, You must not have to switch between the Visual Studio window for debugging and your application window to see what happens. Start the application, set a breakpoint at label1->Text ..., put the application window beside the VS window and place the mouse cursor over the VS window.)

  1. When I click once on VS after app start (to put the focues there and enable stepping) and step through it WITHOUT moving the mouse, the new text is set and the label is updated in the update() function. This means, the UI is repainted obviously.

  2. When I step over the first line, then move the mouse around a lot and click somewhere, then step further, the new text is likely set and the update() function is called, but the UI is not updated/repainted and the old text remains there until the button1_click() function finishes. Instead of repainting, the window is marked as "not responsive"! It also doesn't help to add this->Update(); to update the whole form.

  3. Adding Application::DoEvents(); gives the UI a chance to update/repaint. Anyway you have to take care that the user can not press buttons or perform other operations on the UI that are not permitted!! Therefore: Try to avoid DoEvents()!, better use threading (which I think is quite simple in .Net).
    But (@Jagd, Apr 2 '10 at 19:25) you can omit .refresh() and .invalidate().

My explanations is as following: AFAIK winform still uses the WINAPI function. Also MSDN article about System.Windows.Forms Control.Update method refers to WINAPI function WM_PAINT. The MSDN article about WM_PAINT states in its first sentence that the WM_PAINT command is only sent by the system when the message queue is empty. But as the message queue is already filled in the 2nd case, it is not send and thus the label and the application form are not repainted.

<>joke> Conclusion: so you just have to keep the user from using the mouse ;-) <>/joke>

Putting images with options in a dropdown list

I found a lot of people recommending ddSlick.js it seems to be a really cool option ! unfortunately it doesnt work as expected for me, maybe I didn't know how to integrate it, today I discovered a library like bootstrap named : MaterialiseCss so I returned to this section to help !!

https://materializecss.com/select.html
https://materializecss.com/dropdown.html

Can't start Eclipse - Java was started but returned exit code=13

I also encountered the same issue. It turned out that the environment variable Path was pointing to an incorrect Java version.

Please check the environment variable and point it to the correct Java. For example:

C:\Program Files (x86)\Java\jdk1.6.0_17\bin

To check the environment variable, go to:

Computer ? properties ? Advanced system settings ? Advanced -> Environment variables

How do I grab an INI value within a shell script?

Sed one-liner, that takes sections into account. Example file:

[section1]
param1=123
param2=345
param3=678

[section2]
param1=abc
param2=def
param3=ghi

[section3]
param1=000
param2=111
param3=222

Say you want param2 from section2. Run the following:

sed -nr "/^\[section2\]/ { :l /^param2[ ]*=/ { s/.*=[ ]*//; p; q;}; n; b l;}" ./file.ini

will give you

def

css transform, jagged edges in chrome

Adding a 1px transparent border will trigger anti-aliasing

outline: 1px solid transparent;

Alternatively, add a 1px transparent box-shadow.

box-shadow: 0 0 1px rgba(255,255,255,0);

Matplotlib-Animation "No MovieWriters Available"

I'm running Ubuntu 20 and I had a similar problem

Installed ffmpeg

pip install ffmpeg

then

sudo apt install ffmpeg

Base table or view not found: 1146 Table Laravel 5

I faced this problem too in laravel 5.2 and if declaring the table name doesn't work,it is probably because you have some wrong declaration or mistake in validation code in Request (If you are using one)

Confusing error in R: Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, : line 1 did not have 42 elements)

To read characters try

scan("/PathTo/file.csv", "")

If you're reading numeric values, then just use

scan("/PathTo/file.csv")

scan by default will use white space as separator. The type of the second arg defines 'what' to read (defaults to double()).

How do I close a tkinter window?

Try this:

from Tkinter import *
import sys
def exitApp():
    sys.exit()
root = Tk()
Button(root, text="Quit", command=exitApp).pack()
root.mainloop()

How can I connect to MySQL on a WAMP server?

Change localhost:8080 to localhost:3306.

Array of an unknown length in C#

In a nutshell, please use Collections and Generics.

It's a must for any C# developer, it's worth spending time to learn :)

Concatenate two NumPy arrays vertically

If the actual problem at hand is to concatenate two 1-D arrays vertically, and we are not fixated on using concatenate to perform this operation, I would suggest the use of np.column_stack:

In []: a = np.array([1,2,3])
In []: b = np.array([4,5,6])
In []: np.column_stack((a, b))
array([[1, 4],
       [2, 5],
       [3, 6]])

Launch Image does not show up in my iOS App

Removing "Launch screen interface file base name" from Info.plist file AND trashing "Launch Screen.xib" worked for me.

make *** no targets specified and no makefile found. stop

I recently ran into this problem while trying to do a manual install of texane's open-source STLink utility on Ubuntu. The solution was, oddly enough,

make clean
make

Delete files in subfolder using batch script

I had to complete the same task and I used a "for" loop and a "del" command as follows:

@ECHO OFF

set dir=%cd%

FOR /d /r %dir% %%x in (archive\) do (
    if exist "%%x" del %%x\*.txt /f /q
)

You can set the dir variable with any start directory you want or used the current directory (%cd%) variable.

These are the options for "for" command:

  • /d For directories
  • /r For recursive

These are the options for "del" command:

  • /f Force deletes read-only files
  • /q Quiet mode; suppresses prompts for delete confirmations.

How to uninstall a package installed with pip install --user

I strongly recommend you to use virtual environments for python package installation. With virtualenv, you prevent any package conflict and total isolation from your python related userland commands.

To delete all your package follow this;

It's possible to uninstall packages installed with --user flag. This one worked for me;

pip freeze --user | xargs pip uninstall -y

For python 3;

pip3 freeze --user | xargs pip3 uninstall -y

But somehow these commands don't uninstall setuptools and pip. After those commands (if you really want clean python) you may delete them with;

pip uninstall setuptools && pip uninstall pip

get UTC timestamp in python with datetime

Naïve datetime versus aware datetime

Default datetime objects are said to be "naïve": they keep time information without the time zone information. Think about naïve datetime as a relative number (ie: +4) without a clear origin (in fact your origin will be common throughout your system boundary).

In contrast, think about aware datetime as absolute numbers (ie: 8) with a common origin for the whole world.

Without timezone information you cannot convert the "naive" datetime towards any non-naive time representation (where does +4 targets if we don't know from where to start ?). This is why you can't have a datetime.datetime.toutctimestamp() method. (cf: http://bugs.python.org/issue1457227)

To check if your datetime dt is naïve, check dt.tzinfo, if None, then it's naïve:

datetime.now()        ## DANGER: returns naïve datetime pointing on local time
datetime(1970, 1, 1)  ## returns naïve datetime pointing on user given time

I have naïve datetimes, what can I do ?

You must make an assumption depending on your particular context: The question you must ask yourself is: was your datetime on UTC ? or was it local time ?

  • If you were using UTC (you are out of trouble):

    import calendar
    
    def dt2ts(dt):
        """Converts a datetime object to UTC timestamp
    
        naive datetime will be considered UTC.
    
        """
    
        return calendar.timegm(dt.utctimetuple())
    
  • If you were NOT using UTC, welcome to hell.

    You have to make your datetime non-naïve prior to using the former function, by giving them back their intended timezone.

    You'll need the name of the timezone and the information about if DST was in effect when producing the target naïve datetime (the last info about DST is required for cornercases):

    import pytz     ## pip install pytz
    
    mytz = pytz.timezone('Europe/Amsterdam')             ## Set your timezone
    
    dt = mytz.normalize(mytz.localize(dt, is_dst=True))  ## Set is_dst accordingly
    

    Consequences of not providing is_dst:

    Not using is_dst will generate incorrect time (and UTC timestamp) if target datetime was produced while a backward DST was put in place (for instance changing DST time by removing one hour).

    Providing incorrect is_dst will of course generate incorrect time (and UTC timestamp) only on DST overlap or holes. And, when providing also incorrect time, occuring in "holes" (time that never existed due to forward shifting DST), is_dst will give an interpretation of how to consider this bogus time, and this is the only case where .normalize(..) will actually do something here, as it'll then translate it as an actual valid time (changing the datetime AND the DST object if required). Note that .normalize() is not required for having a correct UTC timestamp at the end, but is probably recommended if you dislike the idea of having bogus times in your variables, especially if you re-use this variable elsewhere.

    and AVOID USING THE FOLLOWING: (cf: Datetime Timezone conversion using pytz)

    dt = dt.replace(tzinfo=timezone('Europe/Amsterdam'))  ## BAD !!
    

    Why? because .replace() replaces blindly the tzinfo without taking into account the target time and will choose a bad DST object. Whereas .localize() uses the target time and your is_dst hint to select the right DST object.

OLD incorrect answer (thanks @J.F.Sebastien for bringing this up):

Hopefully, it is quite easy to guess the timezone (your local origin) when you create your naive datetime object as it is related to the system configuration that you would hopefully NOT change between the naive datetime object creation and the moment when you want to get the UTC timestamp. This trick can be used to give an imperfect question.

By using time.mktime we can create an utc_mktime:

def utc_mktime(utc_tuple):
    """Returns number of seconds elapsed since epoch

    Note that no timezone are taken into consideration.

    utc tuple must be: (year, month, day, hour, minute, second)

    """

    if len(utc_tuple) == 6:
        utc_tuple += (0, 0, 0)
    return time.mktime(utc_tuple) - time.mktime((1970, 1, 1, 0, 0, 0, 0, 0, 0))

def datetime_to_timestamp(dt):
    """Converts a datetime object to UTC timestamp"""

    return int(utc_mktime(dt.timetuple()))

You must make sure that your datetime object is created on the same timezone than the one that has created your datetime.

This last solution is incorrect because it makes the assumption that the UTC offset from now is the same than the UTC offset from EPOCH. Which is not the case for a lot of timezones (in specific moment of the year for the Daylight Saving Time (DST) offsets).

Formatting floats in a numpy array

You can use round function. Here some example

numpy.round([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01],2)
array([ 21.53,   8.13,   3.97,  10.08])

IF you want change just display representation, I would not recommended to alter printing format globally, as it suggested above. I would format my output in place.

>>a=np.array([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01])
>>> print([ "{:0.2f}".format(x) for x in a ])
['21.53', '8.13', '3.97', '10.08']

How do I start a process from C#?

Use the Process class. The MSDN documentation has an example how to use it.

How to count number of files in each directory?

I edited the script in order to exclude all node_modules directories inside the analyzed one.

This can be used to check if the project number of files is exceeding the maximum number that the file watcher can handle.

find . -type d ! -path "*node_modules*" -print0 | while read -d '' -r dir; do
    files=("$dir"/*)
    printf "%5d files in directory %s\n" "${#files[@]}" "$dir"
done

To check the maximum files that your system can watch:

cat /proc/sys/fs/inotify/max_user_watches

node_modules folder should be added to your IDE/editor excluded paths in slow systems, and the other files count shouldn't ideally exceed the maximum (which can be changed though).

Input type "number" won't resize

change type="number" to type="tel"

Implementing INotifyPropertyChanged - does a better way exist?

I resolved in This Way (it's a little bit laboriouse, but it's surely the faster in runtime).

In VB (sorry, but I think it's not hard translate it in C#), I make this substitution with RE:

(?<Attr><(.*ComponentModel\.)Bindable\(True\)>)( |\r\n)*(?<Def>(Public|Private|Friend|Protected) .*Property )(?<Name>[^ ]*) As (?<Type>.*?)[ |\r\n](?![ |\r\n]*Get)

with:

Private _${Name} As ${Type}\r\n${Attr}\r\n${Def}${Name} As ${Type}\r\nGet\r\nReturn _${Name}\r\nEnd Get\r\nSet (Value As ${Type})\r\nIf _${Name} <> Value Then \r\n_${Name} = Value\r\nRaiseEvent PropertyChanged(Me, New ComponentModel.PropertyChangedEventArgs("${Name}"))\r\nEnd If\r\nEnd Set\r\nEnd Property\r\n

This transofrm all code like this:

<Bindable(True)>
Protected Friend Property StartDate As DateTime?

In

Private _StartDate As DateTime?
<Bindable(True)>
Protected Friend Property StartDate As DateTime?
    Get
        Return _StartDate
    End Get
    Set(Value As DateTime?)
        If _StartDate <> Value Then
            _StartDate = Value
            RaiseEvent PropertyChange(Me, New ComponentModel.PropertyChangedEventArgs("StartDate"))
        End If
    End Set
End Property

And If I want to have a more readable code, I can be the opposite just making the following substitution:

Private _(?<Name>.*) As (?<Type>.*)[\r\n ]*(?<Attr><(.*ComponentModel\.)Bindable\(True\)>)[\r\n ]*(?<Def>(Public|Private|Friend|Protected) .*Property )\k<Name> As \k<Type>[\r\n ]*Get[\r\n ]*Return _\k<Name>[\r\n ]*End Get[\r\n ]*Set\(Value As \k<Type>\)[\r\n ]*If _\k<Name> <> Value Then[\r\n ]*_\k<Name> = Value[\r\n ]*RaiseEvent PropertyChanged\(Me, New (.*ComponentModel\.)PropertyChangedEventArgs\("\k<Name>"\)\)[\r\n ]*End If[\r\n ]*End Set[\r\n ]*End Property

With

${Attr} ${Def} ${Name} As ${Type}

I throw to replace the IL code of the set method, but I can't write a lot of compiled code in IL... If a day I write it, I'll say you!

How do I rename a Git repository?

To rename any repository of your GitHub account:

  1. Go to that particular repository which you want to rename
  2. Navigate to the settings tab
  3. There, in the repository name section, type the new name you want to put and click Rename

MySQL: Get column name or alias from query

cursor.description will give you a tuple of tuples where [0] for each is the column header.

num_fields = len(cursor.description)
field_names = [i[0] for i in cursor.description]

Where can I download JSTL jar

You can download JSTL 1.1 here and JSTL 1.2 here.

See also:

A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war

In my case the situation was this: I had an offline server on which I had to perform the build. For that I had compiled everything locally first and then transferred repository folder to the offline server.

Problem - build works locally but not on the server, even thou they both have same maven version, same repository folder, same JDK.

Cause: on my local machine I had additional custom "" entry in settings.xml. When I added same to the settings.xml on the server then my issues disappeared.

Missing XML comment for publicly visible type or member

I know this is a really old thread, but it's the first response on google so I thought I'd add this bit of information:

This behavior only occurs when the warning level is set to 4 under "Project Properties" -> "Build". Unless you really need that much information you can set it to 3 and you'll get rid of these warnings. Of course, changing the warning level affects more than just comments, so please refer to the documentation if you're unsure what you'll be missing:
https://msdn.microsoft.com/en-us/library/thxezb7y.aspx

How to check for null in Twig?

     //test if varibale exist
     {% if var is defined %}
         //todo
     {% endif %}

     //test if variable is not null
     {% if var is not null %}
         //todo
     {% endif %}

Keyboard shortcuts are not active in Visual Studio with Resharper installed

I had a very difficult time getting this working one under VS2015 one day. After the initial install everything was working, but I come in this morning and my keyboard shortcuts don't work. Going through Resharper's Environment > Keyboard & Menus didn't work; reinstalling Resharper didn't work. Even deleting every configuration from Resharper's AppData folder didn't work.

So what did work? Going to Visual Studio's Tools > Options > Environment > Keyboard and clicking Reset. After I did that, then Resharper's schemes would take.

How to save an image locally using Python whose URL address I already know?

If you don't already have the url for the image, you could scrape it with gazpacho:

from gazpacho import Soup
base_url = "http://books.toscrape.com"

soup = Soup.get(base_url)
links = [img.attrs["src"] for img in soup.find("img")]

And then download the asset with urllib as mentioned:

from pathlib import Path
from urllib.request import urlretrieve as download

directory = "images"
Path(directory).mkdir(exist_ok=True)

link = links[0]
name = link.split("/")[-1]

download(f"{base_url}/{link}", f"{directory}/{name}")

Why use the INCLUDE clause when creating an index?

There is a limit to the total size of all columns inlined into the index definition. That said though, I have never had to create index that wide. To me, the bigger advantage is the fact that you can cover more queries with one index that has included columns as they don't have to be defined in any particular order. Think about is as an index within the index. One example would be the StoreID (where StoreID is low selectivity meaning that each store is associated with a lot of customers) and then customer demographics data (LastName, FirstName, DOB): If you just inline those columns in this order (StoreID, LastName, FirstName, DOB), you can only efficiently search for customers for which you know StoreID and LastName.

On the other hand, defining the index on StoreID and including LastName, FirstName, DOB columns would let you in essence do two seeks- index predicate on StoreID and then seek predicate on any of the included columns. This would let you cover all possible search permutationsas as long as it starts with StoreID.

Truncate/round whole number in JavaScript?

Travis Pessetto's answer along with mozey's trunc2 function were the only correct answers, considering how JavaScript represents very small or very large floating point numbers in scientific notation.

For example, parseInt(-2.2043642353916286e-15) will not correctly parse that input. Instead of returning 0 it will return -2.

This is the correct (and imho the least insane) way to do it:

function truncate(number)
{
    return number > 0
         ? Math.floor(number)
         : Math.ceil(number);
}

How to select true/false based on column value?

Use a CASE. I would post the specific code, but need more information than is supplied in the post - such as the data type of EntityProfile and what is usually stored in it. Something like:

CASE WHEN EntityProfile IS NULL THEN 'False' ELSE 'True' END

Edit - the entire SELECT statement, as per the info in the comments:

SELECT EntityID, EntityName, 
       CASE WHEN EntityProfile IS NULL THEN 'False' ELSE 'True' END AS HasProfile
FROM Entity

No LEFT JOIN necessary in this case...

HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

This could also be an issue of building the code using a 64 bit configuration. You can try to select x86 as the build platform which can solve this issue. To do this right-click the solution and select Configuration Manager From there you can change the Platform of the project using the 32-bit .dll to x86

Non-Static method cannot be referenced from a static context with methods and variables

You need to make both your method - printMenu() and getUserChoice() static, as you are directly invoking them from your static main method, without creating an instance of the class, those methods are defined in. And you cannot invoke a non-static method without any reference to an instance of the class they are defined in.

Alternatively you can change the method invocation part to:

BookStoreApp2 bookStoreApp = new BookStoreApp2();
bookStoreApp.printMenu();
bookStoreApp.getUserChoice();

session handling in jquery

Assuming you're referring to this plugin, your code should be:

// To Store
$(function() {
    $.session.set("myVar", "value");
});


// To Read
$(function() {
    alert($.session.get("myVar"));
});

Before using a plugin, remember to read its documentation in order to learn how to use it. In this case, an usage example can be found in the README.markdown file, which is displayed on the project page.

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

I resolve this is by changing the version no of recyleview to recyclerview-v7:24.2.1. Please check your dependencies and use the proper version number.

JPA: unidirectional many-to-one and cascading delete

You don't need to use bi-directional association instead of your code, you have just to add CascaType.Remove as a property to ManyToOne annotation, then use @OnDelete(action = OnDeleteAction.CASCADE), it's works fine for me.

How to change the button text of <input type="file" />?

Works Perfectly on All Browsers Hope it will work for you too.

HTML:
<input type="file" class="custom-file-input">

CSS:

 .custom-file-input::-webkit-file-upload-button {
  visibility: hidden;
}
.custom-file-input::before {
  content: 'Select some files';
  display: inline-block;
  background: -webkit-linear-gradient(top, #f9f9f9, #e3e3e3);
  border: 1px solid #999;
  border-radius: 3px;
  padding: 5px 8px;
  outline: none;
  white-space: nowrap;
  -webkit-user-select: none;
  cursor: pointer;
  text-shadow: 1px 1px #fff;
  font-weight: 700;
  font-size: 10pt;
}
.custom-file-input:hover::before {
  border-color: black;
}
.custom-file-input:active::before {
  background: -webkit-linear-gradient(top, #e3e3e3, #f9f9f9);
}

Change content: 'Select some files'; with the text you want within ''

IF NOT WORKING WITH firefox then use this instead of input:

<label class="custom-file-input" for="Upload" >
</label>

<input id="Upload" type="file" multiple="multiple" name="_photos" accept="image/*" style="visibility: hidden">

Pandas - How to flatten a hierarchical index in columns

df.columns = ['_'.join(tup).rstrip('_') for tup in df.columns.values]

What does value & 0xff do in Java?

It help to reduce lot of codes. It is occasionally used in RGB values which consist of 8bits.

where 0xff means 24(0's ) and 8(1's) like 00000000 00000000 00000000 11111111

It effectively masks the variable so it leaves only the value in the last 8 bits, and ignores all the rest of the bits

It’s seen most in cases like when trying to transform color values from a special format to standard RGB values (which is 8 bits long).

Great Explanation See here

How to float a div over Google Maps?

absolute positioning is evil... this solution doesn't take into account window size. If you resize the browser window, your div will be out of place!

In MySQL, can I copy one row to insert into the same table?

I just had to do this and this was my manual solution:

  1. In phpmyadmin, check the row you wish to copy
  2. At the bottom under query result operations click 'Export'
  3. On the next page check 'Save as file' then click 'Go'
  4. Open the exported file with a text editor, find the value of the primary field and change it to something unique.
  5. Back in phpmyadmin click on the 'Import' tab, locate the file to import .sql file under browse, click 'Go' and the duplicate row should be inserted.

If you don't know what the PRIMARY field is, look back at your phpmyadmin page, click on the 'Structure' tab and at the bottom of the page under 'Indexes' it will show you which 'Field' has a 'Keyname' value 'PRIMARY'.

Kind of a long way around, but if you don't want to deal with markup and just need to duplicate a single row there you go.

Is std::vector copying the objects with a push_back?

Yes, std::vector<T>::push_back() creates a copy of the argument and stores it in the vector. If you want to store pointers to objects in your vector, create a std::vector<whatever*> instead of std::vector<whatever>.

However, you need to make sure that the objects referenced by the pointers remain valid while the vector holds a reference to them (smart pointers utilizing the RAII idiom solve the problem).

Why is there no Constant feature in Java?

This is a bit of an old question, but I thought I would contribute my 2 cents anyway since this thread came up in conversation today.

This doesn't exactly answer why is there no const? but how to make your classes immutable. (Unfortunately I have not enough reputation yet to post as a comment to the accepted answer)

The way to guarantee immutability on an object is to design your classes more carefully to be immutable. This requires a bit more care than a mutable class.

This goes back to Josh Bloch's Effective Java Item 15 - Minimize Mutability. If you haven't read the book, pick up a copy and read it over a few times I guarantee it will up your figurative "java game".

In item 15 Bloch suggest that you should limit the mutability of classes to ensure the object's state.

To quote the book directly:

An immutable class is simply a class whose instances cannot be modified. All of the information contained in each instance is provided when it is created and is fixed for the lifetime of the object. The Java platform libraries contain many immutable classes, including String, the boxed primitive classes, and BigInte- ger and BigDecimal. There are many good reasons for this: Immutable classes are easier to design, implement, and use than mutable classes. They are less prone to error and are more secure.

Bloch then describes how to make your classes immutable, by following 5 simple rules:

  1. Don’t provide any methods that modify the object’s state (i.e., setters, aka mutators)
  2. Ensure that the class can’t be extended (this means declaring the class itself as final).
  3. Make all fields final.
  4. Make all fields private.
  5. Ensure exclusive access to any mutable components. (by making defensive copies of the objects)

For more details I highly recommend picking up a copy of the book.

How to trap on UIViewAlertForUnsatisfiableConstraints?

Followed Stephen's advice and tried to debug the code and whoa! it worked. The answer lies in the debug message itself.

Will attempt to recover by breaking constraint NSLayoutConstraint:0x191f0920 H:[MPKnockoutButton:0x17a876b0]-(34)-[MPDetailSlider:0x17a8bc50](LTR)>

The line above tells you that the runtime worked by removing this constraint. May be you don't need Horizontal Spacing on your button (MPKnockoutButton). Once you clear this constraint, it won't complain at runtime & you would get the desired behaviour.

Laravel Soft Delete posts

In Laravel 5.5 Soft Deleted works ( for me ).

Data Base

deleted_at Field, default NULL value

Model

use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model {
    use SoftDeletes;
}

Controller

public function destroy($id)
{
    User::find($id)->delete();
}

DB query builder toArray() laravel 4

And another solution

$objectData = DB::table('user')
    ->select('column1', 'column2')
    ->where('name', '=', 'Jhon')
    ->get();
$arrayData = array_map(function($item) {
    return (array)$item; 
}, $objectData->toArray());

It good in case when you need only several columns from entity.

TSQL DATETIME ISO 8601

For ISO 8601 format for Datetime & Datetime2, below is the recommendation from SQL Server. It does not support basic ISO 8601 format for datetime(yyyyMMddThhmmss).

DateTime

YYYY-MM-DDThh:mm:ss[.mmm]

YYYYMMDD[ hh:mm:ss[.mmm]]

Examples:

  1. 2004-05-23T14:25:10

  2. 2004-05-23T14:25:10.487

Datetime2

YYYY-MM-DDThh:mm:ss[.nnnnnnn]

YYYY-MM-DDThh:mm:ss[.nnnnnnn] Examples:

  1. 2004-05-23T14:25:10

  2. 2004-05-23T14:25:10.8849926

You can convert them using 126 option

--Datetime

DECLARE @table Table(ExtendedDate DATETIME, BasicDate Datetime)

DECLARE @ExtendedDate VARCHAR(30) = '2020-07-01T08:39:17' , @BasicDate VARCHAR(30) = '2009-01-23T10:53:21.000'

INSERT INTO @table(ExtendedDate, BasicDate)
SELECT convert(datetime,@ExtendedDate,126) ,convert(datetime,@BasicDate,126)

SELECT * FROM @table
go

-- Datetime2

DECLARE @table Table(ExtendedDate DATETIME2, BasicDate Datetime2)

DECLARE @ExtendedDate VARCHAR(30) = '2000-01-14T13:42:00.0000000' , @BasicDate VARCHAR(30) = '2009-01-23T10:53:21.0000000'

INSERT INTO @table(ExtendedDate, BasicDate)
SELECT convert(datetime2,@ExtendedDate,126) ,convert(datetime2,@BasicDate,126)

SELECT * FROM @table
go

Datetime

+-------------------------+-------------------------+
|      ExtendedDate       |        BasicDate        |
+-------------------------+-------------------------+
| 2020-07-01 08:39:17.000 | 2009-01-23 10:53:21.000 |
+-------------------------+-------------------------+

Datetime2


+-----------------------------+-----------------------------+
|        ExtendedDate         |          BasicDate          |
+-----------------------------+-----------------------------+
| 2000-01-14 13:42:00.0000000 | 2009-01-23 10:53:21.0000000 |
+-----------------------------+-----------------------------+

Joining 2 SQL SELECT result sets into one

Use JOIN to join the subqueries and use ON to say where the rows from each subquery must match:

SELECT T1.col_a, T1.col_b, T2.col_c
FROM (SELECT col_a, col_b, ...etc...) AS T1
JOIN (SELECT col_a, col_c, ...etc...) AS T2
ON T1.col_a = T2.col_a

If there are some values of col_a that are in T1 but not in T2, you can use a LEFT OUTER JOIN instead.

How to change language of app when user selects language?

    Locale locale = new Locale(langCode);
    Locale.setDefault(locale);
    Configuration configuration = context.getResources().getConfiguration();
    configuration.locale = locale;
    preferences.setLocalePref(langCode);
    context.getResources().updateConfiguration(configuration, context.getResources().getDisplayMetrics());

Here, langCode is the required language code. You can save the language code as string in sharedPreferences. and you can call this code super.onCreate(savedInstanceState) in onCreate.

Java - How to access an ArrayList of another class?

You can do the following:

  public class Numbers {
    private int number1 = 50;
    private int number2 = 100;
    private List<Integer> list;

    public Numbers() {
      list = new ArrayList<Integer>();
      list.add(number1);
      list.add(number2);
    }

    int getNumber(int pos)
    {
      return list.get(pos);
    }
  }

  public class Test {
    private Numbers numbers;

    public Test(){
      numbers = new Numbers();
      int number1 = numbers.getNumber(0);
      int number2 = numbers.getNumber(1);
    }
  }

Convert txt to csv python script

This is how I do it:

 with open(txtfile, 'r') as infile, open(csvfile, 'w') as outfile:
        stripped = (line.strip() for line in infile)
        lines = (line.split(",") for line in stripped if line)
        writer = csv.writer(outfile)
        writer.writerows(lines)

Hope it helps!

How to reset Jenkins security settings from the command line?

1 first check location if you install war or Linux or windows based on that

for example if war under Linux and for admin user

/home/"User_NAME"/.jenkins/users/admin/config.xml

go to this tag after #jbcrypt:

<passwordHash>#jbcrypt:$2a$10$3DzCGLQr2oYXtcot4o0rB.wYi5kth6e45tcPpRFsuYqzLZfn1pcWK</passwordHash>

change this password using use any website for bcrypt hash generator

https://www.dailycred.com/article/bcrypt-calculator

make sure it start with $2a cause this one jenkens uses

How to convert OutputStream to InputStream?

The easystream open source library has direct support to convert an OutputStream to an InputStream: http://io-tools.sourceforge.net/easystream/tutorial/tutorial.html

// create conversion
final OutputStreamToInputStream<Void> out = new OutputStreamToInputStream<Void>() {
    @Override
    protected Void doRead(final InputStream in) throws Exception {
           LibraryClass2.processDataFromInputStream(in);
           return null;
        }
    };
try {   
     LibraryClass1.writeDataToTheOutputStream(out);
} finally {
     // don't miss the close (or a thread would not terminate correctly).
     out.close();
}

They also list other options: http://io-tools.sourceforge.net/easystream/outputstream_to_inputstream/implementations.html

  • Write the data the data into a memory buffer (ByteArrayOutputStream) get the byteArray and read it again with a ByteArrayInputStream. This is the best approach if you're sure your data fits into memory.
  • Copy your data to a temporary file and read it back.
  • Use pipes: this is the best approach both for memory usage and speed (you can take full advantage of the multi-core processors) and also the standard solution offered by Sun.
  • Use InputStreamFromOutputStream and OutputStreamToInputStream from the easystream library.

How does the stack work in assembly language?

You are correct that a stack is a data structure. Often, data structures (stacks included) you work with are abstract and exist as a representation in memory.

The stack you are working with in this case has a more material existence- it maps directly to real physical registers in the processor. As a data structure, stacks are FILO (first in, last out) structures that ensure data is removed in the reverse order it was entered. See the StackOverflow logo for a visual! ;)

You are working with the instruction stack. This is the stack of actual instructions you are feeding the processor.

FileNotFoundException while getting the InputStream object from HttpURLConnection

Please change

con = (HttpURLConnection) new URL("http://localhost:8080/myapp/service/generate").openConnection();

To

con = (HttpURLConnection) new URL("http://YOUR_IP:8080/myapp/service/generate").openConnection();

Get first line of a shell command's output

Yes, that is one way to get the first line of output from a command.

If the command outputs anything to standard error that you would like to capture in the same manner, you need to redirect the standard error of the command to the standard output stream:

utility 2>&1 | head -n 1

There are many other ways to capture the first line too, including sed 1q (quit after first line), sed -n 1p (only print first line, but read everything), awk 'FNR == 1' (only print first line, but again, read everything) etc.

Link a .css on another folder

_x000D_
_x000D_
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
_x000D_
.tree-view-com ul li {_x000D_
  position: relative;_x000D_
  list-style: none;_x000D_
}_x000D_
.tree-view-com .tree-view-child > li{_x000D_
  padding-bottom: 30px;_x000D_
}_x000D_
.tree-view-com .tree-view-child > li:last-of-type{_x000D_
  padding-bottom: 0px;_x000D_
}_x000D_
 _x000D_
.tree-view-com ul li a .c-icon {_x000D_
  margin-right: 10px;_x000D_
  position: relative;_x000D_
  top: 2px;_x000D_
}_x000D_
.tree-view-com ul > li > ul {_x000D_
  margin-top: 20px;_x000D_
  position: relative;_x000D_
}_x000D_
.tree-view-com > ul > li:before {_x000D_
  content: "";_x000D_
  border-left: 1px dashed #ccc;_x000D_
  position: absolute;_x000D_
  height: calc(100% - 30px - 5px);_x000D_
  z-index: 1;_x000D_
  left: 8px;_x000D_
  top: 30px;_x000D_
}_x000D_
.tree-view-com > ul > li > ul > li:before {_x000D_
  content: "";_x000D_
  border-top: 1px dashed #ccc;_x000D_
  position: absolute;_x000D_
  width: 25px;_x000D_
  left: -32px;_x000D_
  top: 12px;_x000D_
}
_x000D_
<div class="tree-view-com">_x000D_
    <ul class="tree-view-parent">_x000D_
        <li>_x000D_
            <a href=""><i class="fa fa-folder c-icon c-icon-list" aria-hidden="true"></i> folder</a>_x000D_
            <ul class="tree-view-child">_x000D_
                <li>_x000D_
                    <a href="" class="document-title">_x000D_
                        <i class="fa fa-folder c-icon" aria-hidden="true"></i>_x000D_
                        sub folder 1_x000D_
                    </a>_x000D_
                </li>_x000D_
                <li>_x000D_
                    <a href="" class="document-title">_x000D_
                        <i class="fa fa-folder c-icon" aria-hidden="true"></i>_x000D_
                        sub folder 2_x000D_
                    </a>_x000D_
                </li>_x000D_
                <li>_x000D_
                    <a href="" class="document-title">_x000D_
                        <i class="fa fa-folder c-icon" aria-hidden="true"></i>_x000D_
                        sub folder 3_x000D_
                    </a>_x000D_
                </li>_x000D_
            </ul>_x000D_
        </li>_x000D_
    </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Open Popup window using javascript

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

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

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


</script>

Then, you link to it by:

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

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

Different color for each bar in a bar chart; ChartJS

I have just got this issue recently, and here is my solution

var labels = ["001", "002", "003", "004", "005", "006", "007"];
var data = [20, 59, 80, 81, 56, 55, 40];
for (var i = 0, len = labels.length; i < len; i++) {
   background_colors.push(getRandomColor());// I use @Benjamin method here
}

var barChartData = {
  labels: labels,
  datasets: [{
    label: "My First dataset",
    fillColor: "rgba(220,220,220,0.5)", 
    strokeColor: "rgba(220,220,220,0.8)", 
    highlightFill: "rgba(220,220,220,0.75)",
    highlightStroke: "rgba(220,220,220,1)",
    backgroundColor: background_colors,
    data: data
  }]
};

PHP 5 disable strict standards error

For no errors.

error_reporting(0);

or for just not strict

error_reporting(E_ALL ^ E_STRICT);

and if you ever want to display all errors again, use

error_reporting(-1);

Position of a string within a string using Linux shell script?

With bash

a="The cat sat on the mat"
b=cat
strindex() { 
  x="${1%%$2*}"
  [[ "$x" = "$1" ]] && echo -1 || echo "${#x}"
}
strindex "$a" "$b"   # prints 4
strindex "$a" foo    # prints -1

what is the size of an enum type data in C++?

With my now ageing Borland C++ Builder compiler enums can be 1,2 or 4 bytes, although it does have a flag you can flip to force it to use ints.

I guess it's compiler specific.

Eclipse CDT project built but "Launch Failed. Binary Not Found"

This happened to me and I found a solution, see if this works for you:

Once you have built your project with the hammer icon:

  1. select "Run".
  2. Run Configurations.
  3. Choose "C++ Application".
  4. Click on the "New Launch Configuration" icon on the top left of the open window.
  5. Select "Browse" under the C/C++ Application.
  6. Browse to the folder where you made your project initially.
  7. Enter the Debug folder.
  8. Click on the binary file with the same name as the project.
  9. Select "OK".
  10. Click "Apply" to confirm the link you just set.
  11. Close that window.

Afterwards you should be able to run the project as much as you'd like.

Hopefully this works for you.

jQuery If DIV Doesn't Have Class "x"

jQuery has the hasClass() function that returns true if any element in the wrapped set contains the specified class

if (!$(this).hasClass("selected")) {
    //do stuff
}

Take a look at my example of use

  • If you hover over a div, it fades as normal speed to 100% opacity if the div does not contain the 'selected' class
  • If you hover out of a div, it fades at slow speed to 30% opacity if the div does not contain the 'selected' class
  • Clicking the button adds 'selected' class to the red div. The fading effects no longer work on the red div

Here is the code for it

<!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" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
<title>Sandbox</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body { background-color: #FFF; font: 16px Helvetica, Arial; color: #000; }
</style>


<!-- jQuery code here -->
<script type="text/javascript">
$(function() {

$('#myButton').click(function(e) {
$('#div2').addClass('selected');
});

$('.thumbs').bind('click',function(e) { alert('You clicked ' + e.target.id ); } );

$('.thumbs').hover(fadeItIn, fadeItOut);


});

function fadeItIn(e) {
if (!$(e.target).hasClass('selected')) 
 { 
    $(e.target).fadeTo('normal', 1.0); 
  } 
}

function fadeItOut(e) { 
  if (!$(e.target).hasClass('selected'))
  { 
    $(e.target).fadeTo('slow', 0.3); 
 } 
}
</script>


</head>
<body>
<div id="div1" class="thumbs" style=" background-color: #0f0; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both;"> 
One div with a thumbs class
</div>
<div id="div2" class="thumbs" style=" background-color: #f00; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both;">
Another one with a thumbs class
</div>
<input type="button" id="myButton" value="add 'selected' class to red div" />
</body>
</html>

EDIT:

this is just a guess, but are you trying to achieve something like this?

  • Both divs start at 30% opacity
  • Hovering over a div fades to 100% opacity, hovering out fades back to 30% opacity. Fade effects only work on elements that don't have the 'selected' class
  • Clicking a div adds/removes the 'selected' class

jQuery Code is here-

$(function() {

$('.thumbs').bind('click',function(e) { $(e.target).toggleClass('selected'); } );
$('.thumbs').hover(fadeItIn, fadeItOut);
$('.thumbs').css('opacity', 0.3);

});

function fadeItIn(e) {
if (!$(e.target).hasClass('selected')) 
 { 
    $(e.target).fadeTo('normal', 1.0); 
  } 
}

function fadeItOut(e) { 
  if (!$(e.target).hasClass('selected'))
  { 
    $(e.target).fadeTo('slow', 0.3); 
 } 
}

<div id="div1" class="thumbs" style=" background-color: #0f0; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both; cursor:pointer;"> 
One div with a thumbs class
</div>
<div id="div2" class="thumbs" style=" background-color: #f00; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both; cursor:pointer;">
Another one with a thumbs class
</div>

jquery json to string?

Edit: You should use the json2.js library from Douglas Crockford instead of implementing the code below. It provides some extra features and better/older browser support.

Grab the json2.js file from: https://github.com/douglascrockford/JSON-js


// implement JSON.stringify serialization
JSON.stringify = JSON.stringify || function (obj) {
    var t = typeof (obj);
    if (t != "object" || obj === null) {
        // simple data type
        if (t == "string") obj = '"'+obj+'"';
        return String(obj);
    }
    else {
        // recurse array or object
        var n, v, json = [], arr = (obj && obj.constructor == Array);
        for (n in obj) {
            v = obj[n]; t = typeof(v);
            if (t == "string") v = '"'+v+'"';
            else if (t == "object" && v !== null) v = JSON.stringify(v);
            json.push((arr ? "" : '"' + n + '":') + String(v));
        }
        return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
    }
};

var tmp = {one: 1, two: "2"};
JSON.stringify(tmp); // '{"one":1,"two":"2"}'

Code from: http://www.sitepoint.com/blogs/2009/08/19/javascript-json-serialization/

Removing "NUL" characters

Try Find and Replace. type \x00 in Find text box, check the Regular expression option. Leave Replace textbox blank and click on replace all. short cut key for find and replace is ctrl+H.

Operand type clash: uniqueidentifier is incompatible with int

The reason is that the data doesn't match the datatype. I have come across the same issues that I forgot to make the fields match. Though my case is not same as yours, but it shows the similar error message.

The situation is that I copy a table, but accidently I misspell one field, so I change it using the ALTER after creating the database. And the order of fields in both table is not identical. so when I use the INSERT INTO TableName SELECT * FROM TableName, the result showed the similar errors: Operand type clash: datetime is incompatible with uniqueidentifier

This is a simiple example:

use example
go
create table Test1 (
    id int primary key,
    item uniqueidentifier,
    inserted_at datetime
    )
go
create table Test2 (
    id int primary key,
    inserted_at datetime
    )
go
alter table Test2 add item uniqueidentifier;
go

--insert into Test1 (id, item, inserted_at) values (1, newid(), getdate()), (2, newid(), getdate());


insert into Test2 select * from Test1;

select * from Test1;
select * from Test2;


The error message is:

Msg 206, Level 16, State 2, Line 24
Operand type clash: uniqueidentifier is incompatible with datetime

What is mutex and semaphore in Java ? What is the main difference?

This question has relevant answers and link to official Java guidance: Is there a Mutex in Java?

Merge two objects with ES6

Another aproach is:

let result = { ...item, location : { ...response } }

But Object spread isn't yet standardized.

May also be helpful: https://stackoverflow.com/a/32926019/5341953

Output Django queryset as JSON

If the goal is to build an API that allow you to access your models in JSON format I recommend you to use the django-restframework that is an enormously popular package within the Django community to achieve this type of tasks.

It include useful features such as Pagination, Defining Serializers, Nested models/relations and more. Even if you only want to do minor Javascript tasks and Ajax calls I would still suggest you to build a proper API using the Django Rest Framework instead of manually defining the JSON response.

SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable

I tried

sdk.dir = \Users\OLUWAGBEMIGA\AppData\Local\Android\sdk 

and it worked, I simply pasted it in the project folder and outside.

In the environment variable I also used the sdk link above and the name ANDROID_HOME as the path name. Close everything reopen and Cabom it all worked

How to check list A contains any value from list B?

You can Intersect the two lists:

if (A.Intersect(B).Any())

Why would you use Expression<Func<T>> rather than Func<T>?

An extremely important consideration in the choice of Expression vs Func is that IQueryable providers like LINQ to Entities can 'digest' what you pass in an Expression, but will ignore what you pass in a Func. I have two blog posts on the subject:

More on Expression vs Func with Entity Framework and Falling in Love with LINQ - Part 7: Expressions and Funcs (the last section)

Dealing with multiple Python versions and PIP?

The current recommendation is to use python -m pip, where python is the version of Python you would like to use. This is the recommendation because it works across all versions of Python, and in all forms of virtualenv. For example:

# The system default python:
$ python -m pip install fish

# A virtualenv's python:
$ .env/bin/python -m pip install fish

# A specific version of python:
$ python-3.6 -m pip install fish

Previous answer, left for posterity:

Since version 0.8, Pip supports pip-{version}. You can use it the same as easy_install-{version}:

$ pip-2.5 install myfoopackage
$ pip-2.6 install otherpackage
$ pip-2.7 install mybarpackage

EDIT: pip changed its schema to use pipVERSION instead of pip-VERSION in version 1.5. You should use the following if you have pip >= 1.5:

$ pip2.6 install otherpackage
$ pip2.7 install mybarpackage

Check https://github.com/pypa/pip/pull/1053 for more details


References:

Escape quote in web.config connection string

Odeds answer is almost complete. Just one thing to add.

  1. Escape xml special chars like Emanuele Greco said.
  2. Put the password in single quotes like Oded said
  3. (this one is new) Escape single ticks with another single tick (ref)

having this password="'; this sould be a valid connection string:

connectionString='Server=dbsrv;User ID=myDbUser;Password='&quot;&amp;&amp;;'

IIS 7, HttpHandler and HTTP Error 500.21

I had the same problem and just solved it. I had posted my own question on stackoverflow:

Can't PUT to my IHttpHandler, GET works fine

The solution was to set runManagedModulesForWebDavRequests to true in the modules element. My guess is that once you install WebDAV then all PUT requests are associated with it. If you need the PUT to go to your handler, you need to remove the WebDAV module and set this attribute to true.

<modules runManagedModulesForWebDavRequests="true">
...
</modules>

So if you're running into the problem when you use the PUT verb and you have installed WebDAV then hopefully this solution will fix your problem.

PHPMyAdmin Default login password

This is asking for your MySQL username and password.

You should enter these details, which will default to "root" and "" (i.e.: nothing) if you've not specified a password.

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

The issue for me was calling get_text_noop in the LANGUAGES iterable.

Changing

LANGUAGES = (
    ('en-gb', get_text_noop('British English')),
    ('fr', get_text_noop('French')),
)

to

from django.utils.translation import gettext_lazy as _

LANGUAGES = (
    ('en-gb', _('British English')),
    ('fr', _('French')),
)

in the base settings file resolved the ImproperlyConfigured: The SECRET_KEY setting must not be empty exception.

How to get DateTime.Now() in YYYY-MM-DDThh:mm:ssTZD format using C#

use zzz instead of TZD

Example:

DateTime.Now.ToString("yyyy-MM-ddThh:mm:sszzz");

Response:

2011-08-09T11:50:00:02+02:00

VBA equivalent to Excel's mod function

My way to replicate Excel's MOD(a,b) in VBA is to use XLMod(a,b) in VBA where you include the function:

Function XLMod(a, b)
    ' This replicates the Excel MOD function
    XLMod = a - b * Int(a / b)
End Function

in your VBA Module

Dataset - Vehicle make/model/year (free)

How about Freebase? I think they have an API available, too.

http://www.freebase.com/

"On Exit" for a Console Application

This code works to catch the user closing the console window:

using System;
using System.Runtime.InteropServices;

class Program {
    static void Main(string[] args) {
        handler = new ConsoleEventDelegate(ConsoleEventCallback);
        SetConsoleCtrlHandler(handler, true);
        Console.ReadLine();
    }

    static bool ConsoleEventCallback(int eventType) {
        if (eventType == 2) {
            Console.WriteLine("Console window closing, death imminent");
        }
        return false;
    }
    static ConsoleEventDelegate handler;   // Keeps it from getting garbage collected
    // Pinvoke
    private delegate bool ConsoleEventDelegate(int eventType);
    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);

}

Beware of the restrictions. You have to respond quickly to this notification, you've got 5 seconds to complete the task. Take longer and Windows will kill your code unceremoniously. And your method is called asynchronously on a worker thread, the state of the program is entirely unpredictable so locking is likely to be required. Do make absolutely sure that an abort cannot cause trouble. For example, when saving state into a file, do make sure you save to a temporary file first and use File.Replace().

How to increase the execution timeout in php?

I know you are specifically asking about the PHP timeout, but what no one else seems to have mentioned is that there can also be a timeout on the webserver and it can look very similar to the PHP timeout.

So if you have tried:

  1. Increasing the timeout in php.ini by adding a line: max_execution_time = {number of seconds i.e. 60 for one minute}
  2. Increasing the timeout in your script itself by adding: ini_set('max_execution_time','{number of seconds i.e. 60 for one minute}');

And you have checked with the phpinfo() function that max_execution_time has indeed be increased, then you might want to try adding this to .htaccess which will make sure Apache itself does not time out:

RewriteRule .* - [E=noabort:1]
RewriteRule .* - [E=noconntimeout:1]

More info here: https://www.antropy.co.uk/blog/php-script-keeps-timing-out-despite-ini-set/

Adding to a vector of pair

You can use std::make_pair

revenue.push_back(std::make_pair("string",map[i].second));

What's the yield keyword in JavaScript?

don't forget the very helpful 'x of generator' syntax to loop through the generator. No need to use the next() function at all.

function* square(x){
    for(i=0;i<100;i++){
        x = x * 2;
        yield x;        
    }   
}

var gen = square(2);
for(x of gen){
   console.log(x);
}

Choosing a file in Python with simple Dialog

Another option to consider is Zenity: http://freecode.com/projects/zenity.

I had a situation where I was developing a Python server application (no GUI component) and hence didn't want to introduce a dependency on any python GUI toolkits, but I wanted some of my debug scripts to be parameterized by input files and wanted to visually prompt the user for a file if they didn't specify one on the command line. Zenity was a perfect fit. To achieve this, invoke "zenity --file-selection" using the subprocess module and capture the stdout. Of course this solution isn't Python-specific.

Zenity supports multiple platforms and happened to already be installed on our dev servers so it facilitated our debugging/development without introducing an unwanted dependency.

Force “landscape” orientation mode

It is now possible with the HTML5 webapp manifest. See below.


Original answer:

You can't lock a website or a web application in a specific orientation. It goes against the natural behaviour of the device.

You can detect the device orientation with CSS3 media queries like this:

@media screen and (orientation:portrait) {
    // CSS applied when the device is in portrait mode
}

@media screen and (orientation:landscape) {
    // CSS applied when the device is in landscape mode
}

Or by binding a JavaScript orientation change event like this:

document.addEventListener("orientationchange", function(event){
    switch(window.orientation) 
    {  
        case -90: case 90:
            /* Device is in landscape mode */
            break; 
        default:
            /* Device is in portrait mode */
    }
});

Update on November 12, 2014: It is now possible with the HTML5 webapp manifest.

As explained on html5rocks.com, you can now force the orientation mode using a manifest.json file.

You need to include those line into the json file:

{
    "display":      "standalone", /* Could be "fullscreen", "standalone", "minimal-ui", or "browser" */
    "orientation":  "landscape", /* Could be "landscape" or "portrait" */
    ...
}

And you need to include the manifest into your html file like this:

<link rel="manifest" href="manifest.json">

Not exactly sure what the support is on the webapp manifest for locking orientation mode, but Chrome is definitely there. Will update when I have the info.

POST: sending a post request in a url itself

Based on what you provided, it is pretty simple for what you need to do and you even have a number of ways to go about doing it. You'll need something that'll let you post a body with your request. Almost any programming language can do this as well as command line tools like cURL.

One you have your tool decided, you'll need to create your JSON body and submit it to the server.

An example using cURL would be (all in one line, minus the \ at the end of the first line):

curl -v -H "Content-Type: application/json" -X POST \
     -d '{"name":"your name","phonenumber":"111-111"}' http://www.abc.com/details

The above command will create a request that should look like the following:

POST /details HTTP/1.1
Host: www.abc.com
Content-Type: application/json
Content-Length: 44

{"name":"your name","phonenumber":"111-111"}

How to calculate distance from Wifi router using Signal Strength?

FSPL depends on two parameters: First is the frequency of radio signals;Second is the wireless transmission distance. The following formula can reflect the relationship between them.

FSPL (dB) = 20log10(d) + 20log10(f) + K

d = distance
f = frequency
K= constant that depends on the units used for d and f
If d is measured in kilometers, f in MHz, the formula is:

FSPL (dB) = 20log10(d)+ 20log10(f) + 32.44

From the Fade Margin equation, Free Space Path Loss can be computed with the following equation.

Free Space Path Loss=Tx Power-Tx Cable Loss+Tx Antenna Gain+Rx Antenna Gain - Rx Cable Loss - Rx Sensitivity - Fade Margin

With the above two Free Space Path Loss equations, we can find out the Distance in km.

Distance (km) = 10(Free Space Path Loss – 32.44 – 20log10(f))/20

The Fresnel Zone is the area around the visual line-of-sight that radio waves spread out into after they leave the antenna. You want a clear line of sight to maintain strength, especially for 2.4GHz wireless systems. This is because 2.4GHz waves are absorbed by water, like the water found in trees. The rule of thumb is that 60% of Fresnel Zone must be clear of obstacles. Typically, 20% Fresnel Zone blockage introduces little signal loss to the link. Beyond 40% blockage the signal loss will become significant.

FSPLr=17.32*v(d/4f)

d = distance [km]
f = frequency [GHz]
r = radius [m]

Source : http://www.tp-link.com/en/support/calculator/

How to pass data to view in Laravel?

It's probably worth mentioning that as of Laravel 5, passing data to the view is now done like this:

return view("blog", ["posts"=>$posts]);

Or:

return view("blog", compact("posts"));

Documentation is available here.

What is the keyguard in Android?

The lock screen works without keyguard i have tested it. The home button stops working and you can't get to task manager by holding the home key. I wish they didn't develop a new process when it used to be built into system ui or whatever. I don't see the need for the change and extra process

Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

As already said here synchronized block can use user-defined variable as lock object, when synchronized function uses only "this". And of course you can manipulate with areas of your function which should be synchronized. But everyone says that no difference between synchronized function and block which covers whole function using "this" as lock object. That is not true, difference is in byte code which will be generated in both situations. In case of synchronized block usage should be allocated local variable which holds reference to "this". And as result we will have a little bit larger size for function (not relevant if you have only few number of functions).

More detailed explanation of the difference you can find here: http://www.artima.com/insidejvm/ed2/threadsynchP.html

What is "Linting"?

Linting is the process of checking the source code for Programmatic as well as Stylistic errors. This is most helpful in identifying some common and uncommon mistakes that are made during coding.

A Lint or a Linter is a program that supports linting (verifying code quality). They are available for most languages like JavaScript, CSS, HTML, Python, etc..

Some of the useful linters are JSLint, CSSLint, JSHint, Pylint

Xcode Error: "The app ID cannot be registered to your development team."

Go to Build Settings tab, and then change the Product Bundle Identifier to another name. It works in mine.

How to automatically select all text on focus in WPF TextBox?

This seems to work well for me. It's basically a recap of some earlier posts. I just put this into my MainWindow.xaml.cs file in the constructor. I create two handlers, one for keyboard, and one for the mouse, and funnel both events into the same function, HandleGotFocusEvent, which is defined right after the constructor in the same file.

public MainWindow()
{
   InitializeComponent();

   EventManager.RegisterClassHandler(typeof(TextBox), 
      UIElement.GotKeyboardFocusEvent,
      new RoutedEventHandler(HandleGotFocusEvent), true);
   EventManager.RegisterClassHandler(typeof(TextBox),
      UIElement.GotMouseCaptureEvent,
      new RoutedEventHandler(HandleGotFocusEvent), true);   
}
private void HandleGotFocusEvent(object sender, RoutedEventArgs e)
{
   if (sender is TextBox)
      (sender as TextBox).SelectAll();
}

How to push JSON object in to array using javascript

Observation

  • If there is a single object and you want to push whole object into an array then no need to iterate the object.

Try this :

_x000D_
_x000D_
var feed = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};_x000D_
_x000D_
var data = [];_x000D_
data.push(feed);_x000D_
_x000D_
console.log(data);
_x000D_
_x000D_
_x000D_

Instead of :

_x000D_
_x000D_
var my_json = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};_x000D_
_x000D_
var data = [];_x000D_
for(var i in my_json) {_x000D_
    data.push(my_json[i]);_x000D_
}_x000D_
_x000D_
console.log(data);
_x000D_
_x000D_
_x000D_

How do I include a path to libraries in g++

To specify a directory to search for (binary) libraries, you just use -L:

-L/data[...]/lib

To specify the actual library name, you use -l:

-lfoo  # (links libfoo.a or libfoo.so)

To specify a directory to search for include files (different from libraries!) you use -I:

-I/data[...]/lib

So I think what you want is something like

g++ -g -Wall -I/data[...]/lib testing.cpp fileparameters.cpp main.cpp -o test

These compiler flags (amongst others) can also be found at the GNU GCC Command Options manual:

Execute external program

import java.io.*;

public class Code {
  public static void main(String[] args) throws Exception {
    ProcessBuilder builder = new ProcessBuilder("ls", "-ltr");
    Process process = builder.start();

    StringBuilder out = new StringBuilder();
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
        String line = null;
      while ((line = reader.readLine()) != null) {
        out.append(line);
        out.append("\n");
      }
      System.out.println(out);
    }
  }
}

Try online

How do I get the list of keys in a Dictionary?

For a hybrid dictionary, I use this:

List<string> keys = new List<string>(dictionary.Count);
keys.AddRange(dictionary.Keys.Cast<string>());

ERROR 403 in loading resources like CSS and JS in my index.php

Find out the web server user

open up terminal and type lsof -i tcp:80

This will show you the user of the web server process Here is an example from a raspberry pi running debian:

COMMAND   PID     USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
apache2  7478 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)
apache2  7664 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)
apache2  7794 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)

The user is www-data

If you give ownership of the web files to the web server:

chown www-data:www-data -R /opt/lamp/htdocs

And chmod 755 for good measure:

chmod 755 -R /opt/lamp/htdocs

Let me know how you go, maybe you need to use 'sudo' before the command, i.e. sudo chown www-data:www-data -R /opt/lamp/htdocs

if it doesn't work, please give us the output of: ls -al /opt/lamp/htdocs

Centos/Linux setting logrotate to maximum file size for all logs

It specifies the size of the log file to trigger rotation. For example size 50M will trigger a log rotation once the file is 50MB or greater in size. You can use the suffix M for megabytes, k for kilobytes, and G for gigabytes. If no suffix is used, it will take it to mean bytes. You can check the example at the end. There are three directives available size, maxsize, and minsize. According to manpage:

minsize size
              Log  files  are  rotated when they grow bigger than size bytes,
              but not before the additionally specified time interval (daily,
              weekly,  monthly, or yearly).  The related size option is simi-
              lar except that it is mutually exclusive with the time interval
              options,  and  it causes log files to be rotated without regard
              for the last rotation time.  When minsize  is  used,  both  the
              size and timestamp of a log file are considered.

size size
              Log files are rotated only if they grow bigger then size bytes.
              If size is followed by k, the size is assumed to  be  in  kilo-
              bytes.  If the M is used, the size is in megabytes, and if G is
              used, the size is in gigabytes. So size 100,  size  100k,  size
              100M and size 100G are all valid.
maxsize size
              Log files are rotated when they grow bigger than size bytes even before
              the additionally specified time interval (daily, weekly, monthly, 
              or yearly).  The related size option is  similar  except  that  it 
              is mutually exclusive with the time interval options, and it causes
              log files to be rotated without regard for the last rotation time.  
              When maxsize is used, both the size and timestamp of a log file are                  
              considered.

Here is an example:

"/var/log/httpd/access.log" /var/log/httpd/error.log {
           rotate 5
           mail [email protected]
           size 100k
           sharedscripts
           postrotate
               /usr/bin/killall -HUP httpd
           endscript
       }

Here is an explanation for both files /var/log/httpd/access.log and /var/log/httpd/error.log. They are rotated whenever it grows over 100k in size, and the old logs files are mailed (uncompressed) to [email protected] after going through 5 rotations, rather than being removed. The sharedscripts means that the postrotate script will only be run once (after the old logs have been compressed), not once for each log which is rotated. Note that the double quotes around the first filename at the beginning of this section allows logrotate to rotate logs with spaces in the name. Normal shell quoting rules apply, with ,, and \ characters supported.

moment.js 24h format

Try: moment({ // Options here }).format('HHmm'). That should give you the time in a 24 hour format.

Remove x-axis label/text in chart.js

Inspired by christutty's answer, here is a solution that modifies the source but has not been tested thoroughly. I haven't had any issues yet though.

In the defaults section, add this line around line 71:

// Boolean - Omit x-axis labels
omitXLabels: true,

Then around line 2215, add this in the buildScale method:

//if omitting x labels, replace labels with empty strings           
if(Chart.defaults.global.omitXLabels){
    var newLabels=[];
    for(var i=0;i<labels.length;i++){
        newLabels.push('');
    }
    labels=newLabels;
}

This preserves the tool tips also.

How to print like printf in Python3?

Simple printf() function from O'Reilly's Python Cookbook.

import sys
def printf(format, *args):
    sys.stdout.write(format % args)

Example output:

i = 7
pi = 3.14159265359
printf("hi there, i=%d, pi=%.2f\n", i, pi)
# hi there, i=7, pi=3.14