Programs & Examples On #N95

WinError 2 The system cannot find the file specified (Python)

I believe you need to .f file as a parameter, not as a command-single-string. same with the "--domain "+i, which i would split in two elements of the list. Assuming that:

  • you have the path set for FORTRAN executable,
  • the ~/ is indeed the correct way for the FORTRAN executable

I would change this line:

subprocess.Popen(["FORTRAN ~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain "+i])

to

subprocess.Popen(["FORTRAN", "~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain", i])

If that doesn't work, you should do a os.path.exists() for the .f file, and check that you can launch the FORTRAN executable without any path, and set the path or system path variable accordingly

[EDIT 6-Mar-2017]

As the exception, detailed in the original post, is a python exception from subprocess; it is likely that the WinError 2 is because it cannot find FORTRAN

I highly suggest that you specify full path for your executable:

for i in input:
    exe = r'c:\somedir\fortrandir\fortran.exe'
    fortran_script = r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f'
    subprocess.Popen([exe, fortran_script, "--domain", i])

if you need to convert the forward-slashes to backward-slashes, as suggested in one of the comments, you can do this:

for i in input:
    exe = os.path.normcase(r'c:\somedir\fortrandir\fortran.exe')
    fortran_script = os.path.normcase(r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
    i = os.path.normcase(i)
    subprocess.Popen([exe, fortran_script, "--domain", i])

[EDIT 7-Mar-2017]

The following line is incorrect:

exe = os.path.normcase(r'~/C:/Program Files (x86)/Silverfrost/ftn95.exe'

I am not sure why you have ~/ as a prefix for every path, don't do that.

for i in input:
    exe = os.path.normcase(r'C:/Program Files (x86)/Silverfrost/ftn95.exe'
    fortran_script = os.path.normcase(r'C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
    i = os.path.normcase(i)
    subprocess.Popen([exe, fortran_script, "--domain", i])

[2nd EDIT 7-Mar-2017]

I do not know this FORTRAN or ftn95.exe, does it need a shell to function properly?, in which case you need to launch as follows:

subprocess.Popen([exe, fortran_script, "--domain", i], shell = True)

You really need to try to launch the command manually from the working directory which your python script is operating from. Once you have the command which is actually working, then build up the subprocess command.

ORA-01653: unable to extend table by in tablespace ORA-06512

Just add a new datafile for the existing tablespace

ALTER TABLESPACE LEGAL_DATA ADD DATAFILE '/u01/oradata/userdata03.dbf' SIZE 200M;

To find out the location and size of your data files:

SELECT FILE_NAME, BYTES FROM DBA_DATA_FILES WHERE TABLESPACE_NAME = 'LEGAL_DATA';

creating Hashmap from a JSON String

You can use Google's Gson library to convert json to Hashmap. Try below code

String jsonString = "Your JSON string";
HashMap<String,String> map = new Gson().fromJson(jsonString, new TypeToken<HashMap<String, String>>(){}.getType());

conversion from string to json object android

May be below is better.

JSONObject jsonObject=null;
    try {
        jsonObject=new JSONObject();
        jsonObject.put("phonetype","N95");
        jsonObject.put("cat","wp");
        String jsonStr=jsonObject.toString();
    } catch (JSONException e) {
        e.printStackTrace();
    }

How to convert image into byte array and byte array to base64 String in android?

I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:

String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
    fis = new FileInputStream(imagefile);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
}

Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);    
byte[] b = baos.toByteArray(); 
encImage = Base64.encodeToString(b, Base64.DEFAULT);

How to convert jsonString to JSONObject in Java

To convert a string to json and the sting is like json. {"phonetype":"N95","cat":"WP"}

String Data=response.getEntity().getText().toString(); // reading the string value 
JSONObject json = (JSONObject) new JSONParser().parse(Data);
String x=(String) json.get("phonetype");
System.out.println("Check Data"+x);
String y=(String) json.get("cat");
System.out.println("Check Data"+y);

Angular2 change detection: ngOnChanges not firing for nested object

In my case it was changes in object value which the ngOnChange was not capturing. A few object values are modified in response of api call. Reinitializing the object fixed the issue and caused the ngOnChange to trigger in the child component.

Something like

 this.pagingObj = new Paging(); //This line did the magic
 this.pagingObj.pageNumber = response.PageNumber;

Make virtualenv inherit specific packages from your global site-packages

You can use the --system-site-packages and then "overinstall" the specific stuff for your virtualenv. That way, everything you install into your virtualenv will be taken from there, otherwise it will be taken from your system.

Read from database and fill DataTable

Private Function LoaderData(ByVal strSql As String) As DataTable
    Dim cnn As SqlConnection
    Dim dad As SqlDataAdapter

    Dim dtb As New DataTable
    cnn = New SqlConnection(My.Settings.mySqlConnectionString)
    Try
        cnn.Open()
        dad = New SqlDataAdapter(strSql, cnn)
        dad.Fill(dtb)
        cnn.Close()
        dad.Dispose()
    Catch ex As Exception
        cnn.Close()
        MsgBox(ex.Message)
    End Try
    Return dtb
End Function

How to hide collapsible Bootstrap 4 navbar on click

add below code in your < a > TAG

data-toggle="collapse" data-target=".navbar-collapse.show"

as shows below in every TAG

<li class="nav-item">
   <a class="nav-link" href="#about-us" data-toggle="collapse" data-target=".navbar-collapse.show">About</a>
</li>

How to loop through all the files in a directory in c # .net?

You can have a look at this page showing Deep Folder Copy, it uses recursive means to iterate throught the files and has some really nice tips, like filtering techniques etc.

http://www.codeproject.com/Tips/512208/Folder-Directory-Deep-Copy-including-sub-directori

How do you create nested dict in Python?

This thing is empty nested list from which ne will append data to empty dict

ls = [['a','a1','a2','a3'],['b','b1','b2','b3'],['c','c1','c2','c3'], 
['d','d1','d2','d3']]

this means to create four empty dict inside data_dict

data_dict = {f'dict{i}':{} for i in range(4)}
for i in range(4):
    upd_dict = {'val' : ls[i][0], 'val1' : ls[i][1],'val2' : ls[i][2],'val3' : ls[i][3]}

    data_dict[f'dict{i}'].update(upd_dict)

print(data_dict)

The output

{'dict0': {'val': 'a', 'val1': 'a1', 'val2': 'a2', 'val3': 'a3'}, 'dict1': {'val': 'b', 'val1': 'b1', 'val2': 'b2', 'val3': 'b3'},'dict2': {'val': 'c', 'val1': 'c1', 'val2': 'c2', 'val3': 'c3'}, 'dict3': {'val': 'd', 'val1': 'd1', 'val2': 'd2', 'val3': 'd3'}}

php create object without class

you can always use new stdClass(). Example code:

   $object = new stdClass();
   $object->property = 'Here we go';

   var_dump($object);
   /*
   outputs:

   object(stdClass)#2 (1) {
      ["property"]=>
      string(10) "Here we go"
    }
   */

Also as of PHP 5.4 you can get same output with:

$object = (object) ['property' => 'Here we go'];

How to delete/truncate tables from Hadoop-Hive?

You need to drop the table and then recreate it and then load it again

How to make google spreadsheet refresh itself every 1 minute?

GOOGLEFINANCE can have a 20 minutes delay, so refreshing every minute would not really help.

Instead of GOOGLEFINANCE you can use different source. I'm using this RealTime stock prices(I tried a couple but this is the easiest by-far to implement. They have API that retuen JSON { Name: CurrentPrice }

Here's a little script you can use in Google Sheets(Tools->Script Editor)

function GetStocksPrice() {      
   var url = 'https://financialmodelingprep.com/api/v3/stock/real-time- 
   price/AVP,BAC,CHK,CY,GE,GPRO,HIMX,IMGN,MFG,NIO,NMR,SSSS,UCTT,UMC,ZNGA';
   var response = UrlFetchApp.fetch(url);

   // convert json string to json object
   var jsonSignal = JSON.parse(response);    

  // define an array of all the object keys
  var headerRow = Object.keys(jsonSignal);
  // define an array of all the object values
  var values = headerRow.map(function(key){ return jsonSignal[key]});   
  var data = values[0];

  // get sheet by ID -  
  // you can get the sheet unqiue ID from the your current sheet url
  var jsonSheet = SpreadsheetApp.openById("Your Sheet UniqueID");  
  //var name = jsonSheet.getName();

  var sheet = jsonSheet.getSheetByName('Sheet1'); 

  // the column to put the data in -> Y
  var letter = "F";

  // start from line 
  var index = 4;
  data.forEach(function( row, index2 ) { 

     var keys = Object.keys(row);
     var value2 = row[keys[1]];            

     // set value loction
     var cellXY = letter +  index;      
     sheet.getRange(cellXY).setValue(value2);  
  
     index = index + 1;    
 });  
}

Now you need to add a trigger that will execute every minute.

  1. Go to Project Triggers -> click on the Watch icon next to the Save icon
  2. Add Trigger
  3. In -> Choose which function to run -> GetStocksPrice
  4. In -> Select event source -> Time-driven
  5. In -> Select type of time based trigger -> Minutes timer
  6. In -> Select minute interval -> Every minute

And your set :)

How to force keyboard with numbers in mobile website in Android

inputmode according to WHATWG spec is the the default method.

For iOS devices adding pattern could also help.

For backward compatibility use type as well since Chrome use these as of version 66.

<input
  inputmode="numeric"
  pattern="[0-9]*"
  type="number"
/>

When is JavaScript synchronous?

JavaScript is single threaded and has a synchronous execution model. Single threaded means that one command is being executed at a time. Synchronous means one at a time i.e. one line of code is being executed at time in order the code appears. So in JavaScript one thing is happening at a time.

Execution Context

The JavaScript engine interacts with other engines in the browser. In the JavaScript execution stack there is global context at the bottom and then when we invoke functions the JavaScript engine creates new execution contexts for respective functions. When the called function exits its execution context is popped from the stack, and then next execution context is popped and so on...

For example

function abc()
{
   console.log('abc');
}


function xyz()
{
   abc()
   console.log('xyz');
}
var one = 1;
xyz();

In the above code a global execution context will be created and in this context var one will be stored and its value will be 1... when the xyz() invocation is called then a new execution context will be created and if we had defined any variable in xyz function those variables would be stored in the execution context of xyz(). In the xyz function we invoke abc() and then the abc() execution context is created and put on the execution stack... Now when abc() finishes its context is popped from stack, then the xyz() context is popped from stack and then global context will be popped...

Now about asynchronous callbacks; asynchronous means more than one at a time.

Just like the execution stack there is the Event Queue. When we want to be notified about some event in the JavaScript engine we can listen to that event, and that event is placed on the queue. For example an Ajax request event, or HTTP request event.

Whenever the execution stack is empty, like shown in above code example, the JavaScript engine periodically looks at the event queue and sees if there is any event to be notified about. For example in the queue there were two events, an ajax request and a HTTP request. It also looks to see if there is a function which needs to be run on that event trigger... So the JavaScript engine is notified about the event and knows the respective function to execute on that event... So the JavaScript engine invokes the handler function, in the example case, e.g. AjaxHandler() will be invoked and like always when a function is invoked its execution context is placed on the execution context and now the function execution finishes and the event ajax request is also removed from the event queue... When AjaxHandler() finishes the execution stack is empty so the engine again looks at the event queue and runs the event handler function of HTTP request which was next in queue. It is important to remember that the event queue is processed only when execution stack is empty.

For example see the code below explaining the execution stack and event queue handling by Javascript engine.

function waitfunction() {
    var a = 5000 + new Date().getTime();
    while (new Date() < a){}
    console.log('waitfunction() context will be popped after this line');
}

function clickHandler() {
    console.log('click event handler...');   
}

document.addEventListener('click', clickHandler);


waitfunction(); //a new context for this function is created and placed on the execution stack
console.log('global context will be popped after this line');

And

<html>
    <head>

    </head>
    <body>

        <script src="program.js"></script>
    </body>
</html>

Now run the webpage and click on the page, and see the output on console. The output will be

waitfunction() context will be popped after this line
global context will be emptied after this line
click event handler...

The JavaScript engine is running the code synchronously as explained in the execution context portion, the browser is asynchronously putting things in event queue. So the functions which take a very long time to complete can interrupt event handling. Things happening in a browser like events are handled this way by JavaScript, if there is a listener supposed to run, the engine will run it when the execution stack is empty. And events are processed in the order they happen, so the asynchronous part is about what is happening outside the engine i.e. what should the engine do when those outside events happen.

So JavaScript is always synchronous.

How to validate a file upload field using Javascript/jquery

My function will check if the user has selected the file or not and you can also check whether you want to allow that file extension or not.

Try this:

<input type="file" name="fileUpload" onchange="validate_fileupload(this.value);">

function validate_fileupload(fileName)
{
    var allowed_extensions = new Array("jpg","png","gif");
    var file_extension = fileName.split('.').pop().toLowerCase(); // split function will split the filename by dot(.), and pop function will pop the last element from the array which will give you the extension as well. If there will be no extension then it will return the filename.

    for(var i = 0; i <= allowed_extensions.length; i++)
    {
        if(allowed_extensions[i]==file_extension)
        {
            return true; // valid file extension
        }
    }

    return false;
}

Getting the array length of a 2D array in Java

Try this following program for 2d array in java:

public class ArrayTwo2 {
    public static void main(String[] args) throws  IOException,NumberFormatException{
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int[][] a;
        int sum=0;
        a=new int[3][2];
        System.out.println("Enter array with 5 elements");
        for(int i=0;i<a.length;i++)
        {
            for(int j=0;j<a[0].length;j++)
            {
            a[i][j]=Integer.parseInt(br.readLine());
            }
        }
        for(int i=0;i<a.length;i++)
        {
            for(int j=0;j<a[0].length;j++)
            {
            System.out.print(a[i][j]+"  ");
            sum=sum+a[i][j];
            }
        System.out.println();   
        //System.out.println("Array Sum: "+sum);
        sum=0;
        }
    }
}

Java: How to convert a File object to a String object in java?

I use apache common IO to read a text file into a single string

String str = FileUtils.readFileToString(file);

simple and "clean". you can even set encoding of the text file with no hassle.

String str = FileUtils.readFileToString(file, "UTF-8");

setBackground vs setBackgroundDrawable (Android)

seems that currently there is no difference between the 2 functions, as shown on the source code (credit to this post) :

public void setBackground(Drawable background) {
    //noinspection deprecation
    setBackgroundDrawable(background);
}

@Deprecated
public void setBackgroundDrawable(Drawable background) { ... }

so it's just a naming decision, similar to the one with fill-parent vs match-parent .

Why Anaconda does not recognize conda command?

For Windows

Go to Control Panel\System and Security\System\Advanced System Settings then look for Environment Variables.

Your user variables should contain Path=Path\to\Anaconda3\Scripts.

You need to figure where your Anaconda3 folder is (i.e. the path to this folder) . Mine was in C:\Users.

For Linux

You need to add conda to PATH. To do so, type:

export PATH=/path/to/anaconda3/bin:$PATH.

Same thing, you need to figure the path to anaconda3 folder (Usually, the path is stored in $HOME)

If you don't want to do this everytime you start a session, you can also add conda to PATH in your .bashrc file:

echo 'export PATH=/path/to/anaconda3/bin:$PATH' >> ~/.bashrc

How to fix error Base table or view not found: 1146 Table laravel relationship table?

Schema::table is to modify an existing table, use Schema::create to create new.

Getting DOM elements by classname

There is also another approach without the use of DomXPath or Zend_Dom_Query.

Based on dav's original function, I wrote the following function that returns all the children of the parent node whose tag and class match the parameters.

function getElementsByClass(&$parentNode, $tagName, $className) {
    $nodes=array();

    $childNodeList = $parentNode->getElementsByTagName($tagName);
    for ($i = 0; $i < $childNodeList->length; $i++) {
        $temp = $childNodeList->item($i);
        if (stripos($temp->getAttribute('class'), $className) !== false) {
            $nodes[]=$temp;
        }
    }

    return $nodes;
}

suppose you have a variable $html the following HTML:

<html>
 <body>
  <div id="content_node">
    <p class="a">I am in the content node.</p>
    <p class="a">I am in the content node.</p>
    <p class="a">I am in the content node.</p>    
  </div>
  <div id="footer_node">
    <p class="a">I am in the footer node.</p>
  </div>
 </body>
</html>

use of getElementsByClass is as simple as:

$dom = new DOMDocument('1.0', 'utf-8');
$dom->loadHTML($html);
$content_node=$dom->getElementById("content_node");

$div_a_class_nodes=getElementsByClass($content_node, 'div', 'a');//will contain the three nodes under "content_node".

PHP exec() vs system() vs passthru()

It really all comes down to how you want to handle output that the command might return and whether you want your PHP script to wait for the callee program to finish or not.

  • exec executes a command and passes output to the caller (or returns it in an optional variable).

  • passthru is similar to the exec() function in that it executes a command . This function should be used in place of exec() or system() when the output from the Unix command is binary data which needs to be passed directly back to the browser.

  • system executes an external program and displays the output, but only the last line.

If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.

CURRENT_DATE/CURDATE() not working as default DATE value

create table the_easy_way(
  capture_ts DATETIME DEFAULT CURRENT_TIMESTAMP,
  capture_dt DATE AS (DATE(capture_ts))
)

(MySQL 5.7)

How do I parse a string to a float or int?

Here's another interpretation of your question (hint: it's vague). It's possible you're looking for something like this:

def parseIntOrFloat( aString ):
    return eval( aString )

It works like this...

>>> parseIntOrFloat("545.2222")
545.22220000000004
>>> parseIntOrFloat("545")
545

Theoretically, there's an injection vulnerability. The string could, for example be "import os; os.abort()". Without any background on where the string comes from, however, the possibility is theoretical speculation. Since the question is vague, it's not at all clear if this vulnerability actually exists or not.

What is an ORM, how does it work, and how should I use one?

An ORM (Object Relational Mapper) is a piece/layer of software that helps map your code Objects to your database.

Some handle more aspects than others...but the purpose is to take some of the weight of the Data Layer off of the developer's shoulders.

Here's a brief clip from Martin Fowler (Data Mapper):

Patterns of Enterprise Application Architecture Data Mappers

How do I create a Bash alias?

The config file for scripts and programs is ~/.bashrc and the config file that gets loaded when you use Terminal is ~/.bash_login.

I think the best way is to just have everything in ~/.bashrc.

For your specific question just enter (this will overwrite any existing ~/.bashrc):

echo "alias blah=\"/usr/bin/blah\"" >>~/.bashrc

into the Terminal and a ~/.bashrc file will be created with your new alises. After that just edit the file to add new aliases, functions, settings etc.

Retrieve only the queried element in an object array in MongoDB collection

Along with $project it will be more appropriate other wise matching elements will be clubbed together with other elements in document.

db.test.aggregate(
  { "$unwind" : "$shapes" },
  { "$match" : { "shapes.color": "red" } },
  { 
    "$project": {
      "_id":1,
      "item":1
    }
  }
)

Windows-1252 to UTF-8 encoding

If you are sure your files are either UTF-8 or Windows 1252 (or Latin1), you can take advantage of the fact that recode will exit with an error if you try to convert an invalid file.

While utf8 is valid Win-1252, the reverse is not true: win-1252 is NOT valid UTF-8. So:

recode utf8..utf16 <unknown.txt >/dev/null || recode cp1252..utf8 <unknown.txt >utf8-2.txt

Will spit out errors for all cp1252 files, and then proceed to convert them to UTF8.

I would wrap this into a cleaner bash script, keeping a backup of every converted file.

Before doing the charset conversion, you may wish to first ensure you have consistent line-endings in all files. Otherwise, recode will complain because of that, and may convert files which were already UTF8, but just had the wrong line-endings.

Sending POST data without form

Send your data with SESSION rather than post.

session_start();
$_SESSION['foo'] = "bar";

On the page where you recieve the request, if you absolutely need POST data (some weird logic), you can do this somwhere at the beginning:

$_POST['foo'] = $_SESSION['foo'];

The post data will be valid just the same as if it was sent with POST.

Then destroy the session (or just unset the fields if you need the session for other purposes).

It is important to destroy a session or unset the fields, because unlike POST, SESSION will remain valid until you explicitely destroy it or until the end of browser session. If you don't do it, you can observe some strange results. For example: you use sesson for filtering some data. The user switches the filter on and gets filtered data. After a while, he returns to the page and expects the filter to be reset, but it's not: he still sees filtered data.

Check that a variable is a number in UNIX shell

Here is the test without any regular expressions (tcsh code):

Create a file checknumber:

#! /usr/bin/env tcsh
if ( "$*" == "0" ) then
    exit 0 # number
else
    ((echo "$*" | bc) > /tmp/tmp.txt) >& /dev/null
    set tmp = `cat /tmp/tmp.txt`
    rm -f /tmp/tmp/txt
    if ( "$tmp" == "" || $tmp == 0 ) then
        exit 1 # not a number
    else
        exit 0 # number
    endif

endif

and run

chmod +x checknumber

Use

checknumber -3.45

and you'll got the result as errorlevel ($?).

You can optimise it easily.

Unable to Git-push master to Github - 'origin' does not appear to be a git repository / permission denied

I have the same problem and i think the firewall is blocking the git protocol. So in the end I have to resort to using https:// to fetch and push. However this will always prompt the user to enter the password...

here is the example what working for me (just to share with those cant use git:// protocol :)

git fetch https://[user-name]@github.com/[user-name]/[project].git

if the above works, you can remove the origin and replace with

git remote rm origin  
git remote add origin https://[user-name]@github.com/[user-name]/[project].git

iterating quickly through list of tuples

The code can be cleaned up, but if you are using a list to store your tuples, any such lookup will be O(N).

If lookup speed is important, you should use a dict to store your tuples. The key should be the 0th element of your tuples, since that's what you're searching on. You can easily create a dict from your list:

my_dict = dict(my_list)

Then, (VALUE, my_dict[VALUE]) will give you your matching tuple (assuming VALUE exists).

How to use boolean datatype in C?

As an alternative to James McNellis answer, I always try to use enumeration for the bool type instead of macros: typedef enum bool {false=0; true=1;} bool;. It is safer b/c it lets the compiler do type checking and eliminates macro expansion races

Google server putty connect 'Disconnected: No supported authentication methods available (server sent: publickey)

You need to use an SSH key to login to your instance.

The GCE documentation explains the process here.

How to keep environment variables when using sudo

The trick is to add environment variables to sudoers file via sudo visudo command and add these lines:

Defaults env_keep += "ftp_proxy http_proxy https_proxy no_proxy"

taken from ArchLinux wiki.

For Ubuntu 14, you need to specify in separate lines as it returns the errors for multi-variable lines:

Defaults  env_keep += "http_proxy"
Defaults  env_keep += "https_proxy"
Defaults  env_keep += "HTTP_PROXY"
Defaults  env_keep += "HTTPS_PROXY"

How to get a matplotlib Axes instance to plot to?

Use the gca ("get current axes") helper function:

ax = plt.gca()

Example:

import matplotlib.pyplot as plt
import matplotlib.finance
quotes = [(1, 5, 6, 7, 4), (2, 6, 9, 9, 6), (3, 9, 8, 10, 8), (4, 8, 8, 9, 8), (5, 8, 11, 13, 7)]
ax = plt.gca()
h = matplotlib.finance.candlestick(ax, quotes)
plt.show()

enter image description here

Find and Replace string in all files recursive using grep and sed

The GNU guys REALLY messed up when they introduced recursive file searching to grep. grep is for finding REs in files and printing the matching line (g/re/p remember?) NOT for finding files. There's a perfectly good tool with a very obvious name for FINDing files. Whatever happened to the UNIX mantra of do one thing and do it well?

Anyway, here's how you'd do what you want using the traditional UNIX approach (untested):

find /path/to/folder -type f -print |
while IFS= read -r file
do
   awk -v old="$oldstring" -v new="$newstring" '
      BEGIN{ rlength = length(old) }
      rstart = index($0,old) { $0 = substr($0,rstart-1) new substr($0,rstart+rlength) }
      { print }
   ' "$file" > tmp &&
   mv tmp "$file"
done

Not that by using awk/index() instead of sed and grep you avoid the need to escape all of the RE metacharacters that might appear in either your old or your new string plus figure out a character to use as your sed delimiter that can't appear in your old or new strings, and that you don't need to run grep since the replacement will only occur for files that do contain the string you want. Having said all of that, if you don't want the file timestamp to change if you don't modify the file, then just do a diff on tmp and the original file before doing the mv or throw in an fgrep -q before the awk.

Caveat: The above won't work for file names that contain newlines. If you have those then let us know and we can show you how to handle them.

SQL query question: SELECT ... NOT IN

SELECT distinct idCustomer FROM reservations
WHERE DATEPART ( hour, insertDate) < 2
  and idCustomer is not null

Make sure your list parameter does not contain null values.

Here's an explanation:

WHERE field1 NOT IN (1, 2, 3, null)

is the same as:

WHERE NOT (field1 = 1 OR field1 = 2 OR field1 = 3 OR field1 = null)
  • That last comparision evaluates to null.
  • That null is OR'd with the rest of the boolean expression, yielding null. (*)
  • null is negated, yielding null.
  • null is not true - the where clause only keeps true rows, so all rows are filtered.

(*) Edit: this explanation is pretty good, but I wish to address one thing to stave off future nit-picking. (TRUE OR NULL) would evaluate to TRUE. This is relevant if field1 = 3, for example. That TRUE value would be negated to FALSE and the row would be filtered.

How to avoid "Permission denied" when using pip with virtualenv

While creating virtualenv if you use sudo the directory is created with root privileges.So when you try to install a package with non-sudo user you won't have permission to install into it. So always create virtualenv without sudo and install without sudo.

You can also copy packages installed on global python to virtualenv.

cp -r /lib/python/site-packages/* virtualenv/lib/python/site-packages/

Converting URL to String and back again

Swift 3 used with UIWebViewDelegate shouldStartLoadWith

  func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {

    let urlPath: String = (request.url?.absoluteString)!
    print(urlPath)
    if urlPath.characters.last == "#" {
        return false
    }else{
        return true
    }

}

How can I open a website in my web browser using Python?

If you want to open a specific browser (e.g. Chrome and Chromium) with command line options like full screen or kiosk mode and also want to be able to kill it later on, then this might work for you:

from threading import Timer
from time import sleep

import subprocess
import platform

# Hint 1: to enable F11 use --start-fullscreen instead of --kiosk, otherwise Alt+F4 to close the browser   
# Hint 2: fullscreen will only work if chrome is not already running

platform_browser = {
'Windows': r'"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --kiosk http://stackoverflow.com',
'Linux' : ['/usr/bin/chromium-browser', '--kiosk', 'http://stackoverflow.com']
}

browser = None
def open_browser():
    global browser

    platform_name = platform.system()

    if platform_name in  platform_browser:        
        browser = subprocess.Popen(platform_browser[platform_name])
    else:
        print(":-(")

Timer(1, open_browser).start() # delayed start, give e.g. your own web server time to launch

sleep(20) # start e.g. your python web server here instead

browser.kill()

Send JSON via POST in C# and Receive the JSON returned?

You can also use the PostAsJsonAsync() method available in HttpClient()

_x000D_
_x000D_
   var requestObj= JsonConvert.SerializeObject(obj);_x000D_
   HttpResponseMessage response = await    client.PostAsJsonAsync($"endpoint",requestObj).ConfigureAwait(false);
_x000D_
_x000D_
_x000D_

Angular - res.json() is not a function

Don't need to use this method:

 .map((res: Response) => res.json() );

Just use this simple method instead of the previous method. hopefully you'll get your result:

.map(res => res );

Launch custom android application from android browser

For example, You have next things:

A link to open your app: http://example.com

The package name of your app: com.example.mypackage

Then you need to do next:

  1. Add an intent filter to your Activity (Can be any activity you want. For more info check the documentation).

    <activity
         android:name=".MainActivity">
    
         <intent-filter android:label="@string/filter_title_view_app_from_web">
             <action android:name="android.intent.action.VIEW" />
             <category android:name="android.intent.category.DEFAULT" />
             <category android:name="android.intent.category.BROWSABLE" />
             <!-- Accepts URIs that begin with "http://example.com" -->
    
             <data
                 android:host="example.com"
                 android:scheme="http" />
         </intent-filter>
    
         <intent-filter>
             <action android:name="android.intent.action.MAIN" />
             <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
    
     </activity> 
    
  2. Create a HTML file to test the link or use this methods.

    Open your Activity directly (just open your Activity, without a choosing dialog).

    Open this link with browser or your programm (by choosing dialog).

  3. Use Mobile Chrome to test

  4. That's it.

And its not necessary to publish app in market to test deep linking =)

Also, for more information, check documentation and useful presentation.

Excel VBA App stops spontaneously with message "Code execution has been halted"

Thanks to everyone for their input. This problem got solved by choosing REPAIR in Control Panel. I guess this explicitly re-registers some of Office's native COM components and does stuff that REINSTALL doesn't. I expect the latter just goes through a checklist and sometimes accepts what's there if it's already installed, maybe. I then had a separate issue with registering my own .NET dll for COM interop on the user's machine (despite this also working on other machines) though I think this was my error rather than Microsoft. Thanks again, I really appreciate it.

How can I center an image in Bootstrap?

Since the img is an inline element, Just use text-center on it's container. Using mx-auto will center the container (column) too.

<div class="row">
    <div class="col-4 mx-auto text-center">
        <img src="..">
    </div>
</div>

By default, images are display:inline. If you only want the center the image (and not the other column content), make the image display:block using the d-block class, and then mx-auto will work.

<div class="row">
  <div class="col-4">
    <img class="mx-auto d-block" src="..">
  </div>
</div>

Demo: http://codeply.com/go/iakGGLdB8s

Android: How to rotate a bitmap on a center point

I came back to this problem now that we are finalizing the game and I just thought to post what worked for me.

This is the method for rotating the Matrix:

this.matrix.reset();
this.matrix.setTranslate(this.floatXpos, this.floatYpos);
this.matrix.postRotate((float)this.direction, this.getCenterX(), this.getCenterY()); 

(this.getCenterX() is basically the bitmaps X position + the bitmaps width / 2)

And the method for Drawing the bitmap (called via a RenderManager Class):

canvas.drawBitmap(this.bitmap, this.matrix, null);

So it is prettey straight forward but I find it abit strange that I couldn't get it to work by setRotate followed by postTranslate. Maybe some knows why this doesn't work? Now all the bitmaps rotate properly but it is not without some minor decrease in bitmap quality :/

Anyways, thanks for your help!

At runtime, find all classes in a Java application that extend a base class

Think about this from an aspect-oriented point of view; what you want to do, really, is know all the classes at runtime that HAVE extended the Animal class. (I think that's a slightly more accurate description of your problem than your title; otherwise, I don't think you have a runtime question.)

So what I think you want is to create a constructor of your base class (Animal) which adds to your static array (I prefer ArrayLists, myself, but to each their own) the type of the current Class which is being instantiated.

So, roughly;

public abstract class Animal
    {
    private static ArrayList<Class> instantiatedDerivedTypes;
    public Animal() {
        Class derivedClass = this.getClass();
        if (!instantiatedDerivedClass.contains(derivedClass)) {
            instantiatedDerivedClass.Add(derivedClass);
        }
    }

Of course, you'll need a static constructor on Animal to initialize instantiatedDerivedClass... I think this'll do what you probably want. Note that this is execution-path dependent; if you have a Dog class that derives from Animal that never gets invoked, you won't have it in your Animal Class list.

How to find the socket buffer size of linux

Whilst, as has been pointed out, it is possible to see the current default socket buffer sizes in /proc, it is also possible to check them using sysctl (Note: Whilst the name includes ipv4 these sizes also apply to ipv6 sockets - the ipv6 tcp_v6_init_sock() code just calls the ipv4 tcp_init_sock() function):

 sysctl net.ipv4.tcp_rmem
 sysctl net.ipv4.tcp_wmem

However, the default socket buffers are just set when the sock is initialised but the kernel then dynamically sizes them (unless set using setsockopt() with SO_SNDBUF). The actual size of the buffers for currently open sockets may be inspected using the ss command (part of the iproute package), which can also provide a bunch more info on sockets like congestion control parameter etc. E.g. To list the currently open TCP (t option) sockets and associated memory (m) information:

ss -tm

Here's some example output:

State       Recv-Q Send-Q        Local Address:Port        Peer Address:Port
ESTAB       0      0             192.168.56.102:ssh        192.168.56.1:56328
skmem:(r0,rb369280,t0,tb87040,f0,w0,o0,bl0,d0)

Here's a brief explanation of skmem (socket memory) - for more info you'll need to look at the kernel sources (e.g. sock.h):

r:sk_rmem_alloc
rb:sk_rcvbuf          # current receive buffer size
t:sk_wmem_alloc
tb:sk_sndbuf          # current transmit buffer size
f:sk_forward_alloc
w:sk_wmem_queued      # persistent transmit queue size
o:sk_omem_alloc
bl:sk_backlog
d:sk_drops

How to echo (or print) to the js console with php

This will work with either an array, an object or a variable and also escapes the special characters that may break your JS :

function debugToConsole($msg) { 
        echo "<script>console.log(".json_encode($msg).")</script>";
}

Edit : Added json_encode to the echo statement. This will prevent your script from breaking if there are quotes in your $msg variable.

VB.Net .Clear() or txtbox.Text = "" textbox clear methods

The two methods are 100% equivalent.

I’m not sure why Microsoft felt the need to include this extra Clear method but since it’s there, I recommend using it, as it clearly expresses its purpose.

Error: Uncaught SyntaxError: Unexpected token <

I got this error while using the web app with firebase. It was due to not including the desired libraries in the index.html

To fix this in the development environment, I added following line of code in the index.html

<script src="https://www.gstatic.com/firebasejs/8.1.1/firebase.js"></script>

Use the necessary libraries instead of importing all the js sdk when you are planning to deploy for production.

How to "wait" a Thread in Android

I just add this line exactly as it appears below (if you need a second delay):

try {
    Thread.sleep(1000);
} catch(InterruptedException e) {
    // Process exception
}

I find the catch IS necessary (Your app can crash due to Android OS as much as your own code).

How to break out of multiple loops?

My first instinct would be to refactor the nested loop into a function and use return to break out.

Can pm2 run an 'npm start' script

pm2 start ./bin/www

can running

if you wanna multiple server deploy you can do that. instead of pm2 start npm -- start

Transparent background in JPEG image

How can I set a transparent background on JPEG image?

If you intend to keep the image as a JPEG then you can't. As others have suggested, convert it to PNG and add an alpha channel.

Android 6.0 multiple permissions

Use helper like this (permissions names do not matter).

public class MyPermission {

private static final int PERMISSION_REQUEST_ALL = 127;
private MainActivity mMainActivity;

MyPermission(MainActivity mainActivity) {
    mMainActivity = mainActivity;
}

public static boolean hasPermission(String permission, Context context) {
    if (isNewPermissionModel()) {
        return (ActivityCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED);
    }
    return true;
}

private static boolean hasPermissions(Context context, String... permissions) {
    if (isNewPermissionModel() && context != null && permissions != null) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
    }
    return true;
}

private static boolean shouldShowRationale(Activity activity, String permission) {
    return isNewPermissionModel() && ActivityCompat.shouldShowRequestPermissionRationale(activity, permission);
}

private static boolean isNewPermissionModel() {
    return VERSION.SDK_INT > VERSION_CODES.LOLLIPOP_MR1;
}


/**
 * check all permissions
 */
void checkAll() {
    //check dangerous permissions, make request if need (Android will ask only for the ones it needs)
    String[] PERMISSIONS = {
            permission.READ_CALENDAR,           
            permission.ACCESS_COARSE_LOCATION   
    };

    if (!hasPermissions(mMainActivity, PERMISSIONS)) {
        ActivityCompat.requestPermissions(mMainActivity, PERMISSIONS, PERMISSION_REQUEST_ALL);
    }
}

void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if (requestCode == PERMISSION_REQUEST_ALL) {
        if (grantResults.length > 0) {
            //for not granted
            for (int i = 0; i < permissions.length; i++) {

                if (permissions[i].equals(permission.READ_CALENDAR)) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        smartRequestPermissions(permission.READ_CALENDAR, R.string.permission_required_dialog_read_calendar);
                    }
                } else if (permissions[i].equals(permission.ACCESS_COARSE_LOCATION)) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        smartRequestPermissions(permission.ACCESS_COARSE_LOCATION, R.string.permission_required_dialog_access_coarse_location);
                    }
                }

            }
        }
    }
}

private void smartRequestPermissions(final String permissionName, int permissionRequiredDialog) {
    if (shouldShowRationale(mMainActivity, permissionName)) {// If the user turned down the permission request in the past and chose the Don't ask again option in the permission request system dialog, this method returns false.

        //Show an explanation to the user with action
        mMainActivity.mSnackProgressBarManager.show(
                new SnackProgressBar(
                        SnackProgressBar.TYPE_ACTION, mMainActivity.getString(permissionRequiredDialog)
                )
                        .setAction("OK", new OnActionClickListener() {
                            @Override
                            public void onActionClick() {
                                checkAll();
                            }
                        })
                        .setSwipeToDismiss(true).setAllowUserInput(true)
                , MainActivity.SNACKBAR_WARNING_DURATION
        );

    } // else do nothing
}

}

Use of Finalize/Dispose method in C#

From what I know, it's highly recommended NOT to use the Finalizer / Destructor:

public ~MyClass() {
  //dont use this
}

Mostly, this is due to not knowing when or IF it will be called. The dispose method is much better, especially if you us using or dispose directly.

using is good. use it :)

What is attr_accessor in Ruby?

Basically they fake publicly accessible data attributes, which Ruby doesn't have.

django order_by query set, ascending and descending

67

Reserved.objects.filter(client=client_id).order_by('-check_in')

'-' is indicates Descending order and for Ascending order just give class attribute

Purpose of __repr__ method?

The __repr__ method simply tells Python how to print objects of a class

How to hide a navigation bar from first ViewController in Swift?

 private func setupView() {
        view.backgroundColor = .white
        navigationController?.setNavigationBarHidden(true, animated: false)
    }

Trouble using ROW_NUMBER() OVER (PARTITION BY ...)

A bit involved. Easiest would be to refer to this SQL Fiddle I created for you that produces the exact result. There are ways you can improve it for performance or other considerations, but this should hopefully at least be clearer than some alternatives.

The gist is, you get a canonical ranking of your data first, then use that to segment the data into groups, then find an end date for each group, then eliminate any intermediate rows. ROW_NUMBER() and CROSS APPLY help a lot in doing it readably.


EDIT 2019:

The SQL Fiddle does in fact seem to be broken, for some reason, but it appears to be a problem on the SQL Fiddle site. Here's a complete version, tested just now on SQL Server 2016:

CREATE TABLE Source
(
  EmployeeID int,
  DateStarted date,
  DepartmentID int
)

INSERT INTO Source
VALUES
(10001,'2013-01-01',001),
(10001,'2013-09-09',001),
(10001,'2013-12-01',002),
(10001,'2014-05-01',002),
(10001,'2014-10-01',001),
(10001,'2014-12-01',001)


SELECT *, 
  ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS EntryRank,
  newid() as GroupKey,
  CAST(NULL AS date) AS EndDate
INTO #RankedData
FROM Source
;

UPDATE #RankedData
SET GroupKey = beginDate.GroupKey
FROM #RankedData sup
  CROSS APPLY 
  (
    SELECT TOP 1 GroupKey
    FROM #RankedData sub 
    WHERE sub.EmployeeID = sup.EmployeeID AND
      sub.DepartmentID = sup.DepartmentID AND
      NOT EXISTS 
        (
          SELECT * 
          FROM #RankedData bot 
          WHERE bot.EmployeeID = sup.EmployeeID AND
            bot.EntryRank BETWEEN sub.EntryRank AND sup.EntryRank AND
            bot.DepartmentID <> sup.DepartmentID
        )
      ORDER BY DateStarted ASC
    ) beginDate (GroupKey);

UPDATE #RankedData
SET EndDate = nextGroup.DateStarted
FROM #RankedData sup
  CROSS APPLY 
  (
    SELECT TOP 1 DateStarted
    FROM #RankedData sub
    WHERE sub.EmployeeID = sup.EmployeeID AND
      sub.DepartmentID <> sup.DepartmentID AND
      sub.EntryRank > sup.EntryRank
    ORDER BY EntryRank ASC
  ) nextGroup (DateStarted);

SELECT * FROM 
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY GroupKey ORDER BY EntryRank ASC) AS GroupRank FROM #RankedData
) FinalRanking
WHERE GroupRank = 1
ORDER BY EntryRank;

DROP TABLE #RankedData
DROP TABLE Source

How to master AngularJS?

The video AngularJS Fundamentals In 60-ish Minutes provides a very good introduction and overview.

I would also highly recomend the AngularJS book from O'Reilly, mentioned by @Atropo.

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of its dependencies could not be resolved

his issue is happening due to change of protocol from http to https for central repository. please refer following link for more details. https://support.sonatype.com/hc/en-us/articles/360041287334-Central-501-HTTPS-Required 

In order to fix the problem, copy following into your pom.ml file. This will set the repository url to use https.

<repositories>
        <repository>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <id>central</id>
            <name>Central Repository</name>
            <url>https://repo.maven.apache.org/maven2</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <releases>
                <updatePolicy>never</updatePolicy>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <id>central</id>
            <name>Central Repository</name>
            <url>https://repo.maven.apache.org/maven2</url>
        </pluginRepository>
    </pluginRepositories>

oracle SQL how to remove time from date

You can use TRUNC on DateTime to remove Time part of the DateTime. So your where clause can be:

AND TRUNC(p1.PA_VALUE) >= TO_DATE('25/10/2012', 'DD/MM/YYYY')

The TRUNCATE (datetime) function returns date with the time portion of the day truncated to the unit specified by the format model.

HTTP error 403 in Python 3 Web Scraping

"This is probably because of mod_security or some similar server security feature which blocks known

spider/bot

user agents (urllib uses something like python urllib/3.3.0, it's easily detected)" - as already mentioned by Stefano Sanfilippo

from urllib.request import Request, urlopen
url="https://stackoverflow.com/search?q=html+error+403"
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})

web_byte = urlopen(req).read()

webpage = web_byte.decode('utf-8')

The web_byte is a byte object returned by the server and the content type present in webpage is mostly utf-8. Therefore you need to decode web_byte using decode method.

This solves complete problem while I was having trying to scrap from a website using PyCharm

P.S -> I use python 3.4

Multiple ping script in Python

This script:

import subprocess
import os
with open(os.devnull, "wb") as limbo:
        for n in xrange(1, 10):
                ip="192.168.0.{0}".format(n)
                result=subprocess.Popen(["ping", "-c", "1", "-n", "-W", "2", ip],
                        stdout=limbo, stderr=limbo).wait()
                if result:
                        print ip, "inactive"
                else:
                        print ip, "active"

will produce something like this output:

192.168.0.1 active
192.168.0.2 active
192.168.0.3 inactive
192.168.0.4 inactive
192.168.0.5 inactive
192.168.0.6 inactive
192.168.0.7 active
192.168.0.8 inactive
192.168.0.9 inactive

You can capture the output if you replace limbo with subprocess.PIPE and use communicate() on the Popen object:

p=Popen( ... )
output=p.communicate()
result=p.wait()

This way you get the return value of the command and can capture the text. Following the manual this is the preferred way to operate a subprocess if you need flexibility:

The underlying process creation and management in this module is handled by the Popen class. It offers a lot of flexibility so that developers are able to handle the less common cases not covered by the convenience functions.

Getting the URL of the current page using Selenium WebDriver

Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium

Annotations from javax.validation.constraints not working

You need to add @Valid to each member variable, which was also an object that contained validation constraints.

Asynchronous Function Call in PHP

This old question has a new answer. There are a few "async" solutions for PHP this days (which are equivalent to Python's multiprocess in the sense that they spawn new independent PHP processes rather than manage it at the framework level)

The two solutions I have seen are

Give them a try!

Formatting Phone Numbers in PHP

Phone numbers are hard. For a more robust, international solution, I would recommend this well-maintained PHP port of Google's libphonenumber library.

Using it like this,

use libphonenumber\NumberParseException;
use libphonenumber\PhoneNumber;
use libphonenumber\PhoneNumberFormat;
use libphonenumber\PhoneNumberUtil;

$phoneUtil = PhoneNumberUtil::getInstance();

$numberString = "+12123456789";

try {
    $numberPrototype = $phoneUtil->parse($numberString, "US");

    echo "Input: " .          $numberString . "\n";
    echo "isValid: " .       ($phoneUtil->isValidNumber($numberPrototype) ? "true" : "false") . "\n";
    echo "E164: " .           $phoneUtil->format($numberPrototype, PhoneNumberFormat::E164) . "\n";
    echo "National: " .       $phoneUtil->format($numberPrototype, PhoneNumberFormat::NATIONAL) . "\n";
    echo "International: " .  $phoneUtil->format($numberPrototype, PhoneNumberFormat::INTERNATIONAL) . "\n";
} catch (NumberParseException $e) {
    // handle any errors
}

you will get the following output:

Input: +12123456789
isValid: true
E164: +12123456789
National: (212) 345-6789
International: +1 212-345-6789

I'd recommend using the E164 format for duplicate checks. You could also check whether the number is a actually mobile number or not (using PhoneNumberUtil::getNumberType()), or whether it's even a US number (using PhoneNumberUtil::getRegionCodeForNumber()).

As a bonus, the library can handle pretty much any input. If you, for instance, choose to run 1-800-JETBLUE through the code above, you will get

Input: 1-800-JETBLUE
isValid: true
E164: +18005382583
National: (800) 538-2583
International: +1 800-538-2583

Neato.

It works just as nicely for countries other than the US. Just use another ISO country code in the parse() argument.

Having links relative to root?

A root-relative URL starts with a / character, to look something like <a href="/directoryInRoot/fileName.html">link text</a>.

The link you posted: <a href="fruits/index.html">Back to Fruits List</a> is linking to an html file located in a directory named fruits, the directory being in the same directory as the html page in which this link appears.

To make it a root-relative URL, change it to:

<a href="/fruits/index.html">Back to Fruits List</a>

Edited in response to question, in comments, from OP:

So doing / will make it relative to www.example.com, is there a way to specify what the root is, e.g what if i want the root to be www.example.com/fruits in www.example.com/fruits/apples/apple.html?

Yes, prefacing the URL, in the href or src attributes, with a / will make the path relative to the root directory. For example, given the html page at www.example.com/fruits/apples.html, the a of href="/vegetables/carrots.html" will link to the page www.example.com/vegetables/carrots.html.

The base tag element allows you to specify the base-uri for that page (though the base tag would have to be added to every page in which it was necessary for to use a specific base, for this I'll simply cite the W3's example:

For example, given the following BASE declaration and A declaration:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
 <HEAD>
   <TITLE>Our Products</TITLE>
   <BASE href="http://www.aviary.com/products/intro.html">
 </HEAD>

 <BODY>
   <P>Have you seen our <A href="../cages/birds.gif">Bird Cages</A>?
 </BODY>
</HTML>

the relative URI "../cages/birds.gif" would resolve to:

http://www.aviary.com/cages/birds.gif

Example quoted from: http://www.w3.org/TR/html401/struct/links.html#h-12.4.

Suggested reading:

Why do I get PLS-00302: component must be declared when it exists?

I came here because I had the same problem.
What was the problem for me was that the procedure was defined in the package body, but not in the package header.
I was executing my function with a lose BEGIN END statement.

TypeError: 'dict' object is not callable

Access the dictionary with square brackets.

strikes = [number_map[int(x)] for x in input_str.split()]

How do I search a Perl array for a matching string?

If you will be doing many searches of the array, AND matching always is defined as string equivalence, then you can normalize your data and use a hash.

my @strings = qw( aAa Bbb cCC DDD eee );

my %string_lut;

# Init via slice:
@string_lut{ map uc, @strings } = ();

# or use a for loop:
#    for my $string ( @strings ) {
#        $string_lut{ uc($string) } = undef;
#    }


#Look for a string:

my $search = 'AAa';

print "'$string' ", 
    ( exists $string_lut{ uc $string ? "IS" : "is NOT" ),
    " in the array\n";

Let me emphasize that doing a hash lookup is good if you are planning on doing many lookups on the array. Also, it will only work if matching means that $foo eq $bar, or other requirements that can be met through normalization (like case insensitivity).

AWS ssh access 'Permission denied (publickey)' issue

use...

# chmod 400 ec2-keypair.pem

don't use the 600 permission otherwise you might overwrite your key accidently.

How to get the latest record in each group using GROUP BY?

Try this

SELECT * FROM messages where id in (SELECT max(id) FROM messages GROUP BY from_id ) order by id desc

UTF-8: General? Bin? Unicode?

Really, I tested saving values like 'é' and 'e' in column with unique index and they cause duplicate error on both 'utf8_unicode_ci' and 'utf8_general_ci'. You can save them only in 'utf8_bin' collated column.

And mysql docs (in http://dev.mysql.com/doc/refman/5.7/en/charset-applications.html) suggest into its examples set 'utf8_general_ci' collation.

[mysqld]
character-set-server=utf8
collation-server=utf8_general_ci

Using tr to replace newline with space

Best guess is you are on windows and your line ending settings are set for windows. See this topic: How to change line-ending settings

or use:

tr '\r\n' ' '

password for postgres

Set the default password in the .pgpass file. If the server does not save the password, it is because it is not set in the .pgpass file, or the permissions are open and the file is therefore ignored.

Read more about the password file here.

Also, be sure to check the permissions: on *nix systems the permissions on .pgpass must disallow any access to world or group; achieve this by the command chmod 0600 ~/.pgpass. If the permissions are less strict than this, the file will be ignored.

Have you tried logging-in using PGAdmin? You can save the password there, and modify the pgpass file.

Remove multiple objects with rm()

Make the list a character vector (not a vector of names)

rm(list = c('temp1','temp2'))

or

rm(temp1, temp2)

How to access accelerometer/gyroscope data from Javascript?

Can't add a comment to the excellent explanation in the other post but wanted to mention that a great documentation source can be found here.

It is enough to register an event function for accelerometer like so:

if(window.DeviceMotionEvent){
  window.addEventListener("devicemotion", motion, false);
}else{
  console.log("DeviceMotionEvent is not supported");
}

with the handler:

function motion(event){
  console.log("Accelerometer: "
    + event.accelerationIncludingGravity.x + ", "
    + event.accelerationIncludingGravity.y + ", "
    + event.accelerationIncludingGravity.z
  );
}

And for magnetometer a following event handler has to be registered:

if(window.DeviceOrientationEvent){
  window.addEventListener("deviceorientation", orientation, false);
}else{
  console.log("DeviceOrientationEvent is not supported");
}

with a handler:

function orientation(event){
  console.log("Magnetometer: "
    + event.alpha + ", "
    + event.beta + ", "
    + event.gamma
  );
}

There are also fields specified in the motion event for a gyroscope but that does not seem to be universally supported (e.g. it didn't work on a Samsung Galaxy Note).

There is a simple working code on GitHub

Spring Boot how to hide passwords in properties file

To the already proposed solutions I can add an option to configure an external Secrets Manager such as Vault.

  1. Configure Vault Server vault server -dev (Only for DEV and not for PROD)
  2. Write secrets vault write secret/somename key1=value1 key2=value2
  3. Verify secrets vault read secret/somename

Add the following dependency to your SpringBoot project:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-vault-config</artifactId>
</dependency>

Add Vault config properties:

spring.cloud.vault.host=localhost
spring.cloud.vault.port=8200
spring.cloud.vault.scheme=http
spring.cloud.vault.authentication=token
spring.cloud.vault.token=${VAULT_TOKEN}

Pass VAULT_TOKEN as an environment variable.

Refer to the documentation here.

There is a Spring Vault project which is also can be used for accessing, storing and revoking secrets.

Dependency:

<dependency>
    <groupId>org.springframework.vault</groupId>
    <artifactId>spring-vault-core</artifactId>
</dependency>

Configuring Vault Template:

@Configuration
class VaultConfiguration extends AbstractVaultConfiguration {

  @Override
  public VaultEndpoint vaultEndpoint() {
    return new VaultEndpoint();
  }

  @Override
  public ClientAuthentication clientAuthentication() {
    return new TokenAuthentication("…");
  }
}

Inject and use VaultTemplate:

public class Example {

  @Autowired
  private VaultOperations operations;

  public void writeSecrets(String userId, String password) {
      Map<String, String> data = new HashMap<String, String>();
      data.put("password", password);
      operations.write(userId, data);
  }

  public Person readSecrets(String userId) {
      VaultResponseSupport<Person> response = operations.read(userId, Person.class);
      return response.getBody();
  }
}

Use Vault PropertySource:

@VaultPropertySource(value = "aws/creds/s3",
  propertyNamePrefix = "aws."
  renewal = Renewal.RENEW)
public class Config {

}

Usage example:

public class S3Client {

  // inject the actual values
  @Value("${aws.access_key}")
  private String awsAccessKey;
  @Value("${aws.secret_key}")
  private String awsSecretKey;

  public InputStream getFileFromS3(String filenname) {
    // …
  }
}

"Not allowed to load local resource: file:///C:....jpg" Java EE Tomcat

This error means you can not directly load data from file system because there are security issues behind this. The only solution that I know is create a web service to serve load files.

Converting JSON data to Java object

If, by any change, you are in an application which already uses http://restfb.com/ then you can do:

import com.restfb.json.JsonObject;

...

JsonObject json = new JsonObject(jsonString);
json.get("title");

etc.

Installation error: INSTALL_FAILED_OLDER_SDK

Go in your project's build.cradle file and add

defaultConfig {
    minSdkVersion versions.minSdk

}`

This makes it that your application conforms to the minimum SDK your device is running.

Can I position an element fixed relative to parent?

Let me provide answers to both possible questions. Note that your existing title (and original post) ask a question different than what you seek in your edit and subsequent comment.


To position an element "fixed" relative to a parent element, you want position:absolute on the child element, and any position mode other than the default or static on your parent element.

For example:

#parentDiv { position:relative; }
#childDiv { position:absolute; left:50px; top:20px; }

This will position childDiv element 50 pixels left and 20 pixels down relative to parentDiv's position.


To position an element "fixed" relative to the window, you want position:fixed, and can use top:, left:, right:, and bottom: to position as you see fit.

For example:

#yourDiv { position:fixed; bottom:40px; right:40px; }

This will position yourDiv fixed relative to the web browser window, 40 pixels from the bottom edge and 40 pixels from the right edge.

How do I check if a directory exists? "is_dir", "file_exists" or both?

Both would return true on Unix systems - in Unix everything is a file, including directories. But to test if that name is taken, you should check both. There might be a regular file named 'foo', which would prevent you from creating a directory name 'foo'.

vue.js 'document.getElementById' shorthand

Try not to do DOM manipulation by referring the DOM directly, it will have lot of performance issue, also event handling becomes more tricky when we try to access DOM directly, instead use data and directives to manipulate the DOM.

This will give you more control over the manipulation, also you will be able to manage functionalities in the modular format.

Get contentEditable caret index position

If you set the editable div style to "display:inline-block; white-space: pre-wrap" you don't get new child divs when you enter a new line, you just get LF character (i.e. &#10);.

_x000D_
_x000D_
function showCursPos(){
    selection = document.getSelection();
    childOffset = selection.focusOffset;
    const range = document.createRange();
    eDiv = document.getElementById("eDiv");
    range.setStart(eDiv, 0);
    range.setEnd(selection.focusNode, childOffset);
    var sHtml = range.toString();
    p = sHtml.length; 
    sHtml=sHtml.replace(/(\r)/gm, "\\r");
    sHtml=sHtml.replace(/(\n)/gm, "\\n");
    document.getElementById("caretPosHtml").value=p;
    document.getElementById("exHtml").value=sHtml;   
  }
_x000D_
click/type in div below:
<br>
<div contenteditable name="eDiv" id="eDiv"  
     onkeyup="showCursPos()" onclick="showCursPos()" 
     style="width: 10em; border: 1px solid; display:inline-block; white-space: pre-wrap; "
     >123&#13;&#10;456&#10;789</div>
<p>
html caret position:<br> <input type="text" id="caretPosHtml">
<p>  
html from start of div:<br> <input type="text" id="exHtml">
_x000D_
_x000D_
_x000D_

What I noticed was when you press "enter" in the editable div, it creates a new node, so the focusOffset resets to zero. This is why I've had to add a range variable, and extend it from the child nodes' focusOffset back to the start of eDiv (and thus capturing all text in-between).

How to set the part of the text view is clickable

For bold,

mySpannable.setSpan(new StyleSpan(Typeface.BOLD),termStart,termStop,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

What difference is there between WebClient and HTTPWebRequest classes in .NET?

Also WebClient doesn't have timeout property. And that's the problem, because dafault value is 100 seconds and that's too much to indicate if there's no Internet connection.

Workaround for that problem is here https://stackoverflow.com/a/3052637/1303422

Integer division: How do you produce a double?

Cast one of the integers/both of the integer to float to force the operation to be done with floating point Math. Otherwise integer Math is always preferred. So:

1. double d = (double)5 / 20;
2. double v = (double)5 / (double) 20;
3. double v = 5 / (double) 20;

Note that casting the result won't do it. Because first division is done as per precedence rule.

double d = (double)(5 / 20); //produces 0.0

I do not think there is any problem with casting as such you are thinking about.

How to store command results in a shell variable?

The syntax to store the command output into a variable is var=$(command).

So you can directly do:

result=$(ls -l | grep -c "rahul.*patle")

And the variable $result will contain the number of matches.

How do I login and authenticate to Postgresql after a fresh install?

you can also connect to database as "normal" user (not postgres):

postgres=# \connect opensim Opensim_Tester localhost;

Password for user Opensim_Tester:    

You are now connected to database "opensim" as user "Opensim_Tester" on host "localhost" at port "5432"

How can I get a random number in Kotlin?

As of kotlin 1.2, you could write:

(1..3).shuffled().last()

Just be aware it's big O(n), but for a small list (especially of unique values) it's alright :D

reading a line from ifstream into a string variable

Use the std::getline() from <string>.

 istream & getline(istream & is,std::string& str)

So, for your case it would be:

std::getline(read,x);

A network-related or instance-specific error occurred while establishing a connection to SQL Server

Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.

  1. Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .

  2. if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .

  3. if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .

  4. after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).

  5. if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.

  6. If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.

  7. If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.

  8. If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property. enter image description here

    1. Restart your sql server instance after making any changes in property as some changes will require restart.

if you further face any difficulty then you need to provide more information about your web site and sql server .

Removing whitespace between HTML elements when using line breaks

The whitespace between the elements is only put there by the HTML editor for visual formatting purposes. You can use jQuery to remove the whitespace:

$("div#MyImages").each(function () {

    var div = $(this);
    var children= div.children();
    children.detach();
    div.empty();
    div.append(children);

});

This detaches the child elements, clears any whitespace that remains before adding the child elements back again.

Unlike the other answers to this question, using this method ensures that the inherited css display and font-size values are maintained. There's also no need to use float and the cumbersome clear that is then required. Of course, you will need to be using jQuery.

How to Alter a table for Identity Specification is identity SQL Server

You can't alter the existing columns for identity.

You have 2 options,

Create a new table with identity & drop the existing table

Create a new column with identity & drop the existing column

Approach 1. (New table) Here you can retain the existing data values on the newly created identity column.

CREATE TABLE dbo.Tmp_Names
    (
      Id int NOT NULL
             IDENTITY(1, 1),
      Name varchar(50) NULL
    )
ON  [PRIMARY]
go

SET IDENTITY_INSERT dbo.Tmp_Names ON
go

IF EXISTS ( SELECT  *
            FROM    dbo.Names ) 
    INSERT  INTO dbo.Tmp_Names ( Id, Name )
            SELECT  Id,
                    Name
            FROM    dbo.Names TABLOCKX
go

SET IDENTITY_INSERT dbo.Tmp_Names OFF
go

DROP TABLE dbo.Names
go

Exec sp_rename 'Tmp_Names', 'Names'

Approach 2 (New column) You can’t retain the existing data values on the newly created identity column, The identity column will hold the sequence of number.

Alter Table Names
Add Id_new Int Identity(1, 1)
Go

Alter Table Names Drop Column ID
Go

Exec sp_rename 'Names.Id_new', 'ID', 'Column'

See the following Microsoft SQL Server Forum post for more details:

http://social.msdn.microsoft.com/forums/en-US/transactsql/thread/04d69ee6-d4f5-4f8f-a115-d89f7bcbc032

Write in body request with HttpClient

If your xml is written by java.lang.String you can just using HttpClient in this way

    public void post() throws Exception{
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://www.baidu.com");
        String xml = "<xml>xxxx</xml>";
        HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        String result = EntityUtils.toString(response.getEntity());
    }

pay attention to the Exceptions.

BTW, the example is written by the httpclient version 4.x

How to pass data from child component to its parent in ReactJS?

You can create the state in the ParentComponent using useState and pass down the setIsParentData function as prop into the ChildComponent.

In the ChildComponent, update the data using the received function through prop to send the data back to ParentComponent.

I use this technique especially when my code in the ParentComponent is getting too long, therefore I will create child components from the ParentComponent. Typically, it will be only 1 level down and using useContext or redux seems overkill in order to share states between components.

ParentComponent.js

import React, { useState } from 'react';
import ChildComponent from './ChildComponent';

export function ParentComponent(){
  const [isParentData, setIsParentData] = useState(True);

  return (
    <p>is this a parent data?: {isParentData}</p>
    <ChildComponent toChild={isParentData} sendToParent={setIsParentData} />
  );
}

ChildComponent.js

import React from 'react';

export function ChildComponent(props){

  return (
    <button onClick={() => {props.sendToParent(False)}}>Update</button>
    <p>The state of isParentData is {props.toChild}</p>
  );
};

Uncaught SyntaxError: Unexpected token :

I did Wrong in this

   `var  fs = require('fs');
    var fs.writeFileSync(file, configJSON);`

Already I intialized the fs variable.But again i put var in the second line.This one also gives that kind of error...

Include CSS and Javascript in my django template

First, create staticfiles folder. Inside that folder create css, js, and img folder.

settings.py

import os

PROJECT_DIR = os.path.dirname(__file__)

DATABASES = {
    'default': {
         'ENGINE': 'django.db.backends.sqlite3', 
         'NAME': os.path.join(PROJECT_DIR, 'myweblabdev.sqlite'),                        
         'USER': '',
         'PASSWORD': '',
         'HOST': '',                      
         'PORT': '',                     
    }
}

MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')

MEDIA_URL = '/media/'

STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(PROJECT_DIR, 'staticfiles'),
)

main urls.py

from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from myweblab import settings

admin.autodiscover()

urlpatterns = patterns('',
    .......
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns += staticfiles_urlpatterns()

template

{% load static %}

<link rel="stylesheet" href="{% static 'css/style.css' %}">

Python: URLError: <urlopen error [Errno 10060]

This is because of the proxy settings. I also had the same problem, under which I could not use any of the modules which were fetching data from the internet. There are simple steps to follow:
1. open the control panel
2. open internet options
3. under connection tab open LAN settings
4. go to advance settings and unmark everything, delete every proxy in there. Or u can just unmark the checkbox in proxy server this will also do the same
5. save all the settings by clicking ok.
you are done. try to run the programme again, it must work it worked for me at least

Sleep/Wait command in Batch

timeout 5

to delay

timeout 5 >nul

to delay without asking you to press any key to cancel

SQL Server GROUP BY datetime ignore hour minute and a select with a date and sum value

SELECT CAST(Datetimefield AS DATE) as DateField, SUM(intfield) as SumField
FROM MyTable
GROUP BY CAST(Datetimefield AS DATE)

PDF Editing in PHP?

If you need really simple PDFs, then Zend or FPDF is fine. However I find them difficult and frustrating to work with. Also, because of the way the API works, there's no good way to separate content from presentation from business logic.

For that reason, I use dompdf, which automatically converts HTML and CSS to PDF documents. You can lay out a template just as you would for an HTML page and use standard HTML syntax. You can even include an external CSS file. The library isn't perfect and very complex markup or css sometimes gets mangled, but I haven't found anything else that works as well.

What are valid values for the id attribute in HTML?

In practice many sites use id attributes starting with numbers, even though this is technically not valid HTML.

The HTML 5 draft specification loosens up the rules for the id and name attributes: they are now just opaque strings which cannot contain spaces.

BSTR to std::string (std::wstring) and vice versa

There is a c++ class called _bstr_t. It has useful methods and a collection of overloaded operators.

For example, you can easily assign from a const wchar_t * or a const char * just doing _bstr_t bstr = L"My string"; Then you can convert it back doing const wchar_t * s = bstr.operator const wchar_t *();. You can even convert it back to a regular char const char * c = bstr.operator char *(); You can then just use the const wchar_t * or the const char * to initialize a new std::wstring oe std::string.

How to list files in an android directory?

I just discovered that:

new File("/sdcard/").listFiles() returns null if you do not have:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

set in your AndroidManifest.xml file.

Dots in URL causes 404 with ASP.NET mvc and IIS

It's as simple as changing path="." to path="". Just remove the dot in the path for ExensionlessUrlHandler-Integrated-4.0 in web.config.

Here's a nice article https://weblog.west-wind.com/posts/2015/Nov/13/Serving-URLs-with-File-Extensions-in-an-ASPNET-MVC-Application

How do you uninstall a python package that was installed using distutils?

If this is for testing and/or development purposes, setuptools has a develop command that updates every time you make a change (so you don't have to uninstall and reinstall every time you make a change). And you can uninstall the package using this command as well.

If you do use this, anything that you declare as a script will be left behind as a lingering file.

Undefined or null for AngularJS

lodash provides a shorthand method to check if undefined or null: _.isNil(yourVariable)

Getting Cannot read property 'offsetWidth' of undefined with bootstrap carousel script

I got same error. Because i used v4 alpha class names like carousel-control-next When i changed with v3, problem solved.

Alternative to header("Content-type: text/xml");

Now I see what you are doing. You cannot send output to the screen then change the headers. If you are trying to create an XML file of map marker and download them to display, they should be in separate files.

Take this

<?php
require("database.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','&lt;',$htmlStr);
$xmlStr=str_replace('>','&gt;',$xmlStr);
$xmlStr=str_replace('"','&quot;',$xmlStr);
$xmlStr=str_replace("'",'&#39;',$xmlStr);
$xmlStr=str_replace("&",'&amp;',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
  die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
  die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
  // ADD TO XML DOCUMENT NODE
  echo '<marker ';
  echo 'name="' . parseToXML($row['name']) . '" ';
  echo 'address="' . parseToXML($row['address']) . '" ';
  echo 'lat="' . $row['lat'] . '" ';
  echo 'lng="' . $row['lng'] . '" ';
  echo 'type="' . $row['type'] . '" ';
  echo '/>';
}
// End XML file
echo '</markers>';
?>

and place it in phpsqlajax_genxml.php so your javascript can download the XML file. You are trying to do too many things in the same file.

What is the most efficient way of finding all the factors of a number in Python?

Further improvement to afg & eryksun's solution. The following piece of code returns a sorted list of all the factors without changing run time asymptotic complexity:

    def factors(n):    
        l1, l2 = [], []
        for i in range(1, int(n ** 0.5) + 1):
            q,r = n//i, n%i     # Alter: divmod() fn can be used.
            if r == 0:
                l1.append(i) 
                l2.append(q)    # q's obtained are decreasing.
        if l1[-1] == l2[-1]:    # To avoid duplication of the possible factor sqrt(n)
            l1.pop()
        l2.reverse()
        return l1 + l2

Idea: Instead of using the list.sort() function to get a sorted list which gives nlog(n) complexity; It is much faster to use list.reverse() on l2 which takes O(n) complexity. (That's how python is made.) After l2.reverse(), l2 may be appended to l1 to get the sorted list of factors.

Notice, l1 contains i-s which are increasing. l2 contains q-s which are decreasing. Thats the reason behind using the above idea.

How can I lock the first row and first column of a table when scrolling, possibly using JavaScript and CSS?

There are quite a few cross browser solutions for this today, among which are SuperTable which I like due to its elegance and simplicity (now being continued with MooGrid) and SlickGrid with its awesome set of features.

CardView Corner Radius

You can use the standard MaterialCard included in the official Material Components library.

Use in your layout:

<com.google.android.material.card.MaterialCardView
        style="@style/MyCardView"
        ...>

In your style use the shapeAppearanceOverlay attribute to customize the shape (the default corner radius is 4dp)

  <style name="MyCardView" parent="@style/Widget.MaterialComponents.CardView">
    <item name="shapeAppearanceOverlay">@style/ShapeAppearanceOverlay.MaterialCardView.Cut</item>
  </style>


  <style name="ShapeAppearanceOverlay.MaterialCardView.Cut" parent="">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSizeTopRight">8dp</item>
    <item name="cornerSizeTopLeft">8dp</item>
    <item name="cornerSizeBottomRight">0dp</item>
    <item name="cornerSizeBottomLeft">0dp</item>
  </style>

You can also use:

<com.google.android.material.card.MaterialCardView
     app:shapeAppearanceOverlay="@style/ShapeAppearanceOverlay.MaterialCardView.Cut"
     ...>

It is the result:

enter image description here

Fatal error: Class 'ZipArchive' not found in

You need to check the PHP version

If php version is 5.6 then , You need to install php5.7-zip

sudo apt-get install php5.6-zip

and then

sudo service apache2 restart

Hope it helps

Rock, Paper, Scissors Game Java

int w =0 , l =0, d=0, i=0;
    Scanner sc = new Scanner(System.in);

// try tentimes
    while (i<10) {


        System.out.println("scissor(1) ,Rock(2),Paper(3) ");
        int n = sc.nextInt();
        int m =(int)(Math.random()*3+1);


        if(n==m){

            System.out.println("Com:"+m +"so>>> " + "draw");
            d++;


        }else if ((n-1)%3==(m%3)){
            w++;
            System.out.println("Com:"+m +"so>>> " +"win");
        }
        else if(n >=4 )
        {
            System.out.println("pleas enter correct number)");


    }
        else {
            System.out.println("Com:"+m +"so>>> " +"lose");
            l++;

        }
        i++;

No appenders could be found for logger(log4j)?

In java eclipse copy your conf_ref to conf folder.

How to change the color of progressbar in C# .NET 3.5?

Just in case anyone looks for another option.... you can extend a Panel, use it as background (white or whatever), add another Panel inside it for the foreground (the moving bar). Then you have total control changing the color, etc.

How to embed a .mov file in HTML?

Well, if you don't want to do the work yourself (object elements aren't really all that hard), you could always use Mike Alsup's Media plugin: http://jquery.malsup.com/media/

How do I convert two lists into a dictionary?

Try this:

>>> import itertools
>>> keys = ('name', 'age', 'food')
>>> values = ('Monty', 42, 'spam')
>>> adict = dict(itertools.izip(keys,values))
>>> adict
{'food': 'spam', 'age': 42, 'name': 'Monty'}

In Python 2, it's also more economical in memory consumption compared to zip.

How to add a browser tab icon (favicon) for a website?

The best one that I found is http://www.favicomatic.com/ I say best because it gave me the crispest favicon, and required no editing after their transformation. It will generate favicons at 16x16 and 32x32 and to quote them "Every damn size, sir!" Also, their site looks cool and is easy to use.

They also generate the html that you need to use for the files they generate.

<link rel="apple-touch-icon-precomposed" sizes="57x57" href="apple-touch-icon-57x57.png" />
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="apple-touch-icon-114x114.png" />
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="apple-touch-icon-72x72.png" />
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="apple-touch-icon-144x144.png" />
<link rel="apple-touch-icon-precomposed" sizes="60x60" href="apple-touch-icon-60x60.png" />
<link rel="apple-touch-icon-precomposed" sizes="120x120" href="apple-touch-icon-120x120.png" />
<link rel="apple-touch-icon-precomposed" sizes="76x76" href="apple-touch-icon-76x76.png" />
<link rel="apple-touch-icon-precomposed" sizes="152x152" href="apple-touch-icon-152x152.png" />
<link rel="icon" type="image/png" href="favicon-196x196.png" sizes="196x196" />
<link rel="icon" type="image/png" href="favicon-96x96.png" sizes="96x96" />
<link rel="icon" type="image/png" href="favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="favicon-16x16.png" sizes="16x16" />
<link rel="icon" type="image/png" href="favicon-128.png" sizes="128x128" />
<meta name="application-name" content="&nbsp;"/>
<meta name="msapplication-TileColor" content="#FFFFFF" />
<meta name="msapplication-TileImage" content="mstile-144x144.png" />
<meta name="msapplication-square70x70logo" content="mstile-70x70.png" />
<meta name="msapplication-square150x150logo" content="mstile-150x150.png" />
<meta name="msapplication-wide310x150logo" content="mstile-310x150.png" />
<meta name="msapplication-square310x310logo" content="mstile-310x310.png" />

I looked at the first 20 or so google results, and this was by far the best.

Notify ObservableCollection when Item changes

One simple solution to this is to replace the item being changed in the ObservableCollection which notifies the collection of the changed item. In the sample code snippet below Artists is the ObservableCollection and artist is an item of the type in the ObservableCollection:

    var index = Artists.IndexOf(artist);
    Artists.RemoveAt(index);
    artist.IsFollowed = true; // change something in the item
    Artists.Insert(index, artist);

How do I iterate through lines in an external file with shell?

This might work for you:

cat <<\! >names.txt
> alison
> barb
> charlie
> david
> !
OIFS=$IFS; IFS=$'\n'; NAMES=($(<names.txt)); IFS=$OIFS
echo "${NAMES[@]}"
alison barb charlie david
echo "${NAMES[0]}"
alison
for NAME in "${NAMES[@]}";do echo $NAME;done
alison
barb
charlie
david

Already defined in .obj - no double inclusions

This is not a compiler error: the error is coming from the linker. After compilation, the linker will merge the object files resulting from the compilation of each of your translation units (.cpp files).

The linker finds out that you have the same symbol defined multiple times in different translation units, and complains about it (it is a violation of the One Definition Rule).

The reason is most certainly that main.cpp includes client.cpp, and both these files are individually processed by the compiler to produce two separate object files. Therefore, all the symbols defined in the client.cpp translation unit will be defined also in the main.cpp translation unit. This is one of the reasons why you do not usually #include .cpp files.

Put the definition of your class in a separate client.hpp file which does not contain also the definitions of the member functions of that class; then, let client.cpp and main.cpp include that file (I mean #include). Finally, leave in client.cpp the definitions of your class's member functions.

client.h

#ifndef SOCKET_CLIENT_CLASS
#define SOCKET_CLIENT_CLASS
#ifndef BOOST_ASIO_HPP
#include <boost/asio.hpp>
#endif

class SocketClient // Or whatever the name is...
{

// ...

    bool read(int, char*); // Or whatever the name is...

//  ...
};

#endif

client.cpp

#include "Client.h"

// ...

bool SocketClient::read(int, char*)
{
    // Implementation  goes here...
}

// ... (add the definitions for all other member functions)

main.h

#include <iostream>
#include <string>
#include <sstream>
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>
#include "client.h"
//              ^^ Notice this!

main.cpp

#include "main.h"

Manually adding a Userscript to Google Chrome

The best thing to do is to install the Tampermonkey extension.

This will allow you to easily install Greasemonkey scripts, and to easily manage them. Also it makes it easier to install userscripts directly from sites like OpenUserJS, MonkeyGuts, etc.

Finally, it unlocks most all of the GM functionality that you don't get by installing a GM script directly with Chrome. That is, more of what GM on Firefox can do, is available with Tampermonkey.


But, if you really want to install a GM script directly, it's easy a right pain on Chrome these days...

Chrome After about August, 2014:

You can still drag a file to the extensions page and it will work... Until you restart Chrome. Then it will be permanently disabled. See Continuing to "protect" Chrome users from malicious extensions for more information. Again, Tampermonkey is the smart way to go. (Or switch browsers altogether to Opera or Firefox.)

Chrome 21+ :

Chrome is changing the way extensions are installed. Userscripts are pared-down extensions on Chrome but. Starting in Chrome 21, link-click behavior is disabled for userscripts. To install a user script, drag the **.user.js* file into the Extensions page (chrome://extensions in the address input).

Older Chrome versions:

Merely drag your **.user.js* files into any Chrome window. Or click on any Greasemonkey script-link.

You'll get an installation warning:
Initial warning

Click Continue.


You'll get a confirmation dialog:
confirmation dialog

Click Add.


Notes:

  1. Scripts installed this way have limitations compared to a Greasemonkey (Firefox) script or a Tampermonkey script. See Cross-browser user-scripting, Chrome section.

Controlling the Script and name:

By default, Chrome installs scripts in the Extensions folder1, full of cryptic names and version numbers. And, if you try to manually add a script under this folder tree, it will be wiped the next time Chrome restarts.

To control the directories and filenames to something more meaningful, you can:

  1. Create a directory that's convenient to you, and not where Chrome normally looks for extensions. For example, Create: C:\MyChromeScripts\.

  2. For each script create its own subdirectory. For example, HelloWorld.

  3. In that subdirectory, create or copy the script file. For example, Save this question's code as: HelloWorld.user.js.

  4. You must also create a manifest file in that subdirectory, it must be named: manifest.json.

    For our example, it should contain:

    {
        "manifest_version": 2,
        "content_scripts": [ {
            "exclude_globs":    [  ],
            "include_globs":    [ "*" ],
            "js":               [ "HelloWorld.user.js" ],
            "matches":          [   "https://stackoverflow.com/*",
                                    "https://stackoverflow.com/*"
                                ],
            "run_at": "document_end"
        } ],
        "converted_from_user_script": true,
        "description":  "My first sensibly named script!",
        "name":         "Hello World",
        "version":      "1"
    }
    

    The manifest.json file is automatically generated from the meta-block by Chrome, when an user script is installed. The values of @include and @exclude meta-rules are stored in include_globs and exclude_globs, @match (recommended) is stored in the matches list. "converted_from_user_script": true is required if you want to use any of the supported GM_* methods.

  5. Now, in Chrome's Extension manager (URL = chrome://extensions/), Expand "Developer mode".

  6. Click the Load unpacked extension... button.

  7. For the folder, paste in the folder for your script, In this example it is: C:\MyChromeScripts\HelloWorld.

  8. Your script is now installed, and operational!

  9. If you make any changes to the script source, hit the Reload link for them to take effect:

    Reload link




1 The folder defaults to:

Windows XP:
  Chrome  : %AppData%\..\Local Settings\Application Data\Google\Chrome\User Data\Default\Extensions\
  Chromium: %AppData%\..\Local Settings\Application Data\Chromium\User Data\Default\Extensions\

Windows Vista/7/8:
  Chrome  : %LocalAppData%\Google\Chrome\User Data\Default\Extensions\
  Chromium: %LocalAppData%\Chromium\User Data\Default\Extensions\

Linux:
  Chrome  : ~/.config/google-chrome/Default/Extensions/
  Chromium: ~/.config/chromium/Default/Extensions/

Mac OS X:
  Chrome  : ~/Library/Application Support/Google/Chrome/Default/Extensions/
  Chromium: ~/Library/Application Support/Chromium/Default/Extensions/

Although you can change it by running Chrome with the --user-data-dir= option.

Map over object preserving keys

_.map returns an Array, not an Object.

If you want an object you're better off using a different function, like each; if you really want to use map you could do something like this:

Object.keys(object).map(function(value, index) {
   object[value] *= 3;
})

but that is confusing, when seeing map one would expect to have an array as result and then make something with it.

What is the best way to iterate over a dictionary?

If say, you want to iterate over the values collection by default, I believe you can implement IEnumerable<>, Where T is the type of the values object in the dictionary, and "this" is a Dictionary.

public new IEnumerator<T> GetEnumerator()
{
   return this.Values.GetEnumerator();
}

How do I unload (reload) a Python module?

For Python 2 use built-in function reload():

reload(module)

For Python 2 and 3.2–3.3 use reload from module imp:

import imp
imp.reload(module)

But imp is deprecated since version 3.4 in favor of importlib, so use:

import importlib
importlib.reload(module)

or

from importlib import reload
reload(module)

Reordering Chart Data Series

FYI, if you are using two y-axis, the order numbers will only make a difference within the set of series of that y-axis. I believe secondary -y-axis by default are on top of the primary. If you want the series in the primary axis to be on top, you'll need to make it secondary instead.

How can I find the first occurrence of a sub-string in a python string?

def find_pos(chaine,x):

    for i in range(len(chaine)):
        if chaine[i] ==x :
            return 'yes',i 
    return 'no'

Convert JsonObject to String

Add a double quotes outside the brackets and replace double quotes inside the {} with \"

So: "{\"data\":{..... }"

What does set -e mean in a bash script?

I believe the intention is for the script in question to fail fast.

To test this yourself, simply type set -e at a bash prompt. Now, try running ls. You'll get a directory listing. Now, type lsd. That command is not recognized and will return an error code, and so your bash prompt will close (due to set -e).

Now, to understand this in the context of a 'script', use this simple script:

#!/bin/bash 
# set -e

lsd 

ls

If you run it as is, you'll get the directory listing from the ls on the last line. If you uncomment the set -e and run again, you won't see the directory listing as bash stops processing once it encounters the error from lsd.

How to set text size in a button in html

Try this, its working in FF

body,
input,
select,
button {
 font-family: Arial,Helvetica,sans-serif;
 font-size: 14px;
}

'Linker command failed with exit code 1' when using Google Analytics via CocoaPods

Close Xcode, rename the folder. Then make a new folder with the previous name. Run the project, stop the project. Delete the new folder, rename old folder and re-run.

My iPad Pro simulator is affected with this issue. Its something that makes me upset, so much hard work... hopefully Google works through bugs for the next SDK.

Difference between Pragma and Cache-Control headers?

There is no difference, except that Pragma is only defined as applicable to the requests by the client, whereas Cache-Control may be used by both the requests of the clients and the replies of the servers.

So, as far as standards go, they can only be compared from the perspective of the client making a requests and the server receiving a request from the client. The http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32 defines the scenario as follows:

HTTP/1.1 caches SHOULD treat "Pragma: no-cache" as if the client had sent "Cache-Control: no-cache". No new Pragma directives will be defined in HTTP.

  Note: because the meaning of "Pragma: no-cache as a response
  header field is not actually specified, it does not provide a
  reliable replacement for "Cache-Control: no-cache" in a response

The way I would read the above:

  • if you're writing a client and need no-cache:

    • just use Pragma: no-cache in your requests, since you may not know if Cache-Control is supported by the server;
    • but in replies, to decide on whether to cache, check for Cache-Control
  • if you're writing a server:

    • in parsing requests from the clients, check for Cache-Control; if not found, check for Pragma: no-cache, and execute the Cache-Control: no-cache logic;
    • in replies, provide Cache-Control.

Of course, reality might be different from what's written or implied in the RFC!

Localhost not working in chrome and firefox

In case the browser LAN proxy setting solution doesn't work for you:

As mentioned in this similar Q&A How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

Simply changing the port number of your web project can be a quick fix.

enter image description here

Converting integer to string in Python

If you need unary numeral system, you can convert an integer like this:

>> n = 6
>> '1' * n
'111111'

If you need a support of negative ints you can just write like that:

>> n = -6
>> '1' * n if n >= 0 else '-' + '1' * (-n)
'-111111'

Zero is special case which takes an empty string in this case, which is correct.

>> n = 0
>> '1' * n if n >= 0 else '-' + '1' * (-n)
''

Application Loader stuck at "Authenticating with the iTunes store" when uploading an iOS app

Dec 10th 2019, Xcode Version 11.2.1, MacOS X 10.15.1

I was facing exactly same issue yesterday and I thought it might be network issues, at least it looks like so. But this morning I had tried couple different networks and several VPN connections, none of them is working!

The highest voted answer here asks me to reset a cache folder named .itmstransporter under my home dir, the run a program iTMSTransporter under a specific folder, but I can't find both of them.

But soon I figured that it is the cache folder for the people who uses the legacy uploader program: Application Loader, which is deprecated by Apple and can be no longer found in Xcode 11. Then I found that the latest Xcode has located iTMSTransporter here:

/Applications/Xcode.app/Contents/SharedFrameworks/ContentDeliveryServices.framework/itms/bin/iTMSTransporter

And its cache folder is here:

/Users/your_user_name/Library/Caches/com.apple.amp.itmstransporter/

I removed my existed cache folder, and run iTMSTransporter without any parameter, it soon started to output logs and download a bunch of files, and finished in 2 or 3 minutes. Then I tried again to upload my ipa file, it works!!!

CONCLUTION:

  1. Either the old Application Loader, or the latest Xcode, uses a Java program iTMSTransporter to process the ipa file uploading.
  2. To function correctly, iTMSTransporter requires a set of jar files downloaded from Internet and cached in your local folder.
  3. If your cache is somehow broken, or doesn't exist at all, directly invoking iTMSTransporter with functional parameters such as --upload-app in our case, iTMSTransporter DOES NOT WARN YOU, NOR FIX CACHE BY ITSELF, it just gets stuck there, SAYS NOTHING AT ALL! (Whoever wrote this iTMSTransporter, you seriously need to improve your programming sense).
  4. Invoking iTMSTransporter without any parameter fixes the cache.
  5. A functional cache is about 65MB, at Dec 10th 2019 with Xcode Version 11.2.1 (11B500)

Is there a way to get version from package.json in nodejs code?

Using ES6 modules you can do the following:

import {version} from './package.json';

Do we need to execute Commit statement after Update in SQL Server

The SQL Server Management Studio has implicit commit turned on, so all statements that are executed are implicitly commited.

This might be a scary thing if you come from an Oracle background where the default is to not have commands commited automatically, but it's not that much of a problem.

If you still want to use ad-hoc transactions, you can always execute

BEGIN TRANSACTION

within SSMS, and than the system waits for you to commit the data.

If you want to replicate the Oracle behaviour, and start an implicit transaction, whenever some DML/DDL is issued, you can set the SET IMPLICIT_TRANSACTIONS checkbox in

Tools -> Options -> Query Execution -> SQL Server -> ANSI

Push item to associative array in PHP

This is a cool function

function array_push_assoc($array, $key, $value){
   $array[$key] = $value;
   return $array;
}

Just use

$myarray = array_push_assoc($myarray, 'h', 'hello');

Credits & Explanation

Copy Paste Values only( xlPasteValues )

since you only want values copied, you can pass the values of arr1 directly to arr2 and avoid copy/paste. code inside the loop:

      Sheets("SheetB").Range(arr2(i) & firstrowDB).Resize(lastrow, 1).Value = .Range(.Cells(1, arr1(i)), .Cells(lastrow, arr1(i))).Value

Explicitly select items from a list or tuple

Maybe a list comprehension is in order:

L = ['a', 'b', 'c', 'd', 'e', 'f']
print [ L[index] for index in [1,3,5] ]

Produces:

['b', 'd', 'f']

Is that what you are looking for?

Jenkins "Console Output" log location in filesystem

Easy solution would be:

curl  http://jenkinsUrl/job/<Build_Name>/<Build_Number>/consoleText -OutFile <FilePathToLocalDisk>

or for the last successful build...

curl  http://jenkinsUrl/job/<Build_Name>/lastSuccessfulBuild/consoleText -OutFile <FilePathToLocalDisk>

working with negative numbers in python

import time

print ('Two Digit Multiplication Calculator')
print ('===================================')
print ()
print ('Give me two numbers.')

x = int ( input (':'))

y = int ( input (':'))

z = 0

print ()


while x > 0:
    print (':',z)
    x = x - 1
    z = y + z
    time.sleep (.2)
    if x == 0:
        print ('Final answer: ',z)

while x < 0:
    print (':',-(z))
    x = x + 1
    z = y + z
    time.sleep (.2)
    if x == 0:
        print ('Final answer: ',-(z))

print ()  

selecting unique values from a column

Use the DISTINCT operator in MySQL:

SELECT DISTINCT(Date) AS Date FROM buy ORDER BY Date DESC;

Best way to do a split pane in HTML

I found a working splitter, http://www.dreamchain.com/split-pane/, which works with jQuery v1.9. Note I had to add the following CSS code to get it working with a fixed bootstrap navigation bar.

fixed-left {
    position: absolute !important; /* to override relative */
    height: auto !important;
    top: 55px; /* Fixed navbar height */
    bottom: 0px;
}

Excel SUMIF between dates

One more solution when you want to use data from any sell ( in the key C3)

=SUMIF(Sheet6!M:M;CONCATENATE("<";TEXT(C3;"dd.mm.yyyy"));Sheet6!L:L)

Wrapping a react-router Link in an html button

You can use useHistory hook since react-router v5.1.0.

The useHistory hook gives you access to the history instance that you may use to navigate.

import React from 'react'
import { useHistory } from 'react-router-dom'

export default function SomeComponent() {
  const { push } = useHistory()
  ...
  <button
    type="button"
    onClick={() => push('/some-link')}
  >
    Some link
  </button>
  ...
}

Python: Figure out local timezone

Avoiding non-standard module (seems to be a missing method of datetime module):

from datetime import datetime
utcOffset_min = int(round((datetime.now() - datetime.utcnow()).total_seconds())) / 60   # round for taking time twice
utcOffset_h = utcOffset_min / 60
assert(utcOffset_min == utcOffset_h * 60)   # we do not handle 1/2 h timezone offsets

print 'Local time offset is %i h to UTC.' % (utcOffset_h)

How to iterate through XML in Powershell?

PowerShell has built-in XML and XPath functions. You can use the Select-Xml cmdlet with an XPath query to select nodes from XML object and then .Node.'#text' to access node value.

[xml]$xml = Get-Content $serviceStatePath
$nodes = Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml
$nodes | ForEach-Object {$_.Node.'#text'}

Or shorter

[xml]$xml = Get-Content $serviceStatePath
Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml |
  % {$_.Node.'#text'}

TypeError: document.getElementbyId is not a function

Case sensitive: document.getElementById (notice the capital B).

How to read until end of file (EOF) using BufferedReader in Java?

With text files, maybe the EOF is -1 when using BufferReader.read(), char by char. I made a test with BufferReader.readLine()!=null and it worked properly.

Using Server.MapPath in external C# Classes in ASP.NET

Whether you're running within the context of ASP.NET or not, you should be able to use HostingEnvironment.ApplicationPhysicalPath

Sort arrays of primitive types in descending order

There's been some confusion about Arrays.asList in the other answers. If you say

double[] arr = new double[]{6.0, 5.0, 11.0, 7.0};
List xs = Arrays.asList(arr);
System.out.println(xs.size());  // prints 1

then you'll have a List with 1 element. The resulting List has the double[] array as its own element. What you want is to have a List<Double> whose elements are the elements of the double[].

Unfortunately, no solution involving Comparators will work for a primitive array. Arrays.sort only accepts a Comparator when being passed an Object[]. And for the reasons describe above, Arrays.asList won't let you make a List out of the elements of your array.

So despite my earlier answer which the comments below reference, there's no better way than manually reversing the array after sorting. Any other approach (such as copying the elements into a Double[] and reverse-sorting and copying them back) would be more code and slower.

How to delete and update a record in Hive

Recently I was looking to resolve a similar issue, Apache Hive, Hadoop do not support Update/Delete operations. So ? So you have two ways:

  1. Use a backup table: Save the whole table in a backup_table, then truncate your input table, then re-write only the data you are intrested to mantain.
  2. Use Uber Hudi: It's a framework created by Uber to resolve the HDFS limitations including Deletion and Update. You can give a look in this link: https://eng.uber.com/hoodie/

an example for point 1:

Create table bck_table like input_table;
Insert overwrite table bck_table 
    select * from input_table;
Truncate table input_table;
Insert overwrite table input_table
    select * from bck_table where id <> 1;

NB: If the input_table is an external table you must follow the following link: How to truncate a partitioned external table in hive?

Javascript get object key name

ECMAscript edition 5 also offers you the neat methods Object.keys() and Object.getOwnPropertyNames().

So

Object.keys( buttons );  // ['button1', 'button2'];

Is it better in C++ to pass by value or pass by constant reference?

As it has been pointed out, it depends on the type. For built-in data types, it is best to pass by value. Even some very small structures, such as a pair of ints can perform better by passing by value.

Here is an example, assume you have an integer value and you want pass it to another routine. If that value has been optimized to be stored in a register, then if you want to pass it be reference, it first must be stored in memory and then a pointer to that memory placed on the stack to perform the call. If it was being passed by value, all that is required is the register pushed onto the stack. (The details are a bit more complicated than that given different calling systems and CPUs).

If you are doing template programming, you are usually forced to always pass by const ref since you don't know the types being passed in. Passing penalties for passing something bad by value are much worse than the penalties of passing a built-in type by const ref.

Regular Expression for password validation

Thanks Nicholas Carey. I was going to use regex first but what you wrote changed my mind. It is so much easier to maintain this way.

//You can set these from your custom service methods
int minLen = 8;
int minDigit 2;
int minSpChar 2;

Boolean ErrorFlag = false;
//Check for password length
if (model.NewPassword.Length < minLen)
{
    ErrorFlag = true;
    ModelState.AddModelError("NewPassword", "Password must be at least " + minLen + " characters long.");
}

//Check for Digits and Special Characters
int digitCount = 0;
int splCharCount = 0;
foreach (char c in model.NewPassword)
{
    if (char.IsDigit(c)) digitCount++;
    if (Regex.IsMatch(c.ToString(), @"[!#$%&'()*+,-.:;<=>?@[\\\]{}^_`|~]")) splCharCount++;
}

if (digitCount < minDigit)
{
    ErrorFlag = true;
    ModelState.AddModelError("NewPassword", "Password must have at least " + minDigit + " digit(s).");
}
if (splCharCount < minSpChar)
{
    ErrorFlag = true;
    ModelState.AddModelError("NewPassword", "Password must have at least " + minSpChar + " special character(s).");
}

if (ErrorFlag)
    return View(model);

How to reduce the image size without losing quality in PHP

If you are looking to reduce the size using coding itself, you can follow this code in php.

<?php 
function compress($source, $destination, $quality) {

    $info = getimagesize($source);

    if ($info['mime'] == 'image/jpeg') 
        $image = imagecreatefromjpeg($source);

    elseif ($info['mime'] == 'image/gif') 
        $image = imagecreatefromgif($source);

    elseif ($info['mime'] == 'image/png') 
        $image = imagecreatefrompng($source);

    imagejpeg($image, $destination, $quality);

    return $destination;
}

$source_img = 'source.jpg';
$destination_img = 'destination .jpg';

$d = compress($source_img, $destination_img, 90);
?>

$d = compress($source_img, $destination_img, 90);

This is just a php function that passes the source image ( i.e., $source_img ), destination image ( $destination_img ) and quality for the image that will take to compress ( i.e., 90 ).

$info = getimagesize($source);

The getimagesize() function is used to find the size of any given image file and return the dimensions along with the file type.

eloquent laravel: How to get a row count from a ->get()

Its better to access the count with the laravels count method

$count = Model::where('status','=','1')->count();

or

$count = Model::count();

Find number of decimal places in decimal value regardless of culture

And here's another way, use the type SqlDecimal which has a scale property with the count of the digits right of the decimal. Cast your decimal value to SqlDecimal and then access Scale.

((SqlDecimal)(decimal)yourValue).Scale

How can I get zoom functionality for images?

You could also try out http://code.google.com/p/android-multitouch-controller/

The library is really great, although initially a little hard to grasp.

How to get the top position of an element?

Try: $('#mytable').attr('offsetTop')

Visual Studio keyboard shortcut to display IntelliSense

Ctrl + Space

or

Ctrl + J

You can also go to menu Tools ? Options ? Environment ? Keyboard and check what is assigned to these shortcuts. The command name should be Edit.CompleteWord.

Angular2, what is the correct way to disable an anchor element?

My answer might be late for this post. It can be achieved through inline css within anchor tag only.

<a [routerLink]="['/user']" [style.pointer-events]="isDisabled ?'none':'auto'">click-label</a>

Considering isDisabled is a property in component which can be true or false.

Plunker for it: https://embed.plnkr.co/TOh8LM/

CSS:Defining Styles for input elements inside a div

CSS 3

divContainer input[type="text"] {
    width:150px;
}

CSS2 add a class "text" to the text inputs then in your css

.divContainer.text{
    width:150px;
}

How do CORS and Access-Control-Allow-Headers work?

Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000 or Access-Control-Allow-Origin: * on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true on the POST response as well.

Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept to match the requested header.

In Java, how to find if first character in a string is upper case without regex

Actually, this is subtler than it looks.

The code above would give the incorrect answer for a lower case character whose code point was above U+FFFF (such as U+1D4C3, MATHEMATICAL SCRIPT SMALL N). String.charAt would return a UTF-16 surrogate pair, which is not a character, but rather half the character, so to speak. So you have to use String.codePointAt, which returns an int above 0xFFFF (not a char). You would do:

Character.isUpperCase(s.codePointAt(0));

Don't feel bad overlooked this; almost all Java coders handle UTF-16 badly, because the terminology misleadingly makes you think that each "char" value represents a character. UTF-16 sucks, because it is almost fixed width but not quite. So non-fixed-width edge cases tend not to get tested. Until one day, some document comes in which contains a character like U+1D4C3, and your entire system blows up.

PHP and MySQL Select a Single Value

It is quite evident that there is only a single id corresponding to a single username because username is unique.

But the actual problem lies in the query itself-

$sql = "SELECT 'id' FROM Users WHERE username='$name'";

O/P

+----+
| id |
+----+
| id |
+----+

i.e. 'id' actually is treated as a string not as the id attribute.

Correct synatx:

$sql = "SELECT `id` FROM Users WHERE username='$name'";

i.e. use grave accent(`) instead of single quote(').

or

$sql = "SELECT id FROM Users WHERE username='$name'";

Complete code

session_start();
$name = $_GET["username"];
$sql = "SELECT `id` FROM Users WHERE username='$name'";
$result = mysql_query($sql);
$row=mysql_fetch_array($result)
$value = $row[0];
$_SESSION['myid'] = $value;

Image scaling causes poor quality in firefox/internet explorer but not chrome

Your problem is that you are relying on the browser to resize your images. Browsers have notoriously poor image scaling algorithms, which will cause the ugly pixelization.

You should resize your images in a graphics program first before you use them on the webpage.

Also, you have a spelling mistake: it should say moz-crisp-edges; however, that won't help you in your case (because that resizing algorithm won't give you a high quality resize: https://developer.mozilla.org/En/CSS/Image-rendering)

What is Robocopy's "restartable" option?

Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.

That option could be useful when copying very large files over a potentially unstable connection.

Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.

Error related to only_full_group_by when executing a query in MySql

I will try to explain you what this error is about.
Starting from MySQL 5.7.5, option ONLY_FULL_GROUP_BY is enabled by default.
Thus, according to standart SQL92 and earlier:

does not permit queries for which the select list, HAVING condition, or ORDER BY list refer to nonaggregated columns that are neither named in the GROUP BY clause nor are functionally dependent on (uniquely determined by) GROUP BY columns

(read more in docs)

So, for example:

SELECT * FROM `users` GROUP BY `name`;

You will get error message after executing query above.

#1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'testsite.user.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

Why?
Because MySQL dont exactly understand, what certain values from grouped records to retrieve, and this is the point.

I.E. lets say you have this records in your users table:
Yo

And you will execute invalid query showen above.
And you will get error shown above, because, there is 3 records with name John, and it is nice, but, all of them have different email field values.
So, MySQL simply don't understand which of them to return in resulting grouped record.

You can fix this issue, by simply changing your query like this:

SELECT `name` FROM `users` GROUP BY `name`

Also, you may want to add more fields to SELECT section, but you cant do that, if they are not aggregated, but there is crutch you could use (but highly not reccomended):

SELECT ANY_VALUE(`id`), ANY_VALUE(`email`), `name` FROM `users` GROUP BY `name`

enter image description here

Now, you may ask, why using ANY_VALUE is highly not recommended?
Because MySQL don't exactly know what value of grouped records to retrieve, and by using this function, you asking it to fetch any of them (in this case, email of first record with name = John was fetched).
Exactly I cant come up with any ideas on why you would want this behaviour to exist.

Please, if you dont understand me, read more about how grouping in MySQL works, it is very simple.

And by the end, here is one more simple, yet valid query.
If you want to query total users count according to available ages, you may want to write down this query

SELECT `age`, COUNT(`age`) FROM `users` GROUP BY `age`;

Which is fully valid, according to MySQL rules.
And so on.

It is important to understand what exactly the problem is and only then write down the solution.

video as site background? HTML 5

First, your HTML markup looks like this:

<video id="awesome_video" src="first_video.mp4" autoplay />

Second, your JavaScript code will look like this:

<script type="text/javascript">
  var index = 1,
      playlist = ['first_video.mp4', 'second_video.mp4', 'third_video.mp4'],
      video = document.getElementById('awesome_video');

  video.addEventListener('ended', rotate_video, false);

  function rotate_video() {
    video.setAttribute('src', playlist[index]);
    video.load();
    index++;
    if (index >= playlist.length) { index = 0; }
  }
</script>

And last but not least, your CSS:

#awesome_video { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }

This will create a video element on your page that starts playing the first video right away, then iterates through the playlist defined by the JavaScript variable. Your mileage with the CSS may vary depending on the CSS for the rest of the site, but 100% width/height should do it on a basic page.

Why I am getting Cannot pass parameter 2 by reference error when I am using bindParam with a constant value?

Based on the other answers but with a little more clarity on how to actually use this solution.

If for example you have an empty string for a time value but you want to save it as a null:

  if($endtime == ""){
    $db->bind(":endtime",$endtime=NULL,PDO::PARAM_STR);
  }else{
    $db->bind("endtime",$endtime);
  }

Notice that for time values you would use PARAM_STR, as times are stored as strings.

Clearing Magento Log Data

After clean the logs using any of the methods described above you can also disable them in your app/etc/local.xml

...
<frontend>
<events>
 <frontend>
  <events>
    <!-- disable Mage_Log -->
    <controller_action_predispatch>
        <observers><log><type>disabled</type></log></observers>
    </controller_action_predispatch>
    <controller_action_postdispatch>
        <observers><log><type>disabled</type></log></observers>
    </controller_action_postdispatch>
    <customer_login>
      <observers>
        <log>
          <type>disabled</type>
        </log>
      </observers>
    </customer_login>
    <customer_logout>
      <observers>
        <log>
          <type>disabled</type>
        </log>
      </observers>
    </customer_logout>
    <sales_quote_save_after>
       <observers>
          <log>
              <type>disabled</type>
          </log>
        </observers>
   </sales_quote_save_after>
   <checkout_quote_destroy>
     <observers>
       <log>
         <type>disabled</type>
       </log>
     </observers>
   </checkout_quote_destroy>
</events>
</frontend>
</config>

What is the proper #include for the function 'sleep()'?

sleep is a non-standard function.

  • On UNIX, you shall include <unistd.h>.
  • On MS-Windows, Sleep is rather from <windows.h>.

In every case, check the documentation.

How do I add multiple conditions to "ng-disabled"?

Wanny is correct. The && operator doesn't work in HTML. With Angular, you must use the double pipes (||)for multiple conditions.

Trying to use Spring Boot REST to Read JSON String from POST

To receive arbitrary Json in Spring-Boot, you can simply use Jackson's JsonNode. The appropriate converter is automatically configured.

    @PostMapping(value="/process")
    public void process(@RequestBody com.fasterxml.jackson.databind.JsonNode payload) {
        System.out.println(payload);
    }

Java null check why use == instead of .equals()

Because equal is a function derived from Object class, this function compares items of the class. if you use it with null it will return false cause cause class content is not null. In addition == compares reference to an object.

When is layoutSubviews called?

calling [self.view setNeedsLayout]; in viewController makes it to call viewDidLayoutSubviews

How to get the PID of a process by giving the process name in Mac OS X ?

You can use the pgrep command like in the following example

$ pgrep Keychain\ Access
44186

How to build & install GLFW 3 and use it in a Linux project

this solved it to me:

sudo apt-get update
sudo apt-get install libglfw3
sudo apt-get install libglfw3-dev

taken from https://github.com/glfw/glfw/issues/808

Printing PDFs from Windows Command Line

Here is another solution:

1) Download SumatraPDF (portable version) - https://www.sumatrapdfreader.org/download-free-pdf-viewer.html

2) Create a class library project and unzip the SumatraPDF.exe to the project directory root and unblock it.

3) Inside the project Properties, go to the Resoruces tab and add the exe as a file.

4) Add the following class to your library:

public class SumatraWrapper : IDisposable
{
    private readonly FileInfo _tempFileForExe = null;
    private readonly FileInfo _exe = null;

    public SumatraWrapper()
    {
        _exe = ExtractExe();
    }

    public SumatraWrapper(FileInfo tempFileForExe)
        : this()
    {
        _tempFileForExe = tempFileForExe ?? throw new ArgumentNullException(nameof(tempFileForExe));
    }

    private FileInfo ExtractExe()
    {
        string tempfile = 
            _tempFileForExe != null ? 
            _tempFileForExe.FullName : 
            Path.GetTempFileName() + ".exe";

        FileInfo exe = new FileInfo(tempfile);
        byte[] bytes = Properties.Resources.SumatraPDF;

        using (FileStream fs = exe.OpenWrite())
        {
            fs.Write(bytes, 0, bytes.Length);
        }

        return exe;
    }

    public bool Print(FileInfo file, string printerName)
    {
        string arguments = $"-print-to \"{printerName}\" \"{file.FullName}\"";
        ProcessStartInfo processStartInfo = new ProcessStartInfo(_exe.FullName, arguments)
        {
            CreateNoWindow = true
        };
        using (Process process = Process.Start(processStartInfo))
        {
            process.WaitForExit();
            return process.ExitCode == 0;
        }
    }

    #region IDisposable Support
    private bool disposedValue = false; // To detect redundant calls

    protected virtual void Dispose(bool disposing)
    {
        if (!disposedValue)
        {
            if (disposing)
            {
                // TODO: dispose managed state (managed objects).
            }

            // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
            // TODO: set large fields to null.
            try
            {
                File.Delete(_exe.FullName);
            }
            catch
            {

            }

            disposedValue = true;
        }
    }

    // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
    // ~PdfToPrinterWrapper() {
    //   // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
    //   Dispose(false);
    // }

    // This code added to correctly implement the disposable pattern.
    public void Dispose()
    {
        // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
        Dispose(true);
        // TODO: uncomment the following line if the finalizer is overridden above.
        // GC.SuppressFinalize(this);
    }
    #endregion
}

5) Enjoy printing pdf files from your code.

Use like this:

FileInfo file = new FileInfo(@"c:\Sandbox\dummy file.pdf");
SumatraWrapper pdfToPrinter =
    new SumatraWrapper();
pdfToPrinter.Print(file, "My Printer");

Seeding the random number generator in Javascript

Many people who need a seedable random-number generator in Javascript these days are using David Bau's seedrandom module.

regex error - nothing to repeat

It's not only a Python bug with * actually, it can also happen when you pass a string as a part of your regular expression to be compiled, like ;

import re
input_line = "string from any input source"
processed_line= "text to be edited with {}".format(input_line)
target = "text to be searched"
re.search(processed_line, target)

this will cause an error if processed line contained some "(+)" for example, like you can find in chemical formulae, or such chains of characters. the solution is to escape but when you do it on the fly, it can happen that you fail to do it properly...

How to list all the files in android phone by using adb shell?

Some Android phones contain Busybox. Was hard to find.

To see if busybox was around:

ls -lR / | grep busybox

If you know it's around. You need some read/write space. Try you flash drive, /sdcard

cd /sdcard
ls -lR / >lsoutput.txt

upload to your computer. Upload the file. Get some text editor. Search for busybox. Will see what directory the file was found in.

busybox find /sdcard -iname 'python*'

to make busybox easier to access, you could:

cd /sdcard
ln -s /where/ever/busybox/is  busybox
/sdcard/busybox find /sdcard -iname 'python*'

Or any other place you want. R

How to show full height background image?

 html, body {
    height:100%;
}

body { 
    background: url(images/bg.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

READ_EXTERNAL_STORAGE permission for Android

You have to ask for the permission at run time:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
        && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
            REQUEST_PERMISSION);
    dialog.dismiss();
    return;
}

And in the callback below you can access the storage without a problem.

@Override
public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == REQUEST_PERMISSION) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // Permission granted.
        } else {
            // User refused to grant permission.
        }
    }
}

Permission denied (publickey,gssapi-keyex,gssapi-with-mic)

I found this error while connecting ec2 instance with ssh. and it comes if i write wrong user name.

eg. for ubuntu I need to use ubuntu as user name and for others I need to use ec2-user.

Using GroupBy, Count and Sum in LINQ Lambda Expressions

    var ListByOwner = list.GroupBy(l => l.Owner)
                          .Select(lg => 
                                new { 
                                    Owner = lg.Key, 
                                    Boxes = lg.Count(),
                                    TotalWeight = lg.Sum(w => w.Weight), 
                                    TotalVolume = lg.Sum(w => w.Volume) 
                                });

Best practices for copying files with Maven

Another way is to bundle these things into an artifact using the assembly plugin. Then you can use the dependency plugin to unpack these files where you want. There are also copy goals in the dependency plugin to copy artifacts.

Datetime equal or greater than today in MySQL

you can return all rows and than use php datediff function inside an if statement, although that will put extra load on the server.

if(dateDiff(date("Y/m/d"), $row['date']) <=0 ){    
}else{    
echo " info here";    
}