Programs & Examples On #Callcc

call-with-current-continuation (abbreviated as call/cc) is a control operator in functional programming

What does Ruby have that Python doesn't, and vice versa?

Surprised to see nothing mentioned of ruby's "method missing" mechanism. I'd give examples of the find_by_... methods in Rails, as an example of the power of that language feature. My guess is that something similar could be implemented in Python, but to my knowledge it isn't there natively.

How to repeat last command in python interpreter shell?

Up Arrow works only in Python command line.

In IDLE (Python GUI) the defaults are: Alt-p : retrieves previous command matching what you have typed. Alt-n : retrieves next... In Python 2.7.9 for example, you can see/change the Action Keys selecting: Options -> Configure IDLE -> (Tab) Keys

grep for multiple strings in file on different lines (ie. whole file, not line based search)?

Here's what worked well for me:

find . -path '*/.svn' -prune -o -type f -exec gawk '/Dansk/{a=1}/Norsk/{b=1}/Svenska/{c=1}END{ if (a && b && c) print FILENAME }' {} \;
./path/to/file1.sh
./another/path/to/file2.txt
./blah/foo.php

If I just wanted to find .sh files with these three, then I could have used:

find . -path '*/.svn' -prune -o -type f -name "*.sh" -exec gawk '/Dansk/{a=1}/Norsk/{b=1}/Svenska/{c=1}END{ if (a && b && c) print FILENAME }' {} \;
./path/to/file1.sh

Show how many characters remaining in a HTML text box using JavaScript

try this code in here...this is done using javascript onKeyUp() function...

<script>
function toCount(entrance,exit,text,characters) {  
var entranceObj=document.getElementById(entrance);  
var exitObj=document.getElementById(exit);  
var length=characters - entranceObj.value.length;  
if(length <= 0) {  
length=0;  
text='<span class="disable"> '+text+' <\/span>';  
entranceObj.value=entranceObj.value.substr(0,characters);  
}  
exitObj.innerHTML = text.replace("{CHAR}",length);  
}
</script>

textarea counter demo

Determine version of Entity Framework I am using?

if you are using EF core this command below could help

dotnet ef --version

Can we use join for two different database tables?

SQL Server allows you to join tables from different databases as long as those databases are on the same server. The join syntax is the same; the only difference is that you must fully specify table names.

Let's suppose you have two databases on the same server - Db1 and Db2. Db1 has a table called Clients with a column ClientId and Db2 has a table called Messages with a column ClientId (let's leave asside why those tables are in different databases).

Now, to perform a join on the above-mentioned tables you will be using this query:

select *
from Db1.dbo.Clients c
join Db2.dbo.Messages m on c.ClientId = m.ClientId

How do I convert strings in a Pandas data frame to a 'date' data type?

Use astype

In [31]: df
Out[31]: 
   a        time
0  1  2013-01-01
1  2  2013-01-02
2  3  2013-01-03

In [32]: df['time'] = df['time'].astype('datetime64[ns]')

In [33]: df
Out[33]: 
   a                time
0  1 2013-01-01 00:00:00
1  2 2013-01-02 00:00:00
2  3 2013-01-03 00:00:00

How to change Maven local repository in eclipse

In newer versions of Eclipse the global configuration file can be set in

Windows > Preferences > Maven > User Settings > Global Settings

Don't beat me why global settings can be configured in user settings... Probably because of the same reason why you need to press "Start" to shutdown your PC on Windows... :D

JavaScript/regex: Remove text between parentheses

I found this version most suitable for all cases. It doesn't remove all whitespaces.

For example "a (test) b" -> "a b"

"Hello, this is Mike (example)".replace(/ *\([^)]*\) */g, " ").trim(); "Hello, this is (example) Mike ".replace(/ *\([^)]*\) */g, " ").trim();

Get string character by index - Java

It is as simple as:

String charIs = string.charAt(index) + "";

How to update/modify an XML file in python?

While I agree with Tim and Oben Sonne that you should use an XML library, there are ways to still manipulate it as a simple string object.

I likely would not try to use a single file pointer for what you are describing, and instead read the file into memory, edit it, then write it out.:

inFile = open('file.xml', 'r')
data = inFile.readlines()
inFile.close()
# some manipulation on `data`
outFile = open('file.xml', 'w')
outFile.writelines(data)
outFile.close()

Find the greatest number in a list of numbers

max is a builtin function in python, which is used to get max value from a sequence, i.e (list, tuple, set, etc..)

print(max([9, 7, 12, 5]))

# prints 12 

MySQL OPTIMIZE all tables?

my 1 cent, added and TABLE_TYPE='BASE TABLE' so we can skip the 'VIEW' type.

for table in `mysql -sss -e "select concat(table_schema,'.',table_name) from information_schema.tables where table_schema not in ('mysql','information_schema','performance_schema') and TABLE_TYPE='BASE TABLE' order by data_free desc;"`
do
mysql -e "OPTIMIZE TABLE $table;"
done

Use CASE statement to check if column exists in table - SQL Server

You can check in the system 'table column mapping' table

SELECT count(*)
  FROM Sys.Columns c
  JOIN Sys.Tables t ON c.Object_Id = t.Object_Id
 WHERE upper(t.Name) = 'TAGS'
   AND upper(c.NAME) = 'MODIFIEDBYUSER'

how to change color of TextinputLayout's label and edittext underline android

With the Material Components Library you can use the com.google.android.material.textfield.TextInputLayout.

You can apply a custom style to change the colors.

To change the hint color you have to use these attributes:
hintTextColor and android:textColorHint.

<style name="Custom_textinputlayout_filledbox" parent="@style/Widget.MaterialComponents.TextInputLayout.FilledBox">
    <!-- The color of the label when it is collapsed and the text field is active -->
    <item name="hintTextColor">?attr/colorPrimary</item>

    <!-- The color of the label in all other text field states (such as resting and disabled) -->
    <item name="android:textColorHint">@color/selector_hint_text_color</item>
</style>

You should use a selector for the android:textColorHint. Something like:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:alpha="0.38" android:color="?attr/colorOnSurface" android:state_enabled="false"/>
  <item android:alpha="0.6" android:color="?attr/colorOnSurface"/>
</selector>

To change the bottom line color you have to use the attribute: boxStrokeColor.

<style name="Custom_textinputlayout_filledbox" parent="@style/Widget.MaterialComponents.TextInputLayout.FilledBox">
    ....
    <item name="boxStrokeColor">@color/selector_stroke_color</item>
</style>

Also in this case you should use a selector. Something like:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:color="?attr/colorPrimary" android:state_focused="true"/>
  <item android:alpha="0.87" android:color="?attr/colorOnSurface" android:state_hovered="true"/>
  <item android:alpha="0.12" android:color="?attr/colorOnSurface" android:state_enabled="false"/>
  <item android:alpha="0.38" android:color="?attr/colorOnSurface"/>
</selector>

enter image description here enter image description here

You can also apply these attributes in your layout:

<com.google.android.material.textfield.TextInputLayout
    style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox"
    app:boxStrokeColor="@color/selector_stroke_color"
    app:hintTextColor="?attr/colorPrimary"
    android:textColorHint="@color/selector_hint_text_color"
    ...>

Copy output of a JavaScript variable to the clipboard

I just want to add, if someone wants to copy two different inputs to clipboard. I also used the technique of putting it to a variable then put the text of the variable from the two inputs into a text area.

Note: the code below is from a user asking how to copy multiple user inputs into clipboard. I just fixed it to work correctly. So expect some old style like the use of var instead of let or const. I also recommend to use addEventListener for the button.

_x000D_
_x000D_
    function doCopy() {_x000D_
_x000D_
        try{_x000D_
            var unique = document.querySelectorAll('.unique');_x000D_
            var msg ="";_x000D_
_x000D_
            unique.forEach(function (unique) {_x000D_
                msg+=unique.value;_x000D_
            });_x000D_
_x000D_
            var temp =document.createElement("textarea");_x000D_
            var tempMsg = document.createTextNode(msg);_x000D_
            temp.appendChild(tempMsg);_x000D_
_x000D_
            document.body.appendChild(temp);_x000D_
            temp.select();_x000D_
            document.execCommand("copy");_x000D_
            document.body.removeChild(temp);_x000D_
            console.log("Success!")_x000D_
_x000D_
_x000D_
        }_x000D_
        catch(err) {_x000D_
_x000D_
            console.log("There was an error copying");_x000D_
        }_x000D_
    }
_x000D_
<input type="text" class="unique" size="9" value="SESA / D-ID:" readonly/>_x000D_
<input type="text" class="unique" size="18" value="">_x000D_
<button id="copybtn" onclick="doCopy()"> Copy to clipboard </button>
_x000D_
_x000D_
_x000D_

CSS Custom Dropdown Select that works across all browsers IE7+ FF Webkit

As per Link: http://bavotasan.com/2011/style-select-box-using-only-css/ there are lot of extra rework that needs to be done(Put extra div and position the image there. Also the design will break as the option drilldown will be mis alligned to the the select.

Here is an easy and simple way which will allow you to put your own dropdown image and remove the browser default dropdown.(Without using any extra div). Its cross browser as well.

HTML

<select class="dropdown" name="drop-down">
  <option value="select-option">Please select...</option>
  <option value="Local-Community-Enquiry">Option 1</option>
  <option value="Bag-Packing-in-Store">Option 2</option>
</select>

CSS

select.dropdown {
  margin: 0px;
  margin-top: 12px;
  height: 48px;
  width: 100%;
  border-width: 1px;
  border-style: solid;
  border-color: #666666;
  padding: 9px;
  font-family: tescoregular;
  font-size: 16px;
  color: #666666;
  -webkit-appearance: none;
  -webkit-border-radius: 0px;
  -moz-appearance: none;
  appearance: none;
  background: url('yoururl/dropdown.png') no-repeat 97% 50% #ffffff;
  background-size: 11px 7px;
}

Split string in C every white space

Something going wrong is get_words() always returning one less than the actual word count, so eventually you attempt to:

char *newbuff[words]; /* Words is one less than the actual number,
so this is declared to be too small. */

newbuff[count2] = (char *)malloc(strlen(buffer))

count2, eventually, is always one more than the number of elements you've declared for newbuff[]. Why malloc() isn't returning a valid ptr, though, I don't know.

PHP - get base64 img string decode and save as jpg (resulting empty image )

Decode and save image as PNG

header('content-type: image/png');

           ob_start();

        $ret = fopen($fullurl, 'r', true, $context);
        $contents = stream_get_contents($ret);
        $base64 = 'data:image/PNG;base64,' . base64_encode($contents);
        echo "<img src=$base64 />" ;


        ob_end_flush();

How to remove an item from an array in Vue.js

Don't forget to bind key attribute otherwise always last item will be deleted

Correct way to delete selected item from array:

Template

<div v-for="(item, index) in items" :key="item.id">
  <input v-model="item.value">
   <button @click="deleteItem(index)">
  delete
</button>

script

deleteItem(index) {
  this.items.splice(index, 1); \\OR   this.$delete(this.items,index)
 \\both will do the same
}

what is an illegal reflective access

Apart from an understanding of the accesses amongst modules and their respective packages. I believe the crux of it lies in the Module System#Relaxed-strong-encapsulation and I would just cherry-pick the relevant parts of it to try and answer the question.

What defines an illegal reflective access and what circumstances trigger the warning?

To aid in the migration to Java-9, the strong encapsulation of the modules could be relaxed.

  • An implementation may provide static access, i.e. by compiled bytecode.

  • May provide a means to invoke its run-time system with one or more packages of one or more of its modules open to code in all unnamed modules, i.e. to code on the classpath. If the run-time system is invoked in this way, and if by doing so some invocations of the reflection APIs succeed where otherwise they would have failed.

In such cases, you've actually ended up making a reflective access which is "illegal" since in a pure modular world you were not meant to do such accesses.

How it all hangs together and what triggers the warning in what scenario?

This relaxation of the encapsulation is controlled at runtime by a new launcher option --illegal-access which by default in Java9 equals permit. The permit mode ensures

The first reflective-access operation to any such package causes a warning to be issued, but no warnings are issued after that point. This single warning describes how to enable further warnings. This warning cannot be suppressed.

The modes are configurable with values debug(message as well as stacktrace for every such access), warn(message for each such access), and deny(disables such operations).


Few things to debug and fix on applications would be:-

  • Run it with --illegal-access=deny to get to know about and avoid opening packages from one module to another without a module declaration including such a directive(opens) or explicit use of --add-opens VM arg.
  • Static references from compiled code to JDK-internal APIs could be identified using the jdeps tool with the --jdk-internals option

The warning message issued when an illegal reflective-access operation is detected has the following form:

WARNING: Illegal reflective access by $PERPETRATOR to $VICTIM

where:

$PERPETRATOR is the fully-qualified name of the type containing the code that invoked the reflective operation in question plus the code source (i.e., JAR-file path), if available, and

$VICTIM is a string that describes the member being accessed, including the fully-qualified name of the enclosing type

Questions for such a sample warning: = JDK9: An illegal reflective access operation has occurred. org.python.core.PySystemState

Last and an important note, while trying to ensure that you do not face such warnings and are future safe, all you need to do is ensure your modules are not making those illegal reflective accesses. :)

How to truncate text in Angular2?

Two way to truncate text into angular.

let str = 'How to truncate text in angular';

1. Solution

  {{str | slice:0:6}}

Output:

   how to

If you want to append any text after slice string like

   {{ (str.length>6)? (str | slice:0:6)+'..':(str) }}

Output:

 how to...

2. Solution(Create custom pipe)

if you want to create custom truncate pipe

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

@Pipe({
 name: 'truncate'
})

export class TruncatePipe implements PipeTransform {

transform(value: string, args: any[]): string {
    const limit = args.length > 0 ? parseInt(args[0], 10) : 20;
    const trail = args.length > 1 ? args[1] : '...';
    return value.length > limit ? value.substring(0, limit) + trail : value;
   }
}

In Markup

{{ str | truncate:[20] }} // or 
{{ str | truncate:[20, '...'] }} // or

Don't forget to add a module entry.

@NgModule({
  declarations: [
    TruncatePipe
  ]
})
export class AppModule {}

How to check the differences between local and github before the pull

And another useful command to do this (after git fetch) is:

git log origin/master ^master

This shows the commits that are in origin/master but not in master. You can also do it in opposite when doing git pull, to check what commits will be submitted to remote.

caching JavaScript files

I have a simple system that is pure JavaScript. It checks for changes in a simple text file that is never cached. When you upload a new version this file is changed. Just put the following JS at the top of the page.

_x000D_
_x000D_
        (function(url, storageName) {_x000D_
            var fromStorage = localStorage.getItem(storageName);_x000D_
            var fullUrl = url + "?rand=" + (Math.floor(Math.random() * 100000000));_x000D_
            getUrl(function(fromUrl) {_x000D_
//                   first load_x000D_
                if (!fromStorage) {_x000D_
                    localStorage.setItem(storageName, fromUrl);_x000D_
                    return;_x000D_
                }_x000D_
//                    old file_x000D_
                if (fromStorage === fromUrl) {_x000D_
                    return;_x000D_
                }_x000D_
                // files updated_x000D_
                localStorage.setItem(storageName, fromUrl);_x000D_
                location.reload(true);_x000D_
            });_x000D_
            function getUrl(fn) {_x000D_
                var xmlhttp = new XMLHttpRequest();_x000D_
                xmlhttp.open("GET", fullUrl, true);_x000D_
                xmlhttp.send();_x000D_
                xmlhttp.onreadystatechange = function() {_x000D_
                    if (xmlhttp.readyState === XMLHttpRequest.DONE) {_x000D_
                        if (xmlhttp.status === 200 || xmlhttp.status === 2) {_x000D_
                            fn(xmlhttp.responseText);_x000D_
                        }_x000D_
                        else if (xmlhttp.status === 400) {_x000D_
                            throw 'unable to load file for cache check ' +  url;_x000D_
                        }_x000D_
                        else {_x000D_
                           throw 'unable to load file for cache check ' +  url;_x000D_
                        }_x000D_
                    }_x000D_
                };_x000D_
            }_x000D_
            ;_x000D_
        })("version.txt", "version");
_x000D_
_x000D_
_x000D_

just replace the "version.txt" with your file that is always run and "version" with the name you want to use for your local storage.

git pull while not in a git directory

You can write a script like this:

cd /X/Y
git pull

You can name it something like gitpull.
If you'd rather have it do arbitrary directories instead of /X/Y:

cd $1
git pull

Then you can call it with gitpull /X/Z
Lastly, you can try finding repositories. I have a ~/git folder which contains repositories, and you can use this to do a pull on all of them.

g=`find /X -name .git`
for repo in ${g[@]}
do
    cd ${repo}
    cd ..
    git pull
done

SQL Server: Get data for only the past year

declare @iMonth int
declare @sYear varchar(4)
declare @sMonth varchar(2)
set @iMonth = 0
while @iMonth > -12
begin
    set @sYear = year(DATEADD(month,@iMonth,GETDATE()))
    set @sMonth = right('0'+cast(month(DATEADD(month,@iMonth,GETDATE())) as varchar(2)),2)
    select @sYear + @sMonth
    set @iMonth = @iMonth - 1
end

Remove non-ascii character in string

You can use the following regex to replace non-ASCII characters

str = str.replace(/[^A-Za-z 0-9 \.,\?""!@#\$%\^&\*\(\)-_=\+;:<>\/\\\|\}\{\[\]`~]*/g, '')

However, note that spaces, colons and commas are all valid ASCII, so the result will be

> str
"INFO] :, , ,  (Higashikurume)"

Create an empty list in python with certain size

I came across this SO question while searching for a similar problem. I had to build a 2D array and then replace some elements of each list (in 2D array) with elements from a dict. I then came across this SO question which helped me, maybe this will help other beginners to get around. The key trick was to initialize the 2D array as an numpy array and then using array[i,j] instead of array[i][j].

For reference this is the piece of code where I had to use this :

nd_array = []
for i in range(30):
    nd_array.append(np.zeros(shape = (32,1)))
new_array = []
for i in range(len(lines)):
    new_array.append(nd_array)
new_array = np.asarray(new_array)
for i in range(len(lines)):
    splits = lines[i].split(' ')
    for j in range(len(splits)):
        #print(new_array[i][j])
        new_array[i,j] = final_embeddings[dictionary[str(splits[j])]-1].reshape(32,1)

Now I know we can use list comprehension but for simplicity sake I am using a nested for loop. Hope this helps others who come across this post.

Django: multiple models in one template using forms

According to Django documentation, inline formsets are for this purpose: "Inline formsets is a small abstraction layer on top of model formsets. These simplify the case of working with related objects via a foreign key".

See https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets

Count specific character occurrences in a string

Use:

Function fNbrStrInStr(strin As Variant, strToCount As String)
    fNbrStrInStr = UBound(Split(strin, strToCount)) - LBound(Split(strin, strToCount))
End Function

I used strin as variant to handle very long text. The split can be zero-based or one-based for low end depending on user settings, and subtracting it ensures the correct count.

I did not include a test for strcount being longer than strin to keep code concise.

Showing Thumbnail for link in WhatsApp || og:image meta-tag doesn't work

Additional useful info:

You can provide several og:images, whatsapp will use the last one. This will help with the problem that e.g. facebook want 1.91:1 ratio and whatsapp 1:1

https://stackoverflow.com/a/61078968/8486854

How to remove any URL within a string in Python

I know this has already been answered and its stupid late but I think this should be here. This is a regex that matches any kind of url.

[^ ]+\.[^ ]+

It can be used like

re.sub('[^ ]+\.[^ ]+','',sentence)

Groovy executing shell commands

Ok, solved it myself;

def sout = new StringBuilder(), serr = new StringBuilder()
def proc = 'ls /badDir'.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println "out> $sout\nerr> $serr"

displays:

out> err> ls: cannot access /badDir: No such file or directory

Binary Data Posting with curl

You don't need --header "Content-Length: $LENGTH".

curl --request POST --data-binary "@template_entry.xml" $URL

Note that GET request does not support content body widely.

Also remember that POST request have 2 different coding schema. This is first form:

  $ nc -l -p 6666 &
  $ curl  --request POST --data-binary "@README" http://localhost:6666

POST / HTTP/1.1
User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6
Host: localhost:6666
Accept: */*
Content-Length: 9309
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

.. -*- mode: rst; coding: cp1251; fill-column: 80 -*-
.. rst2html.py README README.html
.. contents::

You probably request this:

-F/--form name=content
           (HTTP) This lets curl emulate a filled-in form in
              which a user has pressed the submit button. This
              causes curl to POST data using the Content- Type
              multipart/form-data according to RFC2388. This
              enables uploading of binary files etc. To force the
              'content' part to be a file, prefix the file name
              with an @ sign. To just get the content part from a
              file, prefix the file name with the symbol <. The
              difference between @ and < is then that @ makes a
              file get attached in the post as a file upload,
              while the < makes a text field and just get the
              contents for that text field from a file.

Find duplicate characters in a String and count the number of occurances using Java

I solved this with 2 dimensional array. Input: aaaabbbcdefggggh Output:a4b3cdefg4h

int[][] arr = new int[10][2];
    String st = "aaaabbbcdefggggh";
    char[] stArr = st.toCharArray();
    int i = 0;
    int j = 0;
    for (int k = 0; k < stArr.length; k++) {
        if (k == 0) {
            arr[i][j] = stArr[k];
            arr[i][j + 1] = 1;
        } else {
            if (arr[i][j] == stArr[k]) {
                arr[i][j + 1] = arr[i][j + 1] + 1;
            } else {
                arr[++i][j] = stArr[k];
                arr[i][j + 1] = 1;
            }
        }
    }
    System.out.print(arr.length);
    String output = "";
    for (int m = 0; m < arr.length; m++) {
        if (arr[m][1] > 0) {
            String character = Character.toString((char) arr[m][0]);
            String cnt = arr[m][1] > 1 ? String.valueOf(arr[m][1]) : "";
            output = output + character + cnt;

        }
    }
    System.out.print(output);

Is it possible to get a history of queries made in postgres

There's no history in the database itself, if you're using psql you can use "\s" to see your command history there.

You can get future queries or other types of operations into the log files by setting log_statement in the postgresql.conf file. What you probably want instead is log_min_duration_statement, which if you set it to 0 will log all queries and their durations in the logs. That can be helpful once your apps goes live, if you set that to a higher value you'll only see the long running queries which can be helpful for optimization (you can run EXPLAIN ANALYZE on the queries you find there to figure out why they're slow).

Another handy thing to know in this area is that if you run psql and tell it "\timing", it will show how long every statement after that takes. So if you have a sql file that looks like this:

\timing
select 1;

You can run it with the right flags and see each statement interleaved with how long it took. Here's how and what the result looks like:

$ psql -ef test.sql 
Timing is on.
select 1;
 ?column? 
----------
        1
(1 row)

Time: 1.196 ms

This is handy because you don't need to be database superuser to use it, unlike changing the config file, and it's easier to use if you're developing new code and want to test it out.

Custom method names in ASP.NET Web API

By default the route configuration follows RESTFul conventions meaning that it will accept only the Get, Post, Put and Delete action names (look at the route in global.asax => by default it doesn't allow you to specify any action name => it uses the HTTP verb to dispatch). So when you send a GET request to /api/users/authenticate you are basically calling the Get(int id) action and passing id=authenticate which obviously crashes because your Get action expects an integer.

If you want to have different action names than the standard ones you could modify your route definition in global.asax:

Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { action = "get", id = RouteParameter.Optional }
);

Now you can navigate to /api/users/getauthenticate to authenticate the user.

How to read data from a zip file without having to unzip the entire file

Something like this will list and extract the files one by one, if you want to use SharpZipLib:

var zip = new ZipInputStream(File.OpenRead(@"C:\Users\Javi\Desktop\myzip.zip"));
var filestream = new FileStream(@"C:\Users\Javi\Desktop\myzip.zip", FileMode.Open, FileAccess.Read);
ZipFile zipfile = new ZipFile(filestream);
ZipEntry item;
while ((item = zip.GetNextEntry()) != null)
{
     Console.WriteLine(item.Name);
     using (StreamReader s = new StreamReader(zipfile.GetInputStream(item)))
     {
      // stream with the file
          Console.WriteLine(s.ReadToEnd());
     }
 }

Based on this example: content inside zip file

CSS opacity only to background color, not the text on it?

The easiest way to do this is with 2 divs, 1 with the background and 1 with the text:

_x000D_
_x000D_
#container {_x000D_
  position: relative;_x000D_
  width: 300px;_x000D_
  height: 200px;_x000D_
}_x000D_
#block {_x000D_
  background: #CCC;_x000D_
  filter: alpha(opacity=60);_x000D_
  /* IE */_x000D_
  -moz-opacity: 0.6;_x000D_
  /* Mozilla */_x000D_
  opacity: 0.6;_x000D_
  /* CSS3 */_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
}_x000D_
#text {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}
_x000D_
<div id="container">_x000D_
  <div id="block"></div>_x000D_
  <div id="text">Test</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the best way to paginate results in SQL Server

You didn't specify the language nor which driver you are using. Therefore I'm describing it abstractly.

  • Create a scrollable resultset / dataset. This required a primary on the table(s)
  • jump to the end
  • request the row count
  • jump to the start of the page
  • scroll through the rows until the end of the page

PostgreSQL 'NOT IN' and subquery

When using NOT IN, you should also consider NOT EXISTS, which handles the null cases silently. See also PostgreSQL Wiki

SELECT mac, creation_date 
FROM logs lo
WHERE logs_type_id=11
AND NOT EXISTS (
  SELECT *
  FROM consols nx
  WHERE nx.mac = lo.mac
  );

What is the difference between .py and .pyc files?

.pyc contain the compiled bytecode of Python source files. The Python interpreter loads .pyc files before .py files, so if they're present, it can save some time by not having to re-compile the Python source code. You can get rid of them if you want, but they don't cause problems, they're not big, and they may save some time when running programs.

Why can't I check if a 'DateTime' is 'Nothing'?

Some examples on working with nullable DateTime values.

(See Nullable Value Types (Visual Basic) for more.)

'
' An ordinary DateTime declaration. It is *not* nullable. Setting it to
' 'Nothing' actually results in a non-null value.
'
Dim d1 As DateTime = Nothing
Console.WriteLine(String.Format("d1 = [{0}]\n", d1))
' Output:  d1 = [1/1/0001 12:00:00 AM]

' Console.WriteLine(String.Format("d1 is Nothing? [{0}]\n", (d1 Is Nothing)))
'
'   Compilation error on above expression '(d1 Is Nothing)':
'
'      'Is' operator does not accept operands of type 'Date'.
'       Operands must be reference or nullable types.

'
' Three different but equivalent ways to declare a DateTime
' nullable:
'
Dim d2? As DateTime = Nothing
Console.WriteLine(String.Format("d2 = [{0}][{1}]\n", d2, (d2 Is Nothing)))
' Output:  d2 = [][True]

Dim d3 As DateTime? = Nothing
Console.WriteLine(String.Format("d3 = [{0}][{1}]\n", d3, (d3 Is Nothing)))
' Output:  d3 = [][True]

Dim d4 As Nullable(Of DateTime) = Nothing
Console.WriteLine(String.Format("d4 = [{0}][{1}]\n", d4, (d4 Is Nothing)))
' Output:  d4 = [][True]

Also, on how to check whether a variable is null (from Nothing (Visual Basic)):

When checking whether a reference (or nullable value type) variable is null, do not use = Nothing or <> Nothing. Always use Is Nothing or IsNot Nothing.

jQuery window scroll event does not fire up

$('#div').scroll(function () {
   if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight-1) {

     //fire your event


    }
}

month name to month number and vice versa in python

Just for fun:

from time import strptime

strptime('Feb','%b').tm_mon

How to create a box when mouse over text in pure CSS?

You can also do it by toggling between display: block on hover and display:none without hover to produce the effect.

When to use IMG vs. CSS background-image?

Just a small one to add, you should use the img tag if you want users to be able to 'right click' and 'save-image'/'save-picture', so if you intend to provide the image as a resource for others.

Using background image will (as far as I'm aware on most browsers) disable the option to save the image directly.

How to linebreak an svg text within javascript?

This is not something that SVG 1.1 supports. SVG 1.2 does have the textArea element, with automatic word wrapping, but it's not implemented in all browsers. SVG 2 does not plan on implementing textArea, but it does have auto-wrapped text.

However, given that you already know where your linebreaks should occur, you can break your text into multiple <tspan>s, each with x="0" and dy="1.4em" to simulate actual lines of text. For example:

<g transform="translate(123 456)"><!-- replace with your target upper left corner coordinates -->
  <text x="0" y="0">
    <tspan x="0" dy="1.2em">very long text</tspan>
    <tspan x="0" dy="1.2em">I would like to linebreak</tspan>
  </text>
</g>

Of course, since you want to do that from JavaScript, you'll have to manually create and insert each element into the DOM.

Create two threads, one display odd & other even numbers

package com.example;

public class MyClass  {
    static int mycount=0;
    static Thread t;
    static Thread t2;
    public static void main(String[] arg)
    {
        t2=new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.print(mycount++ + " even \n");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(mycount>25)
                    System.exit(0);
                run();
            }
        });
        t=new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.print(mycount++ + " odd \n");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(mycount>26)
                    System.exit(0);
                run();
            }
        });
        t.start();
        t2.start();
    }
}

How to fix "no valid 'aps-environment' entitlement string found for application" in Xcode 4.3?

This was what fixed it for me. (I had already tried toggling the capabilities on/off, recreating the provisioning profile, etc).

In the Build Settings tab, in Code Signing Entitlements, my .entitlements file wasn't link for all sections. Once I added it to the Any SDK section, the error was resolved.

enter image description here

Unable to load script from assets index.android.bundle on windows

For this problem I just solve it by running:

react-native start

then

adb reverse tcp:8081 tcp:8081

on command line. And then i can run:

react-native run-android

So i will not waste my time to run:

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

every time.

how to check for special characters php

preg_match('/'.preg_quote('^\'£$%^&*()}{@#~?><,@|-=-_+-¬', '/').'/', $string);

Maven version with a property

I have two recommendation for you

  1. Use CI Friendly Revision for all your artifacts. You can add -Drevision=2.0.1 in .mvn/maven.config file. So basically you define your version only at one location.
  2. For all external dependency create a property in parent file. You can use Apache Camel Parent Pom as reference

How to do multiple conditions for single If statement

As Hogan notes above, use an AND instead of &. See this tutorial for more info.

Running a command as Administrator using PowerShell?

C:\Users\"username"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell is where the shortcut of PowerShell resides. It too still goes to a different location to invoke the actual 'exe' (%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe).

Since PowerShell is user-profile driven when permissions are concerned; if your username/profile has the permissions to do something then under that profile, in PowerShell you would generally be able to do it as well. That being said, it would make sense that you would alter the shortcut located under your user profile, for example, C:\Users\"username"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell.

Right-click and click properties. Click "Advanced" button under the "Shortcut" tab located right below the "Comments" text field adjacent to the right of two other buttons, "Open File Location" and "Change Icon", respectively.

Check the checkbox that reads, "Run as Administrator". Click OK, then Apply and OK. Once again right click the icon labeled 'Windows PowerShell' located in C:\Users\"username"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell and select "Pin to Start Menu/Taskbar".

Now whenever you click that icon, it will invoke the UAC for escalation. After selecting 'YES', you will notice the PowerShell console open and it will be labeled "Administrator" on the top of the screen.

To go a step further... you could right click that same icon shortcut in your profile location of Windows PowerShell and assign a keyboard shortcut that will do the exact same thing as if you clicked the recently added icon. So where it says "Shortcut Key" put in a keyboard key/button combination like: Ctrl + Alt + PP (for PowerShell). Click Apply and OK.

Now all you have to do is press that button combination you assigned and you will see UAC get invoked, and after you select 'YES' you will see a PowerShell console appear and "Administrator" displayed on the title bar.

python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>

When you open the file you want to write to, open it with a specific encoding that can handle all the characters.

with open('filename', 'w', encoding='utf-8') as f:
    print(r['body'], file=f)

Python Linked List

If you want to just create a simple liked list then refer this code

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

for visualize execution for this cod Visit http://www.pythontutor.com/visualize.html#mode=edit

set initial viewcontroller in appdelegate - swift

Swift 3, Swift 4:

Change first line to

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool

the rest is same.

Swift 5+:

Instantiate root view controller from storyboard:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // this line is important
        self.window = UIWindow(frame: UIScreen.main.bounds)

        // In project directory storyboard looks like Main.storyboard,
        // you should use only part before ".storyboard" as its name,
        // so in this example name is "Main".
        let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
        
        // controller identifier sets up in storyboard utilities
        // panel (on the right), it is called 'Storyboard ID'
        let viewController = storyboard.instantiateViewController(withIdentifier: "YourViewControllerIdentifier") as! YourViewController

        self.window?.rootViewController = viewController
        self.window?.makeKeyAndVisible()        
        return true
    }

If you want to use UINavigationController as root:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // this line is important
        self.window = UIWindow(frame: UIScreen.main.bounds)

        let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
        let viewController = storyboard.instantiateViewController(withIdentifier: "YourViewControllerIdentifier") as! YourViewController
        let navigationController = UINavigationController.init(rootViewController: viewController)
        self.window?.rootViewController = navigationController

        self.window?.makeKeyAndVisible()        
        return true
    }

Instantiate root view controller from xib:

It is almost the same, but instead of lines

let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "YourViewControllerIdentifier") as! YourViewController

you'll have to write

let viewController = YourViewController(nibName: "YourViewController", bundle: nil)

How to make a simple popup box in Visual C#?

Just type mbox then hit tab it will give you a magic shortcut to pump up a message box.

Android XML Percent Symbol

Not exactly your problem but a similar one.

If you have more than one formatting in your string entry, you should not use "%s" multiple times.

DON'T :

<string name="entry">Planned time %s - %s (%s)</string>

DO :

<string name="entry">Planned time %1$s - %2$s (%3$s)</string>

How to execute a java .class from the command line

My situation was a little complicated. I had to do three steps since I was using a .dll in the resources directory, for JNI code. My files were

S:\Accessibility\tools\src\main\resources\dlls\HelloWorld.dll
S:\Accessibility\tools\src\test\java\com\accessibility\HelloWorld.class

My code contained the following line

System.load(HelloWorld.class.getResource("/dlls/HelloWorld.dll").getPath());

First, I had to move to the classpath directory

cd /D "S:\Accessibility\tools\src\test\java"

Next, I had to change the classpath to point to the current directory so that my class would be loaded and I had to change the classpath to point to he resources directory so my dll would be loaded.

set classpath=%classpath%;.;..\..\..\src\main\resources; 

Then, I had to run java using the classname.

java com.accessibility.HelloWorld 

Add a CSS border on hover without moving the element

add margin:-1px; which reduces 1px to each side. or if you need only for side you can do margin-left:-1px etc.

iOS: present view controller programmatically

If you are using Storyboard and your "add" viewController is in storyboard then set an identifier for your "add" viewcontroller in settings so you can do something like this:

UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"NameOfYourStoryBoard" 
                                                     bundle:nil];
AddTaskViewController *add = 
           [storyboard instantiateViewControllerWithIdentifier:@"viewControllerIdentifier"];

[self presentViewController:add 
                   animated:YES 
                 completion:nil];

if you do not have your "add" viewController in storyboard or a nib file and want to create the whole thing programmaticaly then appDocs says:

If you cannot define your views in a storyboard or a nib file, override the loadView method to manually instantiate a view hierarchy and assign it to the view property.

How does Facebook Sharer select Images and other metadata when sharing my URL?

I couldn't get Facebook to pick the right image from a specific post, so I did what's outlined on this page:

https://webapps.stackexchange.com/questions/18468/adding-meta-tags-to-individual-blogger-posts

In other words, something like this:

<b:if cond='data:blog.url == "http://urlofyourpost.com"'>
  <meta content='http://urlofyourimage.png' property='og:image'/>
 </b:if>

Basically, you're going to hard code an if statement into your site's HTML to get it to change the meta content for whatever you've changed for that one post. It's a messy solution, but it works.

Unioning two tables with different number of columns

if only 1 row, you can use join

Select t1.Col1, t1.Col2, t1.Col3, t2.Col4, t2.Col5 from Table1 t1 join Table2 t2;

Deserializing a JSON file with JavaScriptSerializer()

Create a sub-class User with an id field and screen_name field, like this:

public class User
{
    public string id { get; set; }
    public string screen_name { get; set; }
}

public class Response {

    public string id { get; set; }
    public string text { get; set; }
    public string url { get; set; }
    public string width { get; set; }
    public string height { get; set; }
    public string size { get; set; }
    public string type { get; set; }
    public string timestamp { get; set; }
    public User user { get; set; }
}

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

From Save MySQL query results into a text or CSV file:

MySQL provides an easy mechanism for writing the results of a select statement into a text file on the server. Using extended options of the INTO OUTFILE nomenclature, it is possible to create a comma separated value (CSV) which can be imported into a spreadsheet application such as OpenOffice or Excel or any other application which accepts data in CSV format.

Given a query such as

SELECT order_id,product_name,qty FROM orders

which returns three columns of data, the results can be placed into the file /tmp/orders.txt using the query:

SELECT order_id,product_name,qty FROM orders
INTO OUTFILE '/tmp/orders.txt'

This will create a tab-separated file, each row on its own line. To alter this behavior, it is possible to add modifiers to the query:

SELECT order_id,product_name,qty FROM orders
INTO OUTFILE '/tmp/orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'

In this example, each field will be enclosed in double quotes, the fields will be separated by commas, and each row will be output on a new line separated by a newline (\n). Sample output of this command would look like:

"1","Tech-Recipes sock puppet","14.95" "2","Tech-Recipes chef's hat","18.95"

Keep in mind that the output file must not already exist and that the user MySQL is running as has write permissions to the directory MySQL is attempting to write the file to.

Syntax

   SELECT Your_Column_Name
    FROM Your_Table_Name
    INTO OUTFILE 'Filename.csv'
    FIELDS TERMINATED BY ','
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n'

Or you could try to grab the output via the client:

You could try executing the query from the your local client and redirect the output to a local file destination:

mysql -user -pass -e "select cols from table where cols not null" > /tmp/output

Hint: If you don't specify an absoulte path but use something like INTO OUTFILE 'output.csv' or INTO OUTFILE './output.csv', it will store the output file to the directory specified by show variables like 'datadir';.

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

install by this command given below conda install -c conda-forge keras

this is error "CondaError: Cannot link a source that does not exist" ive get in win 10. for your error put this command in your command line.

conda update conda

this work for me .

How do I run a Python program in the Command Prompt in Windows 7?

You need to edit the environment variable named PATH, and add ;c:\python27 to the end of that. The semicolon separates one pathname from another (you will already have several things in your PATH).

Alternately, you can just type

c:\python27\python

at the command prompt without having to modify any environment variables at all.

Get the date (a day before current time) in Bash

if you have GNU date and i understood you correctly

$ date +%Y:%m:%d -d "yesterday"
2009:11:09

or

$ date +%Y:%m:%d -d "1 day ago"
2009:11:09

Is it safe to store a JWT in localStorage with ReactJS?

Localstorage is designed to be accessible by javascript, so it doesn't provide any XSS protection. As mentioned in other answers, there is a bunch of possible ways to do an XSS attack, from which localstorage is not protected by default.

However, cookies have security flags which protect from XSS and CSRF attacks. HttpOnly flag prevents client side javascript from accessing the cookie, Secure flag only allows the browser to transfer the cookie through ssl, and SameSite flag ensures that the cookie is sent only to the origin. Although I just checked and SameSite is currently supported only in Opera and Chrome, so to protect from CSRF it's better to use other strategies. For example, sending an encrypted token in another cookie with some public user data.

So cookies are a more secure choice for storing authentication data.

Is calling destructor manually always a sign of bad design?

I have another situation where I think it is perfectly reasonable to call the destructor.

When writing a "Reset" type of method to restore an object to its initial state, it is perfectly reasonable to call the Destructor to delete the old data that is being reset.

class Widget
{
private: 
    char* pDataText { NULL  }; 
    int   idNumber  { 0     };

public:
    void Setup() { pDataText = new char[100]; }
    ~Widget()    { delete pDataText;          }

    void Reset()
    {
        Widget blankWidget;
        this->~Widget();     // Manually delete the current object using the dtor
        *this = blankObject; // Copy a blank object to the this-object.
    }
};

Getting all request parameters in Symfony 2

Since you are in a controller, the action method is given a Request parameter.

You can access all POST data with $request->request->all();. This returns a key-value pair array.

When using GET requests you access data using $request->query->all();

How to add external fonts to android application

One more point in addition to the above answers. When using a font inside a fragment, the typeface instantiation should be done in the onAttach method ( override ) as given below:

@Override
public void onAttach(Activity activity){
    super.onAttach(activity);
    Typeface tf = Typeface.createFromAsset(getApplicationContext().getAssets(),"fonts/fontname.ttf");
}

Reason:
There is a short span of time before a fragment is attached to an activity. If CreateFromAsset method is called before attaching fragment to an activity an error occurs.

Initialize empty vector in structure - c++

Like this:

#include <string>
#include <vector>

struct user
{
    std::string username;
    std::vector<unsigned char> userpassword;
};

int main()
{
    user r;   // r.username is "" and r.userpassword is empty
    // ...
}

Maven- No plugin found for prefix 'spring-boot' in the current project and in the plugin groups

Adding spring-boot-maven-plugin in the build resolved it in my case

<build>
    <finalName>mysample-web</finalName>
    <plugins>
    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>springloaded</artifactId>
                <version>1.2.1.RELEASE</version>
            </dependency>
        </dependencies>
    </plugin>
    </plugins>
</build>  

send mail from linux terminal in one line

You can also use sendmail:

/usr/sbin/sendmail [email protected] < /file/to/send

Trigger event when user scroll to specific element - with jQuery

Intersection Observer can be the best thing IMO, without any external library it does a really good job.

const options = {
            root: null,
            threshold: 0.25, // 0 - 1 this work as a trigger. 
            rootMargin: '150px'
        };

        const target = document.querySelector('h1#scroll-to');
        const observer = new IntersectionObserver(
           entries => { // each entry checks if the element is the view or not and if yes trigger the function accordingly
            entries.forEach(() => {
                alert('you have scrolled to the h1!')
            });
        }, options);
        observer.observe(target);

How can I solve the error 'TS2532: Object is possibly 'undefined'?

With the release of TypeScript 3.7, optional chaining (the ? operator) is now officially available.

As such, you can simplify your expression to the following:

const data = change?.after?.data();

You may read more about it from that version's release notes, which cover other interesting features released on that version.

Run the following to install the latest stable release of TypeScript.

npm install typescript

That being said, Optional Chaining can be used alongside Nullish Coalescing to provide a fallback value when dealing with null or undefined values

const data = change?.after?.data() ?? someOtherData();

How to split page into 4 equal parts?

Similar to other posts, but with an important distinction to make this work inside a div. The simpler answers aren't very copy-paste-able because they directly modify div or draw over the entire page.

The key here is that the containing div dividedbox has relative positioning, allowing it to sit nicely in your document with the other elements, while the quarters within have absolute positioning, giving you vertical/horizontal control inside the containing div.

As a bonus, text is responsively centered in the quarters.

HTML:

<head>
  <meta charset="utf-8">
  <title>Box model</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <h1 id="title">Title Bar</h1>
  <div id="dividedbox">
    <div class="quarter" id="NW">
      <p>NW</p>
    </div>
    <div class="quarter" id="NE">
      <p>NE</p>
    </div>
    <div class="quarter" id="SE">
      <p>SE</p>
    </div>?
    <div class="quarter" id="SW">
      <p>SW</p>
    </div>
  </div>
</body>

</html>

CSS:

html, body { height:95%;} /* Important to make sure your divs have room to grow in the document */
#title { background: lightgreen}
#dividedbox { position: relative; width:100%; height:95%}   /* for div growth */
.quarter {position: absolute; width:50%; height:50%;  /* gives quarters their size */
  display: flex; justify-content: center; align-items: center;} /* centers text */
#NW { top:0;    left:0;     background:orange;     }
#NE { top:0;    left:50%;   background:lightblue;  }
#SW { top:50%;  left:0;     background:green;      }
#SE { top:50%;  left:50%;   background:red;        }

http://jsfiddle.net/og0j2d3v/

Bootstrap 3 - Set Container Width to 940px Maximum for Desktops?

If you don't wish to compile bootstrap, copy the following and insert it in your custom css file. It's not recommended to change the original bootstrap css file. Also, you won't be able to modify the bootstrap original css if you are loading it from a cdn.

Paste this in your custom css file:

@media (min-width:992px)
    {
        .container{width:960px}
    }
@media (min-width:1200px)
    {
        .container{width:960px}
    }

I am here setting my container to 960px for anything that can accommodate it, and keeping the rest media sizes to default values. You can set it to 940px for this problem.

Python pandas: fill a dataframe row by row

This is a simpler version

import pandas as pd
df = pd.DataFrame(columns=('col1', 'col2', 'col3'))
for i in range(5):
   df.loc[i] = ['<some value for first>','<some value for second>','<some value for third>']`

Is it possible to 'prefill' a google form using data from a google spreadsheet?

You can create a pre-filled form URL from within the Form Editor, as described in the documentation for Drive Forms. You'll end up with a URL like this, for example:

https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=Mike+Jones&entry.787184751=1975-05-09&entry.1381372492&entry.960923899

buildUrls()

In this example, question 1, "Name", has an ID of 726721210, while question 2, "Birthday" is 787184751. Questions 3 and 4 are blank.

You could generate the pre-filled URL by adapting the one provided through the UI to be a template, like this:

function buildUrls() {
  var template = "https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=##Name##&entry.787184751=##Birthday##&entry.1381372492&entry.960923899";
  var ss = SpreadsheetApp.getActive().getSheetByName("Sheet1");  // Email, Name, Birthday
  var data = ss.getDataRange().getValues();

  // Skip headers, then build URLs for each row in Sheet1.
  for (var i = 1; i < data.length; i++ ) {
    var url = template.replace('##Name##',escape(data[i][1]))
                      .replace('##Birthday##',data[i][2].yyyymmdd());  // see yyyymmdd below
    Logger.log(url);  // You could do something more useful here.
  }
};

This is effective enough - you could email the pre-filled URL to each person, and they'd have some questions already filled in.

betterBuildUrls()

Instead of creating our template using brute force, we can piece it together programmatically. This will have the advantage that we can re-use the code without needing to remember to change the template.

Each question in a form is an item. For this example, let's assume the form has only 4 questions, as you've described them. Item [0] is "Name", [1] is "Birthday", and so on.

We can create a form response, which we won't submit - instead, we'll partially complete the form, only to get the pre-filled form URL. Since the Forms API understands the data types of each item, we can avoid manipulating the string format of dates and other types, which simplifies our code somewhat.

(EDIT: There's a more general version of this in How to prefill Google form checkboxes?)

/**
 * Use Form API to generate pre-filled form URLs
 */
function betterBuildUrls() {
  var ss = SpreadsheetApp.getActive();
  var sheet = ss.getSheetByName("Sheet1");
  var data = ss.getDataRange().getValues();  // Data for pre-fill

  var formUrl = ss.getFormUrl();             // Use form attached to sheet
  var form = FormApp.openByUrl(formUrl);
  var items = form.getItems();

  // Skip headers, then build URLs for each row in Sheet1.
  for (var i = 1; i < data.length; i++ ) {
    // Create a form response object, and prefill it
    var formResponse = form.createResponse();

    // Prefill Name
    var formItem = items[0].asTextItem();
    var response = formItem.createResponse(data[i][1]);
    formResponse.withItemResponse(response);

    // Prefill Birthday
    formItem = items[1].asDateItem();
    response = formItem.createResponse(data[i][2]);
    formResponse.withItemResponse(response);

    // Get prefilled form URL
    var url = formResponse.toPrefilledUrl();
    Logger.log(url);  // You could do something more useful here.
  }
};

yymmdd Function

Any date item in the pre-filled form URL is expected to be in this format: yyyy-mm-dd. This helper function extends the Date object with a new method to handle the conversion.

When reading dates from a spreadsheet, you'll end up with a javascript Date object, as long as the format of the data is recognizable as a date. (Your example is not recognizable, so instead of May 9th 1975 you could use 5/9/1975.)

// From http://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
Date.prototype.yyyymmdd = function() {
  var yyyy = this.getFullYear().toString();                                    
  var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based         
  var dd  = this.getDate().toString();             

  return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};

Error : getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443

I have a fresh Windows 10 installed on my PC and tried this on the command line and it works like a charm:

npm config rm https-proxy

SMTPAuthenticationError when sending mail using gmail and python

Your code looks correct but sometimes google blocks an IP when you try to send a email from an unusual location. You can try to unblock it by visiting https://accounts.google.com/DisplayUnlockCaptcha from the IP and following the prompts.

Reference: https://support.google.com/accounts/answer/6009563

Replace first occurrence of pattern in a string

I think you can use the overload of Regex.Replace to specify the maximum number of times to replace...

var regex = new Regex(Regex.Escape("o"));
var newText = regex.Replace("Hello World", "Foo", 1);

General guidelines to avoid memory leaks in C++

valgrind (only avail for *nix platforms) is a very nice memory checker

DSO missing from command line

DSO here means Dynamic Shared Object; since the error message says it's missing from the command line, I guess you have to add it to the command line.

That is, try adding -lpthread to your command line.

How to get absolute path to file in /resources folder of your project

You need to specifie path started from /

URL resource = YourClass.class.getResource("/abc");
Paths.get(resource.toURI()).toFile();

How To Save Canvas As An Image With canvas.toDataURL()?

This solution allows you to change the name of the downloaded file:

HTML:

<a id="link"></a>

JAVASCRIPT:

  var link = document.getElementById('link');
  link.setAttribute('download', 'MintyPaper.png');
  link.setAttribute('href', canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"));
  link.click();

Redirecting new tab on button click.(Response.Redirect) in asp.net C#

I think your code should work just remove one thing from here but it'll do redirection from current page within existing window

<asp:Button ID="btn" runat="Server" Text="SUBMIT" 

 OnClick="btnNewEntry_Click"/>    



protected void btnNewEntry_Click(object sender, EventArgs e)
 {
    Response.Redirect("CMS_1.aspx");
 }

And if u wanna do the this via client side scripting Use this way

<asp:Button ID="BTN" runat="server" Text="Submit" OnClientClick="window.open('Default2.aspx')" />

According to me you should prefer the Client Side Scripting because just to open a new window server side will take a post back and that will be useless..

OperationalError, no such column. Django

In my case, in admin.py I was querying from the table in which new ForeignKey field was added. So comment out admin.py then run makemigrations and migrate command as usual. Finally uncomment admin.py.

What is default color for text in textview?

I found that android:textColor="@android:color/secondary_text_dark" provides a closer result to the default TextView color than android:textColor="@android:color/tab_indicator_text". I suppose you have to switch between secondary_text_dark/light depending on the Theme you are using

Post to another page within a PHP script

For those using cURL, note that CURLOPT_POST option is taken as a boolean value, so there's actually no need to set it to the number of fields you are POSTing.
Setting CURLOPT_POST to TRUE (i.e. any integer except zero) will just tell cURL to encode the data as application/x-www-form-urlencoded, although I bet this is not strictly necessary when you're passing a urlencoded string as CURLOPT_POSTFIELDS, since cURL should already tell the encoding by the type of the value (string vs array) which this latter option is set to.

Also note that, since PHP 5, you can use the http_build_query function to make PHP urlencode the fields array for you, like this:

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));

Can I obtain method parameter name using Java reflection?

Parameter names are only useful to the compiler. When the compiler generates a class file, the parameter names are not included - a method's argument list only consists of the number and types of its arguments. So it would be impossible to retrieve the parameter name using reflection (as tagged in your question) - it doesn't exist anywhere.

However, if the use of reflection is not a hard requirement, you can retrieve this information directly from the source code (assuming you have it).

How to get an absolute file path in Python

>>> import os
>>> os.path.abspath("mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'

Also works if it is already an absolute path:

>>> import os
>>> os.path.abspath("C:/example/cwd/mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'

Get free disk space

this works for me...

using System.IO;

private long GetTotalFreeSpace(string driveName)
{
    foreach (DriveInfo drive in DriveInfo.GetDrives())
    {
        if (drive.IsReady && drive.Name == driveName)
        {
            return drive.TotalFreeSpace;
        }
    }
    return -1;
}

good luck!

How to list AD group membership for AD users using input list?

The below code will return username group membership using the samaccountname. You can modify it to get input from a file or change the query to get accounts with non expiring passwords etc

$location = "c:\temp\Peace2.txt"
$users = (get-aduser -filter *).samaccountname
$le = $users.length
for($i = 0; $i -lt $le; $i++){
  $output = (get-aduser $users[$i] | Get-ADPrincipalGroupMembership).name
  $users[$i] + " " + $output 
  $z =  $users[$i] + " " + $output 
  add-content $location $z
}

Sample Output:

Administrator Domain Users Administrators Schema Admins Enterprise Admins Domain Admins Group Policy Creator Owners
Guest Domain Guests Guests
krbtgt Domain Users Denied RODC Password Replication Group
Redacted Domain Users CompanyUsers Production
Redacted Domain Users CompanyUsers Production
Redacted Domain Users CompanyUsers Production

How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

This code makes json my default and allows me to use the XML format as well. I'll just append the xml=true.

GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("xml", "true", "application/xml"));
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

Thanks everyone!

What size should apple-touch-icon.png be for iPad and iPhone?

Yes. If the size does not match, the system will rescale it. But it's better to make 2 versions of the icons.

  • iPad — 72x72.
  • iPhone (=4) — 114x114.
  • iPhone =3GS — 57x57 — If possible.

You could differentiate iPad and iPhone by the user agent on your server. If you don't want to write script on server, you could also change the icon with Javascript by

<link ref="apple-touch-icon" href="iPhone_version.png" />
...

if (... iPad test ...) {
  $('link[rel="apple-touch-icon"]').href = 'iPad_version.png'; // assuming jQuery
}

This works because the icon is queried only when you add the web clip.

(There's no public way to differentiate iPhone =4 from iPhone =3GS in Javascript yet.)

Video 100% width and height

I am new into all of this. Maybe you can just add/change this HTML code. Without need for CSS. It worked for me :)

width="100%" height="height"

What does [object Object] mean?

[object Object] is the default toString representation of an object in javascript.

If you want to know the properties of your object, just foreach over it like this:

for(var property in obj) {
    alert(property + "=" + obj[property]);
}

In your particular case, you are getting a jQuery object. Try doing this instead:

$('#senddvd').click(function ()
{
   alert('hello');
   var a=whichIsVisible();
   alert(whichIsVisible().attr("id"));
});

This should alert the id of the visible element.

What port is a given program using?

You can use the 'netstat' command for this. There's a description of doing this sort of thing here.

Add custom headers to WebView resource requests - android

You can use this:

@Override

 public boolean shouldOverrideUrlLoading(WebView view, String url) {

                // Here put your code
                Map<String, String> map = new HashMap<String, String>();
                map.put("Content-Type","application/json");
                view.loadUrl(url, map);
                return false;

            }

jQuery "blinking highlight" effect on div?

Since I don't see any jQuery based solutions that don't require extra libraries here is a simple one that is a bit more flexible than those using fadeIn/fadeOut.

$.fn.blink = function (count) {
    var $this = $(this);

    count = count - 1 || 0;

    $this.animate({opacity: .25}, 100, function () {
        $this.animate({opacity: 1}, 100, function () {
            if (count > 0) {
                $this.blink(count);
            }
        });
    });
};

Use it like this

$('#element').blink(3); // 3 Times.

How to restore PostgreSQL dump file into Postgres databases?

I find that psql.exe is quite picky with the slash direction, at least on windows (which the above looks like).

Here's an example. In a cmd window:

C:\Program Files\PostgreSQL\9.2\bin>psql.exe -U postgres
psql (9.2.4)
Type "help" for help.

postgres=# \i c:\temp\try1.sql    
c:: Permission denied
postgres=# \i c:/temp/try1.sql
CREATE TABLE
postgres=#

You can see it fails when I use "normal" windows slashes in a \i call. However both slash styles work if you pass them as input params to psql.exe, for example:

C:\Program Files\PostgreSQL\9.2\bin>psql.exe -U postgres -f c:\TEMP\try1.sql
CREATE TABLE

C:\Program Files\PostgreSQL\9.2\bin>psql.exe -U postgres -f c:/TEMP/try1.sql
CREATE TABLE

C:\Program Files\PostgreSQL\9.2\bin>

Is there a regular expression to detect a valid regular expression?

Good question.

True regular languages can not decide arbitrarily deeply nested well-formed parenthesis. If your alphabet contains '(' and ')' the goal is to decide if a string of these has well-formed matching parenthesis. Since this is a necessary requirement for regular expressions the answer is no.

However, if you loosen the requirement and add recursion you can probably do it. The reason is that the recursion can act as a stack letting you "count" the current nesting depth by pushing onto this stack.

Russ Cox wrote "Regular Expression Matching Can Be Simple And Fast" which is a wonderful treatise on regex engine implementation.

Check if a radio button is checked jquery

Something like this:

 $("input[name=test]").is(":checked");

Using the jQuery is() function should work.

UTF-8 output from PowerShell

Set the [Console]::OuputEncoding as encoding whatever you want, and print out with [Console]::WriteLine.

If powershell ouput method has a problem, then don't use it. It feels bit bad, but works like a charm :)

"Failed to load platform plugin "xcb" " while launching qt5 app on linux without qt installed

Since version 5, Qt uses a platform abstraction system (QPA) to abstract from the underlying platform.

The implementation for each platform is provided by plugins. For X11 it is the XCB plugin. See Qt for X11 requirements for more information about the dependencies.

Truncate Two decimal places without rounding

One issue with the other examples is they multiply the input value before dividing it. There is an edge case here that you can overflow decimal by multiplying first, an edge case, but something I have come across. It's safer to deal with the fractional part separately as follows:

    public static decimal TruncateDecimal(this decimal value, int decimalPlaces)
    {
        decimal integralValue = Math.Truncate(value);

        decimal fraction = value - integralValue;

        decimal factor = (decimal)Math.Pow(10, decimalPlaces);

        decimal truncatedFraction = Math.Truncate(fraction * factor) / factor;

        decimal result = integralValue + truncatedFraction;

        return result;
    }

Why does HTML think “chucknorris” is a color?

The browser is trying to convert chucknorris into hex colour code, because it’s not a valid value.

  1. In chucknorris, everything except c is not a valid hex value.
  2. So it gets converted to c00c00000000.
  3. Which becomes #c00000, a shade of red.

This seems to be an issue primarily with Internet Explorer and Opera (12) as both Chrome (31) and Firefox (26) just ignore this.

P.S. The numbers in brackets are the browser versions I tested on.

On a lighter note

Chuck Norris doesn’t conform to web standards. Web standards conform to him. #BADA55

npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY

A quick solution from the internet search was npm config set strict-ssl false, luckily it worked. But as a part of my work environment, I am restricted to set the strict-ssl flag to false.

Later I found a safe and working solution,

npm config set registry http://registry.npmjs.org/  

this worked perfectly and I got a success message Happy Hacking! by not setting the strict-ssl flag to false.

How to see if an object is an array without using reflection?

You can create a utility class to check if the class represents any Collection, Map or Array

  public static boolean isCollection(Class<?> rawPropertyType) {
        return Collection.class.isAssignableFrom(rawPropertyType) || 
               Map.class.isAssignableFrom(rawPropertyType) || 
               rawPropertyType.isArray();
 }

DateTimePicker time picker in 24 hour but displaying in 12hr?

Meridian pertains to AM/PM, by setting it to false you're indicating you don't want AM/PM, therefore you want 24-hour clock implicitly.

$('#timepicker1').timepicker({showMeridian:false});

Check an integer value is Null in c#

Nullable<T> (or ?) exposes a HasValue flag to denote if a value is set or the item is null.

Also, nullable types support ==:

if (Age == null)

The ?? is the null coalescing operator and doesn't result in a boolean expression, but a value returned:

int i = Age ?? 0;

So for your example:

if (age == null || age == 0)

Or:

if (age.GetValueOrDefault(0) == 0)

Or:

if ((age ?? 0) == 0)

Or ternary:

int i = age.HasValue ? age.Value : 0;

How do I fix a NoSuchMethodError?

I have just solved this error by restarting my Eclipse and run the applcation. The reason for my case may because I replace my source files without closing my project or Eclipse. Which caused different version of classes I was using.

Login failed for user 'DOMAIN\MACHINENAME$'

NETWORK SERVICE and LocalSystem will authenticate themselves always as the correpsonding account locally (builtin\network service and builtin\system) but both will authenticate as the machine account remotely.

If you see a failure like Login failed for user 'DOMAIN\MACHINENAME$' it means that a process running as NETWORK SERVICE or as LocalSystem has accessed a remote resource, has authenticated itself as the machine account and was denied authorization.

Typical example would be an ASP application running in an app pool set to use NETWORK SERVICE credential and connecting to a remote SQL Server: the app pool will authenticate as the machine running the app pool, and is this machine account that needs to be granted access.

When access is denied to a machine account, then access must be granted to the machine account. If the server refuses to login 'DOMAIN\MACHINE$', then you must grant login rights to 'DOMAIN\MACHINE$' not to NETWORK SERVICE. Granting access to NETWORK SERVICE would allow a local process running as NETWORK SERVICE to connect, not a remote one, since the remote one will authenticate as, you guessed, DOMAIN\MACHINE$.

If you expect the asp application to connect to the remote SQL Server as a SQL login and you get exceptions about DOMAIN\MACHINE$ it means you use Integrated Security in the connection string. If this is unexpected, it means you screwed up the connection strings you use.

Deprecated: mysql_connect()

You can remove the warning by adding a '@' before the mysql_connect.

@mysql_connect('localhost','root','');

but as the warning is telling you, use mysqli or PDO since the mysql extension will be removed in the future.

Shrinking navigation bar when scrolling down (bootstrap3)

For those not willing to use jQuery here is a Vanilla Javascript way of doing the same using classList:

function runOnScroll() {
    var element = document.getElementsByTagName('nav')  ;
    if(document.body.scrollTop >= 50) {
        element[0].classList.add('shrink')
    } else {
        element[0].classList.remove('shrink')
    }
    console.log(topMenu[0].classList)

};

There might be a nicer way of doing it using toggle, but the above works fine in Chrome

How to change the date format from MM/DD/YYYY to YYYY-MM-DD in PL/SQL?

if you need to change your column output date format just use to_char this well get you a string, not a date.

How should I multiple insert multiple records?

If I were you I would not use either of them.

The disadvantage of the first one is that the parameter names might collide if there are same values in the list.

The disadvantage of the second one is that you are creating command and parameters for each entity.

The best way is to have the command text and parameters constructed once (use Parameters.Add to add the parameters) change their values in the loop and execute the command. That way the statement will be prepared only once. You should also open the connection before you start the loop and close it after it.

How many characters can you store with 1 byte?

The syntax of TINYINT data type is TINYINT(M),

where M indicates the maximum display width (used only if your MySQL client supports it).

The (m) indicates the column width in SELECT statements; however, it doesn't control the accepted range of numbers for that field.

A TINYINT is an 8-bit integer value, a BIT field can store between 1 bit, BIT(1), and 64 >bits, BIT(64). For a boolean values, BIT(1) is pretty common.

TINYINT()

Visual Studio 2017 errors on standard headers

This problem may also happen if you have a unit test project that has a different C++ version than the project you want to test.

Example:

  • EXE with C++ 17 enabled explicitly
  • Unit Test with C++ version set to "Default"

Solution: change the Unit Test to C++17 as well.

Screenshot

Disable resizing of a Windows Forms form

More precisely, add the code below to the private void InitializeComponent() method of the Form class:

this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;

Entity Framework Code First - two Foreign Keys from same table

I know it's a several years old post and you may solve your problem with above solution. However, i just want to suggest using InverseProperty for someone who still need. At least you don't need to change anything in OnModelCreating.

The below code is un-tested.

public class Team
{
    [Key]
    public int TeamId { get; set;} 
    public string Name { get; set; }

    [InverseProperty("HomeTeam")]
    public virtual ICollection<Match> HomeMatches { get; set; }

    [InverseProperty("GuestTeam")]
    public virtual ICollection<Match> GuestMatches { get; set; }
}


public class Match
{
    [Key]
    public int MatchId { get; set; }

    public float HomePoints { get; set; }
    public float GuestPoints { get; set; }
    public DateTime Date { get; set; }

    public virtual Team HomeTeam { get; set; }
    public virtual Team GuestTeam { get; set; }
}

You can read more about InverseProperty on MSDN: https://msdn.microsoft.com/en-us/data/jj591583?f=255&MSPPError=-2147217396#Relationships

Import Android volley to Android Studio

In the "build.gradle" for your app, (the app, not the project), add this:

dependencies {
    ...
    implementation 'com.android.volley:volley:1.1.0'
}

Can I read the hash portion of the URL on my server-side application (PHP, Ruby, Python, etc.)?

It is retrievable from Javascript - as window.location.hash. From there you could send it to the server with Ajax for example, or encode it and put it into URLs which can then be passed through to the server-side.

How to get the current URL within a Django template?

You can get the url without parameters by using {{request.path}} You can get the url with parameters by using {{request.get_full_path}}

HttpServletRequest - Get query string parameters, no form data

Java 8

return Collections.list(httpServletRequest.getParameterNames())
                  .stream()
                  .collect(Collectors.toMap(parameterName -> parameterName, httpServletRequest::getParameterValues));

'uint32_t' does not name a type

I had tha same problem trying to compile a lib I download from the internet. In my case, there was already a #include <cstdint> in the code. I solved it adding a:

using std::uint32_t;

JavaScript, get date of the next day

Using Date object guarantees that. For eg if you try to create April 31st :

new Date(2014,3,31)        // Thu May 01 2014 00:00:00

Please note that it's zero indexed, so Jan. is 0, Feb. is 1 etc.

How to set 'X-Frame-Options' on iframe?

not really... I used

 <system.webServer>
     <httpProtocol allowKeepAlive="true" >
       <customHeaders>
         <add name="X-Frame-Options" value="*" />
       </customHeaders>
     </httpProtocol>
 </system.webServer>

Haskell: Converting Int to String

The opposite of read is show.

Prelude> show 3
"3"

Prelude> read $ show 3 :: Int
3

How to change the size of the font of a JLabel to take the maximum size

JLabel label = new JLabel("Hello World");
label.setFont(new Font("Calibri", Font.BOLD, 20));

What is the return value of os.system() in Python?

os.system() returns some unix output, not the command output. So, if there is no error then exit code written as 0.

Removing carriage return and new-line from the end of a string in c#

If there's always a single CRLF, then:

myString = myString.Substring(0, myString.Length - 2);

If it may or may not have it, then:

Regex re = new Regex("\r\n$");
re.Replace(myString, "");

Both of these (by design), will remove at most a single CRLF. Cache the regex for performance.

How to watch and reload ts-node when TypeScript files change

I would prefer to not use ts-node and always run from dist folder.

To do that, just setup your package.json with default config:

....
"main": "dist/server.js",
  "scripts": {
    "build": "tsc",
    "prestart": "npm run build",
    "start": "node .",
    "dev": "nodemon"
  },
....

and then add nodemon.json config file:

{
  "watch": ["src"],
  "ext": "ts",
  "ignore": ["src/**/*.spec.ts"],
  "exec": "npm restart"
}

Here, i use "exec": "npm restart"
so all ts file will re-compile to js file and then restart the server.

To run while in dev environment,

npm run dev

Using this setup I will always run from the distributed files and no need for ts-node.

Is it possible to implement a Python for range loop without an iterator variable?

You may be looking for

for _ in itertools.repeat(None, times): ...

this is THE fastest way to iterate times times in Python.

Running .sh scripts in Git Bash

If you wish to execute a script file from the git bash prompt on Windows, just precede the script file with sh

sh my_awesome_script.sh

What's the right way to decode a string that has special HTML entities in it?

Don’t use the DOM to do this. Using the DOM to decode HTML entities (as suggested in the currently accepted answer) leads to differences in cross-browser results.

For a robust & deterministic solution that decodes character references according to the algorithm in the HTML Standard, use the he library. From its README:

he (for “HTML entities”) is a robust HTML entity encoder/decoder written in JavaScript. It supports all standardized named character references as per HTML, handles ambiguous ampersands and other edge cases just like a browser would, has an extensive test suite, and — contrary to many other JavaScript solutions — he handles astral Unicode symbols just fine. An online demo is available.

Here’s how you’d use it:

he.decode("We&#39;re unable to complete your request at this time.");
? "We're unable to complete your request at this time."

Disclaimer: I'm the author of the he library.

See this Stack Overflow answer for some more info.

Compare two Lists for differences

I think you're looking for a method like this:

public static IEnumerable<TResult> CompareSequences<T1, T2, TResult>(IEnumerable<T1> seq1,
    IEnumerable<T2> seq2, Func<T1, T2, TResult> comparer)
{
    var enum1 = seq1.GetEnumerator();
    var enum2 = seq2.GetEnumerator();

    while (enum1.MoveNext() && enum2.MoveNext())
    {
        yield return comparer(enum1.Current, enum2.Current);
    }
}

It's untested, but it should do the job nonetheless. Note that what's particularly useful about this method is that it's full generic, i.e. it can take two sequences of arbitrary (and different) types and return objects of any type.

This solution of course assumes that you want to compare the nth item of seq1 with the nth item in seq2. If you want to do match the elements in the two sequences based on a particular property/comparison, then you'll want to perform some sort of join operation (as suggested by danbruc using Enumerable.Join. Do let me know if it neither of these approaches is quite what I'm after and maybe I can suggest something else.

Edit: Here's an example of how you might use the CompareSequences method with the comparer function you originally posted.

// Prints out to the console all the results returned by the comparer function (CompareTwoClass_ReturnDifferences in this case).
var results = CompareSequences(list1, list2, CompareTwoClass_ReturnDifferences);
int index;    

foreach(var element in results)
{
    Console.WriteLine("{0:#000} {1}", index++, element.ToString());
}

URL for public Amazon S3 bucket

The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.


Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.


If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/ is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/ or http://s3-external-1.amazonaws.com/bucket/

The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].

S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.

If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.

However... the two endpoints do not offer the same functionality.

Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.

Choose the correct type of endpoint (REST or web site) for your application:

http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff


¹ s3-external-1.amazonaws.com has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2 had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1 so s3-external-2 appears to have no purpose except backwards-compatibility.

<meta charset="utf-8"> vs <meta http-equiv="Content-Type">

Another reason to go with the short one is that it matches other instances where you might specify a character set in markup. For example:

<script type="javascript" charset="UTF-8" src="/script.js"></script>

<p><a charset="UTF-8" href="http://example.com/">Example Site</a></p>

Consistency helps to reduce errors and make code more readable.

Note that the charset attribute is case-insensitive. You can use UTF-8 or utf-8, however UTF-8 is clearer, more readable, more accurate.

Also, there is absolutely no reason at all to use any value other than UTF-8 in the meta charset attribute or page header. UTF-8 is the default encoding for Web documents since HTML4 in 1999 and the only practical way to make modern Web pages.

Also you should not use HTML entities in UTF-8. Characters like the copyright symbol should be typed directly. The only entities you should use are for the 5 reserved markup characters: less than, greater than, ampersand, prime, double prime. Entities need an HTML parser, which you may not always want to use going forward, they introduce errors, make your code less readable, increase your file sizes, and sometimes decode incorrectly in various browsers depending on which entities you used. Learn how to type/insert copyright, trademark, open quote, close quote, apostrophe, em dash, en dash, bullet, Euro, and any other characters you encounter in your content, and use those actual characters in your code. The Mac has a Character Viewer that you can turn on in the Keyboard System Preference, and you can find and then drag and drop the characters you need, or use the matching Keyboard Viewer to see which keys to type. For example, trademark is Option+2. UTF-8 contains all of the characters and symbols from every written human language. So there is no excuse for using -- instead of an em dash. It is not a bad idea to learn the rules of punctuation and typography also ... for example, knowing that a period goes inside a close quote, not outside.

Using a tag for something like content-type and encoding is highly ironic, since without knowing those things, you couldn't parse the file to get the value of the meta tag.

No, that is not true. The browser starts out parsing the file as the browser's default encoding, either UTF-8 or ISO-8859-1. Since US-ASCII is a subset of both ISO-8859-1 and UTF-8, the browser can read just fine either way ... it is the same. When the browser encounters the meta charset tag, if the encoding is different than what the browser is already using, the browser reloads the page in the specified encoding. That is why we put the meta charset tag at the top, right after the head tag, before anything else, even the title. That way you can use UTF-8 characters in your title.

You must save your file(s) in UTF-8 encoding without BOM

That is not strictly true. If you only have US-ASCII characters in your document, you can Save it as US-ASCII and serve it as UTF-8, because it is a subset. But if there are Unicode characters, you are correct, you must Save as UTF-8 without BOM.

If you want a good text editor that will save your files in UTF-8, I recommend Notepad++.

On the Mac, use Bare Bones TextWrangler (free) from Mac App Store, or Bare Bones BBEdit which is at Mac App Store for $39.99 ... very cheap for such a great tool. In either app, there is a menu at the bottom of the document window where you specify the document encoding and you can easily choose "UTF-8 no BOM". And of course you can set that as the default for new documents in Preferences.

But if your Webserver serves the encoding in the HTTP header, which is recommended, both [meta tags] are needless.

That is incorrect. You should of course set the encoding in the HTTP header, but you should also set it in the meta charset attribute so that the page can be Saved by the user, out of the browser onto local storage and then Opened again later, in which case the only indication of the encoding that will be present is the meta charset attribute. You should also set a base tag for the same reason ... on the server, the base tag is unnecessary, but when opened from local storage, the base tag enables the page to work as if it is on the server, with all the assets in place and so on, no broken links.

AddDefaultCharset UTF-8

Or you can just change the encoding of particular file types like so:

AddType text/html;charset=utf-8 html

A tip for serving both UTF-8 and Latin-1 (ISO-8859-1) files is to give the UTF-8 files a "text" extension and Latin-1 files "txt."

AddType text/plain;charset=iso-8859-1 txt
AddType text/plain;charset=utf-8 text

Finally, consider Saving your documents with Unix line endings, not legacy DOS or (classic) Mac line endings, which don't help and may hurt, especially down the line as we get further and further from those legacy systems. An HTML document with valid HTML5, UTF-8 encoding, and Unix line endings is a job well done. You can share and edit and store and read and recover and rely on that document in many contexts. It's lingua franca. It's digital paper.

Eclipse copy/paste entire line keyboard shortcut

You have to turn off the graphics hot keys that flip the screen. If you're on Windows, you need to right click on the Windows desktop and select "Graphics Properties..." (or something similar depending on your version of Windows). This will bring up a screen where you can manage graphics and display options, look for a place where you can disable hot keys, sometimes it's hidden under something like "Options and Support". Turn off the CTRL + ALT + ? and CTRL + ALT + ? hotkeys (alternatively you can just disable all graphics hot keys if you're not using them).

React.js inline style best practices

Some time we require to style some element from a component but if we have to display that component only ones or the style is so less then instead of using the CSS class we go for the inline style in react js. reactjs inline style is as same as HTML inline style just the property names are a little bit different

Write your style in any tag using style={{prop:"value"}}

import React, { Component } from "react";
    import { Redirect } from "react-router";

    class InlineStyle extends Component {
      constructor(props) {
        super(props);
        this.state = {};
      }

      render() {
        return (
          <div>
            <div>
              <div
                style={{
                  color: "red",
                  fontSize: 40,
                  background: "green"
                }}// this is inline style in reactjs
              >

              </div>
            </div>
          </div>
        );
      }
    }
    export default InlineStyle;

Convert generic list to dataset in C#

I have slightly modified the accepted answer by handling value types. I came across this when trying to do the following and because GetProperties() is zero length for value types I was getting an empty dataset. I know this is not the use case for the OP but thought I'd post this change in case anyone else came across the same thing.

Enumerable.Range(1, 10).ToList().ToDataSet();

public static DataSet ToDataSet<T>(this IList<T> list)
{
    var elementType = typeof(T);
    var ds = new DataSet();
    var t = new DataTable();
    ds.Tables.Add(t);

    if (elementType.IsValueType)
    {
        var colType = Nullable.GetUnderlyingType(elementType) ?? elementType;
        t.Columns.Add(elementType.Name, colType);

    } else
    {
        //add a column to table for each public property on T
        foreach (var propInfo in elementType.GetProperties())
        {
            var colType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;
            t.Columns.Add(propInfo.Name, colType);
        }
    }

    //go through each property on T and add each value to the table
    foreach (var item in list)
    {
        var row = t.NewRow();

        if (elementType.IsValueType)
        {
            row[elementType.Name] = item;
        }
        else
        {
            foreach (var propInfo in elementType.GetProperties())
            {
                row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
            }
        }
        t.Rows.Add(row);
    }

    return ds;
}

Android AlertDialog Single Button

Kotlin?

  val dialogBuilder = AlertDialog.Builder(this.context)
  dialogBuilder.setTitle("Alert")
               .setMessage(message)
               .setPositiveButton("OK", null)
               .create()
               .show()

Should I Dispose() DataSet and DataTable?

No need to Dispose() because DataSet inherit MarshalByValueComponent class and MarshalByValueComponent implement IDisposable Interface

Tomcat is not running even though JAVA_HOME path is correct

I had similar problem and please note that we need not set JAVA_HOME unless we are going to use debug mode. tomcat in windows 7 can handle spaces in environment variables the problem is because of "bin" in the path. setting JRE_HOME to C:\Program Files (x86)\Java\jre1.8.0_65 solved my problem and tomcat is up and running without any trouble

How to change the buttons text using javascript

You can toggle filterstatus value like this

filterstatus ^= 1;

So your function looks like

function showFilterItem(objButton) {
if (filterstatus == 0) {
    $find('<%=FileAdminRadGrid.ClientID %>').get_masterTableView().showFilterItem();
    objButton.value = "Hide Filter";
}
else {
    $find('<%=FileAdminRadGrid.ClientID %>').get_masterTableView().hideFilterItem();
    objButton.value = "Show filter";
}
  filterstatus ^= 1;    
}

Is it possible to make input fields read-only through CSS?

CSS based input text readonly change color of selection:

CSS:

/**default page CSS:**/
::selection { background: #d1d0c3; color: #393729; }
*::-moz-selection { background: #d1d0c3; color: #393729; }

/**for readonly input**/
input[readonly='readonly']:focus { border-color: #ced4da; box-shadow: none; }
input[readonly='readonly']::selection { background: none; color: #000; }
input[readonly='readonly']::-moz-selection { background: none; color: #000; }

HTML:

<input type="text" value="12345" id="readCaptch" readonly="readonly" class="form-control" />

live Example: https://codepen.io/alpesh88ww/pen/mdyZBmV

also you can see why i was done!! (php captcha): https://codepen.io/alpesh88ww/pen/PoYeZVQ

Vertical (rotated) text in HTML table

Have a look at this, i found this while looking for a solution for IE 7.

totally a cool solution for css only vibes

Thanks aiboy for the soultion

heres the link

and here is the stack-overflow link where i came across this link meow

         .vertical-text-vibes{

                /* this is for shity "non IE" browsers
                   that dosn't support writing-mode */
                -webkit-transform: translate(1.1em,0) rotate(90deg);
                   -moz-transform: translate(1.1em,0) rotate(90deg);
                     -o-transform: translate(1.1em,0) rotate(90deg);
                        transform: translate(1.1em,0) rotate(90deg);
                -webkit-transform-origin: 0 0;
                   -moz-transform-origin: 0 0;
                     -o-transform-origin: 0 0;
                        transform-origin: 0 0;  
             /* IE9+ */    ms-transform: none;    
                   -ms-transform-origin: none;    
        /* IE8+ */    -ms-writing-mode: tb-rl;    
   /* IE7 and below */    *writing-mode: tb-rl;

            }

Modelling an elevator using Object-Oriented Analysis and Design

Main thing to worry about is how would you notify the elevator that it needs to move up or down. and also if you are going to have a centralized class to control this behavior and how could you distribute the control.

It seems like it can be very simple or very complicated. If we don't take concurrency or the time for an elevator to get to one place, then it seems like it will be simple since we just need to check the states of elevator, like is it moving up or down, or standing still. But if we make Elevator implement Runnable, and constantly check and synchronize a queue (linkedList). A Controller class will assign which floor to go in the queue. When the queue is empty, the run() method will wait (queue.wait() ), when a floor is assigned to this elevator, it will call queue.notify() to wake up the run() method, and run() method will call goToFloor(queue.pop()). This will make the problem too complicated. I tried to write it on paper, but dont think it works. It seems like we don't really need to take concurrency or timing issue into account here, but we do need to somehow use a queue to distribute the control.

Any suggestion?

How can I avoid Java code in JSP files, using JSP 2?

If we use the following things in a Java web application, Java code can be eliminated from the foreground of the JSP file.

  1. Use the MVC architecture for a web application

  2. Use JSP Tags

a. Standard Tags

b. Custom Tags

  1. Expression Language

How to check Elasticsearch cluster health?

If Elasticsearch cluster is not accessible (e.g. behind firewall), but Kibana is:

Kibana => DevTools => Console:

GET /_cluster/health 

enter image description here enter image description here

Open mvc view in new window from controller

I've seen where you can do something like this, assuming "NewWindow.cshtml" is in your "Home" folder:

string url = "/Home/NewWindow";
return JavaScript(string.Format("window.open('{0}', '_blank', 'left=100,top=100,width=500,height=500,toolbar=no,resizable=no,scrollable=yes');", url));

or

return Content("/Home/NewWindow");

If you just want to open views in tabs, you could use JavaScript click events to render your partial views. This would be your controller method for NewWindow.cshtml:

public ActionResult DisplayNewWindow(NewWindowModel nwm) {
    // build model list based on its properties & values
    nwm.Name = "John Doe";
    nwm.Address = "123 Main Street";
    return PartialView("NewWindow", nwm);
}

Your markup on your page this is calling it would go like this:

<input type="button" id="btnNewWin" value="Open Window" />
<div id="newWinResults" />

And the JavaScript (requires jQuery):

var url = '@Url.Action("NewWindow", "Home")';
$('btnNewWin').on('click', function() {
    var model = "{ 'Name': 'Jane Doe', 'Address': '555 Main Street' }"; // you must build your JSON you intend to pass into the "NewWindowModel" manually
    $('#newWinResults').load(url, model); // may need to do JSON.stringify(model)
});

Note that this JSON would overwrite what is in that C# function above. I had it there for demonstration purposes on how you could hard-code values, only.

(Adapted from Rendering partial view on button click in ASP.NET MVC)

Connect different Windows User in SQL Server Management Studio (2005 or later)

A bit of powershell magic will do the trick:

cmdkey /add:"SERVER:1433" /user:"DOMAIN\USERNAME" /pass:"PASSWORD"

Then just select windows authentication

Java FileReader encoding issue

FileReader uses Java's platform default encoding, which depends on the system settings of the computer it's running on and is generally the most popular encoding among users in that locale.

If this "best guess" is not correct then you have to specify the encoding explicitly. Unfortunately, FileReader does not allow this (major oversight in the API). Instead, you have to use new InputStreamReader(new FileInputStream(filePath), encoding) and ideally get the encoding from metadata about the file.

How do I pass multiple parameters into a function in PowerShell?

If you try:

PS > Test("ABC", "GHI") ("DEF")

you get:

$arg1 value: ABC GHI
$arg2 value: DEF

So you see that the parentheses separates the parameters


If you try:

PS > $var = "C"
PS > Test ("AB" + $var) "DEF"

you get:

$arg1 value: ABC
$arg2 value: DEF

Now you could find some immediate usefulness of the parentheses - a space will not become a separator for the next parameter - instead you have an eval function.

How to setup FTP on xampp

I launched ubuntu Xampp server on AWS amazon. And met the same problem with FTP, even though add user to group ftp SFTP and set permissions, owner group of htdocs folder. Finally find the reason in inbound rules in security group, added All TCP, 0 - 65535 rule(0.0.0.0/0,::/0) , then working right!

Get path to execution directory of Windows Forms application

Application.Current results in an appdomain http://msdn.microsoft.com/en-us/library/system.appdomain_members.aspx

Also this should give you the location of the assembly

AppDomain.CurrentDomain.BaseDirectory

I seem to recall there being multiple ways of getting the location of the application. but this one worked for me in the past atleast (it's been a while since i've done winforms programming :/)

Django values_list vs values

The best place to understand the difference is at the official documentation on values / values_list. It has many useful examples and explains it very clearly. The django docs are very user freindly.

Here's a short snippet to keep SO reviewers happy:

values

Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.

And read the section which follows it:

value_list

This is similar to values() except that instead of returning dictionaries, it returns tuples when iterated over.

draw diagonal lines in div background with CSS

you can use a CSS3 transform Property:

div
{
transform:rotate(Xdeg);
-ms-transform:rotate(Xdeg); /* IE 9 */
-webkit-transform:rotate(Xdeg); /* Safari and Chrome */
}

Xdeg = your value

For example...

You can make more div and use a z-index property. So,make a div with line, and rotate it.

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

I would point you to Wikipedia:

A few points:

  • Symlinks, unlike hard links, can cross filesystems (most of the time).
  • Symlinks can point to directories.
  • Hard links point to a file and enable you to refer to the same file with more than one name.
  • As long as there is at least one link, the data is still available.

Circle drawing with SVG's arc path

Building upon Anthony and Anton's answers I incorporated the ability to rotate the generated circle without affecting it's overall appearance. This is useful if you're using the path for an animation and you need to control where it begins.

function(cx, cy, r, deg){
    var theta = deg*Math.PI/180,
        dx = r*Math.cos(theta),
        dy = -r*Math.sin(theta);
    return "M "+cx+" "+cy+"m "+dx+","+dy+"a "+r+","+r+" 0 1,0 "+-2*dx+","+-2*dy+"a "+r+","+r+" 0 1,0 "+2*dx+","+2*dy;
}

How to use S_ISREG() and S_ISDIR() POSIX Macros?

You're using S_ISREG() and S_ISDIR() correctly, you're just using them on the wrong thing.

In your while((dit = readdir(dip)) != NULL) loop in main, you're calling stat on currentPath over and over again without changing currentPath:

if(stat(currentPath, &statbuf) == -1) {
    perror("stat");
    return errno;
}

Shouldn't you be appending a slash and dit->d_name to currentPath to get the full path to the file that you want to stat? Methinks that similar changes to your other stat calls are also needed.

Is it possible to Turn page programmatically in UIPageViewController?

Since I needed this as well, I'll go into more detail on how to do this.

Note: I assume you used the standard template form for generating your UIPageViewController structure - which has both the modelViewController and dataViewController created when you invoke it. If you don't understand what I wrote - go back and create a new project that uses the UIPageViewController as it's basis. You'll understand then.

So, needing to flip to a particular page involves setting up the various pieces of the method listed above. For this exercise, I'm assuming that it's a landscape view with two views showing. Also, I implemented this as an IBAction so that it could be done from a button press or what not - it's just as easy to make it selector call and pass in the items needed.

So, for this example you need the two view controllers that will be displayed - and optionally, whether you're going forward in the book or backwards.

Note that I merely hard-coded where to go to pages 4 & 5 and use a forward slip. From here you can see that all you need to do is pass in the variables that will help you get these items...

-(IBAction) flipToPage:(id)sender {

    // Grab the viewControllers at position 4 & 5 - note, your model is responsible for providing these.  
    // Technically, you could have them pre-made and passed in as an array containing the two items...

    DataViewController *firstViewController = [self.modelController viewControllerAtIndex:4 storyboard:self.storyboard];
    DataViewController *secondViewController = [self.modelController viewControllerAtIndex:5 storyboard:self.storyboard];

    //  Set up the array that holds these guys...

    NSArray *viewControllers = nil;

    viewControllers = [NSArray arrayWithObjects:firstViewController, secondViewController, nil];

    //  Now, tell the pageViewContoller to accept these guys and do the forward turn of the page.
    //  Again, forward is subjective - you could go backward.  Animation is optional but it's 
    //  a nice effect for your audience.

      [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL];

    //  Voila' - c'est fin!  

}

Discard all and get clean copy of latest revision?

hg status will show you all the new files, and then you can just rm them.

Normally I want to get rid of ignored and unversioned files, so:

hg status -iu                          # to show 
hg status -iun0 | xargs -r0 rm         # to destroy

And then follow that with:

hg update -C -r xxxxx

which puts all the versioned files in the right state for revision xxxx


To follow the Stack Overflow tradition of telling you that you don't want to do this, I often find that this "Nuclear Option" has destroyed stuff I care about.

The right way to do it is to have a 'make clean' option in your build process, and maybe a 'make reallyclean' and 'make distclean' too.

Create a List that contain each Line of a File

f.readlines() returns a list that contains each line as an item in the list

if you want eachline to be split(",") you can use list comprehensions

[ list.split(",") for line in file ]

What's the difference between window.location= and window.location.replace()?

TLDR;

use location.href or better use window.location.href;

However if you read this you will gain undeniable proof.

The truth is it's fine to use but why do things that are questionable. You should take the higher road and just do it the way that it probably should be done.

location = "#/mypath/otherside"
var sections = location.split('/')

This code is perfectly correct syntax-wise, logic wise, type-wise you know the only thing wrong with it?

it has location instead of location.href

what about this

var mystring = location = "#/some/spa/route"

what is the value of mystring? does anyone really know without doing some test. No one knows what exactly will happen here. Hell I just wrote this and I don't even know what it does. location is an object but I am assigning a string will it pass the string or pass the location object. Lets say there is some answer to how this should be implemented. Can you guarantee all browsers will do the same thing?

This i can pretty much guess all browsers will handle the same.

var mystring = location.href = "#/some/spa/route"

What about if you place this into typescript will it break because the type compiler will say this is suppose to be an object?

This conversation is so much deeper than just the location object however. What this conversion is about what kind of programmer you want to be?

If you take this short-cut, yea it might be okay today, ye it might be okay tomorrow, hell it might be okay forever, but you sir are now a bad programmer. It won't be okay for you and it will fail you.

There will be more objects. There will be new syntax.

You might define a getter that takes only a string but returns an object and the worst part is you will think you are doing something correct, you might think you are brilliant for this clever method because people here have shamefully led you astray.

var Person.name = {first:"John":last:"Doe"}
console.log(Person.name) // "John Doe"

With getters and setters this code would actually work, but just because it can be done doesn't mean it's 'WISE' to do so.

Most people who are programming love to program and love to get better. Over the last few years I have gotten quite good and learn a lot. The most important thing I know now especially when you write Libraries is consistency and predictability.

Do the things that you can consistently do.

+"2" <-- this right here parses the string to a number. should you use it? or should you use parseInt("2")?

what about var num =+"2"?

From what you have learn, from the minds of stackoverflow i am not too hopefully.

If you start following these 2 words consistent and predictable. You will know the right answer to a ton of questions on stackoverflow.

Let me show you how this pays off. Normally I place ; on every line of javascript i write. I know it's more expressive. I know it's more clear. I have followed my rules. One day i decided not to. Why? Because so many people are telling me that it is not needed anymore and JavaScript can do without it. So what i decided to do this. Now because I have become sure of my self as a programmer (as you should enjoy the fruit of mastering a language) i wrote something very simple and i didn't check it. I erased one comma and I didn't think I needed to re-test for such a simple thing as removing one comma.

I wrote something similar to this in es6 and babel

var a = "hello world"
(async function(){
  //do work
})()

This code fail and took forever to figure out. For some reason what it saw was

var a = "hello world"(async function(){})()

hidden deep within the source code it was telling me "hello world" is not a function.

For more fun node doesn't show the source maps of transpiled code.

Wasted so much stupid time. I was presenting to someone as well about how ES6 is brilliant and then I had to start debugging and demonstrate how headache free and better ES6 is. Not convincing is it.

I hope this answered your question. This being an old question it's more for the future generation, people who are still learning.

Question when people say it doesn't matter either way works. Chances are a wiser more experienced person will tell you other wise.

what if someone overwrite the location object. They will do a shim for older browsers. It will get some new feature that needs to be shimmed and your 3 year old code will fail.

My last note to ponder upon.

Writing clean, clear purposeful code does something for your code that can't be answer with right or wrong. What it does is it make your code an enabler.

You can use more things plugins, Libraries with out fear of interruption between the codes.

for the record. use

window.location.href

Get custom product attributes in Woocommerce

woocommerce_get_product_terms() is now deprecated.

Use wc_get_product_terms() instead.

Example:

global $product;
$koostis = array_shift( wc_get_product_terms( $product->id, 'pa_koostis', array( 'fields' => 'names' ) ) );

How to mock static methods in c# using MOQ framework?

As mentioned in the other answers MOQ cannot mock static methods and, as a general rule, one should avoid statics where possible.

Sometimes it is not possible. One is working with legacy or 3rd party code or with even with the BCL methods that are static.

A possible solution is to wrap the static in a proxy with an interface which can be mocked

    public interface IFileProxy {
        void Delete(string path);
    }

    public class FileProxy : IFileProxy {
        public void Delete(string path) {
            System.IO.File.Delete(path);
        }
    }

    public class MyClass {

        private IFileProxy _fileProxy;

        public MyClass(IFileProxy fileProxy) {
            _fileProxy = fileProxy;
        }

        public void DoSomethingAndDeleteFile(string path) {
            // Do Something with file
            // ...
            // Delete
            System.IO.File.Delete(path);
        }

        public void DoSomethingAndDeleteFileUsingProxy(string path) {
            // Do Something with file
            // ...
            // Delete
            _fileProxy.Delete(path);

        }
    }

The downside is that the ctor can become very cluttered if there are a lot of proxies (though it could be argued that if there are a lot of proxies then the class may be trying to do too much and could be refactored)

Another possibility is to have a 'static proxy' with different implementations of the interface behind it

   public static class FileServices {

        static FileServices() {
            Reset();
        }

        internal static IFileProxy FileProxy { private get; set; }

        public static void Reset(){
           FileProxy = new FileProxy();
        }

        public static void Delete(string path) {
            FileProxy.Delete(path);
        }

    }

Our method now becomes

    public void DoSomethingAndDeleteFileUsingStaticProxy(string path) {
            // Do Something with file
            // ...
            // Delete
            FileServices.Delete(path);

    }

For testing, we can set the FileProxy property to our mock. Using this style reduces the number of interfaces to be injected but makes dependencies a bit less obvious (though no more so than the original static calls I suppose).

Test if a string contains any of the strings from an array

Here is one solution :

public static boolean containsAny(String str, String[] words)
{
   boolean bResult=false; // will be set, if any of the words are found
   //String[] words = {"word1", "word2", "word3", "word4", "word5"};

   List<String> list = Arrays.asList(words);
   for (String word: list ) {
       boolean bFound = str.contains(word);
       if (bFound) {bResult=bFound; break;}
   }
   return bResult;
}

How can I get the key value in a JSON object?

Try out this

var str ="{ "name" : "user"}";
var jsonData = JSON.parse(str);     
console.log(jsonData.name)

//Array Object

str ="[{ "name" : "user"},{ "name" : "user2"}]";
jsonData = JSON.parse(str);     
console.log(jsonData[0].name)

React Native TextInput that only accepts numeric characters

Well, this is a very simple way to validate a number different to 0.

if (+inputNum)

It will be NaN if inputNum is not a number or false if it is 0

Hashset vs Treeset

HashSet implementations are, of course, much much faster -- less overhead because there's no ordering. A good analysis of the various Set implementations in Java is provided at http://java.sun.com/docs/books/tutorial/collections/implementations/set.html.

The discussion there also points out an interesting 'middle ground' approach to the Tree vs Hash question. Java provides a LinkedHashSet, which is a HashSet with an "insertion-oriented" linked list running through it, that is, the last element in the linked list is also the most recently inserted into the Hash. This allows you to avoid the unruliness of an unordered hash without incurring the increased cost of a TreeSet.

SSL: CERTIFICATE_VERIFY_FAILED with Python3

Go to the folder where Python is installed, e.g., in my case (Mac OS) it is installed in the Applications folder with the folder name 'Python 3.6'. Now double click on 'Install Certificates.command'. You will no longer face this error.

For those not running a mac, or having a different setup and can't find this file, the file merely runs:

pip install --upgrade certifi

Hope that helps someone :)

In Unix, how do you remove everything in the current directory and below it?

This simplest safe & general solution is probably:

find -mindepth 1 -maxdepth 1 -print0 | xargs -0 rm -rf

AttributeError: Module Pip has no attribute 'main'

First run

import pip
pip.__version__

If the result is '10.0.0', then it means that you installed pip successfully
since pip 10.0.0 doesn't support pip.main() any more, you may find this helpful
https://pip.pypa.io/en/latest/user_guide/#using-pip-from-your-program
Use something like import subprocess subprocess.check_call(["python", '-m', 'pip', 'install', 'pkg']) # install pkg subprocess.check_call(["python", '-m', 'pip', 'install',"--upgrade", 'pkg']) # upgrade pkg


Edit: pip 10.0.1 still doesn't support main
You can choose to DOWNGRADE your pip version via following command:
python -m pip install --upgrade pip==9.0.3

PHP multidimensional array search by value

function searchForId($id, $array) {
   foreach ($array as $key => $val) {
       if ($val['uid'] === $id) {
           return $key;
       }
   }
   return null;
}

This will work. You should call it like this:

$id = searchForId('100', $userdb);

It is important to know that if you are using === operator compared types have to be exactly same, in this example you have to search string or just use == instead ===.

Based on angoru answer. In later versions of PHP (>= 5.5.0) you can use one-liner.

$key = array_search('100', array_column($userdb, 'uid'));

Here is documentation: http://php.net/manual/en/function.array-column.php.

What is the use of the square brackets [] in sql statements?

Regardless of following a naming convention that avoids using reserved words, Microsoft does add new reserved words. Using brackets allows your code to be upgraded to a new SQL Server version, without first needing to edit Microsoft's newly reserved words out of your client code. That editing can be a significant concern. It may cause your project to be prematurely retired....

Brackets can also be useful when you want to Replace All in a script. If your batch contains a variable named @String and a column named [String], you can rename the column to [NewString], without renaming @String to @NewString.

Creating a JSON array in C#

new {var_data[counter] =new [] { 
                new{  "S NO":  "+ obj_Data_Row["F_ID_ITEM_MASTER"].ToString() +","PART NAME": " + obj_Data_Row["F_PART_NAME"].ToString() + ","PART ID": " + obj_Data_Row["F_PART_ID"].ToString() + ","PART CODE":" + obj_Data_Row["F_PART_CODE"].ToString() + ", "CIENT PART ID": " + obj_Data_Row["F_ID_CLIENT"].ToString() + ","TYPES":" + obj_Data_Row["F_TYPE"].ToString() + ","UOM":" + obj_Data_Row["F_UOM"].ToString() + ","SPECIFICATION":" + obj_Data_Row["F_SPECIFICATION"].ToString() + ","MODEL":" + obj_Data_Row["F_MODEL"].ToString() + ","LOCATION":" + obj_Data_Row["F_LOCATION"].ToString() + ","STD WEIGHT":" + obj_Data_Row["F_STD_WEIGHT"].ToString() + ","THICKNESS":" + obj_Data_Row["F_THICKNESS"].ToString() + ","WIDTH":" + obj_Data_Row["F_WIDTH"].ToString() + ","HEIGHT":" + obj_Data_Row["F_HEIGHT"].ToString() + ","STUFF QUALITY":" + obj_Data_Row["F_STUFF_QTY"].ToString() + ","FREIGHT":" + obj_Data_Row["F_FREIGHT"].ToString() + ","THRESHOLD FG":" + obj_Data_Row["F_THRESHOLD_FG"].ToString() + ","THRESHOLD CL STOCK":" + obj_Data_Row["F_THRESHOLD_CL_STOCK"].ToString() + ","DESCRIPTION":" + obj_Data_Row["F_DESCRIPTION"].ToString() + "}
        }
    };

How to concatenate string variables in Bash

I do it this way when convenient: Use an inline command!

echo "The current time is `date`"
echo "Current User: `echo $USER`"

Getting the client's time zone (and offset) in JavaScript

Using getTimezoneOffset()

You can get the time zone offset in minutes like this:

_x000D_
_x000D_
var offset = new Date().getTimezoneOffset();
console.log(offset);
// if offset equals -60 then the time zone offset is UTC+01
_x000D_
_x000D_
_x000D_

The time-zone offset is the difference, in minutes, between UTC and local time. Note that this means that the offset is positive if the local timezone is behind UTC and negative if it is ahead. For example, if your time zone is UTC+10 (Australian Eastern Standard Time), -600 will be returned. Daylight savings time prevents this value from being a constant even for a given locale

Note that not all timezones are offset by whole hours: for example, Newfoundland is UTC minus 3h 30m (leaving Daylight Saving Time out of the equation).

Please also note that this only gives you the time zone offset (eg: UTC+01), it does not give you the time zone (eg: Europe/London).

Read response body in JAX-RS client from a post request

I also had the same issue, trying to run a unit test calling code that uses readEntity. Can't use getEntity in production code because that just returns a ByteInputStream and not the content of the body and there is no way I am adding production code that is hit only in unit tests.

My solution was to create a response and then use a Mockito spy to mock out the readEntity method:

Response error = Response.serverError().build();
Response mockResponse = spy(error);
doReturn("{jsonbody}").when(mockResponse).readEntity(String.class);

Note that you can't use the when(mockResponse.readEntity(String.class) option because that throws the same IllegalStateException.

Hope this helps!

IOCTL Linux device driver

An ioctl, which means "input-output control" is a kind of device-specific system call. There are only a few system calls in Linux (300-400), which are not enough to express all the unique functions devices may have. So a driver can define an ioctl which allows a userspace application to send it orders. However, ioctls are not very flexible and tend to get a bit cluttered (dozens of "magic numbers" which just work... or not), and can also be insecure, as you pass a buffer into the kernel - bad handling can break things easily.

An alternative is the sysfs interface, where you set up a file under /sys/ and read/write that to get information from and to the driver. An example of how to set this up:

static ssize_t mydrvr_version_show(struct device *dev,
        struct device_attribute *attr, char *buf)
{
    return sprintf(buf, "%s\n", DRIVER_RELEASE);
}

static DEVICE_ATTR(version, S_IRUGO, mydrvr_version_show, NULL);

And during driver setup:

device_create_file(dev, &dev_attr_version);

You would then have a file for your device in /sys/, for example, /sys/block/myblk/version for a block driver.

Another method for heavier use is netlink, which is an IPC (inter-process communication) method to talk to your driver over a BSD socket interface. This is used, for example, by the WiFi drivers. You then communicate with it from userspace using the libnl or libnl3 libraries.

Concept behind putting wait(),notify() methods in Object class

I am just having hard time to understand concept behind putting wait() in object class For this questions sake consider as if wait() and notifyAll() are in thread class

In the Java language, you wait() on a particular instance of an Object – a monitor assigned to that object to be precise. If you want to send a signal to one thread that is waiting on that specific object instance then you call notify() on that object. If you want to send a signal to all threads that are waiting on that object instance, you use notifyAll() on that object.

If wait() and notify() were on the Thread instead then each thread would have to know the status of every other thread. How would thread1 know that thread2 was waiting for access to a particular resource? If thread1 needed to call thread2.notify() it would have to somehow find out that thread2 was waiting. There would need to be some mechanism for threads to register the resources or actions that they need so others could signal them when stuff was ready or available.

In Java, the object itself is the entity that is shared between threads which allows them to communicate with each other. The threads have no specific knowledge of each other and they can run asynchronously. They run and they lock, wait, and notify on the object that they want to get access to. They have no knowledge of other threads and don't need to know their status. They don't need to know that it is thread2 which is waiting for the resource – they just notify on the resource and whomever it is that is waiting (if anyone) will be notified.

In Java, we then use objects as synchronization, mutex, and communication points between threads. We synchronize on an object to get mutex access to an important code block and to synchronize memory. We wait on an object if we are waiting for some condition to change – some resource to become available. We notify on an object if we want to awaken sleeping threads.

// locks should be final objects so the object instance we are synchronizing on,
// never changes
private final Object lock = new Object();
...
// ensure that the thread has a mutex lock on some key code
synchronized (lock) {
    ...
    // i need to wait for other threads to finish with some resource
    // this releases the lock and waits on the associated monitor
    lock.wait();
    ...
    // i need to signal another thread that some state has changed and they can
    // awake and continue to run
    lock.notify();
}

There can be any number of lock objects in your program – each locking a particular resource or code segment. You might have 100 lock objects and only 4 threads. As the threads run the various parts of the program, they get exclusive access to one of the lock objects. Again, they don't have to know the running status of the other threads.

This allows you to scale up or down the number of threads running in your software as much as you want. You find that the 4 threads is blocking too much on outside resources, then you can increase the number. Pushing your battered server too hard then reduce the number of running threads. The lock objects ensure mutex and communication between the threads independent of how many threads are running.

How to make div fixed after you scroll to that div?

jquery function is most important

<script>
$(function(){
    var stickyHeaderTop = $('#stickytypeheader').offset().top;

    $(window).scroll(function(){
            if( $(window).scrollTop() > stickyHeaderTop ) {
                    $('#stickytypeheader').css({position: 'fixed', top: '0px'});
                    $('#sticky').css('display', 'block');
            } else {
                    $('#stickytypeheader').css({position: 'static', top: '0px'});
                    $('#sticky').css('display', 'none');
            }
    });
});
</script>

Then use JQuery Lib...

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

Now use HTML

<div id="header">
    <p>This text is non sticky</p>
    <p>This text is non sticky</p>
    <p>This text is non sticky</p>
    <p>This text is non sticky</p>
 </div>

<div id="stickytypeheader">
 <table width="100%">
  <tr>
    <td><a href="http://growthpages.com/">Growth pages</a></td>

    <td><a href="http://google.com/">Google</a></td>

    <td><a href="http://yahoo.com/">Yahoo</a></td>

    <td><a href="http://www.bing.com/">Bing</a></td>

    <td><a href="#">Visitor</a></td>
  </tr>
 </table>
</div>

<div id="content">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis
aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.</p>
</div>

Check DEMO HERE

Double value to round up in Java

Live @Sergey's solution but with integer division.

double value = 23.8764367843;
double rounded = (double) Math.round(value * 100) / 100;
System.out.println(value +" rounded is "+ rounded);

prints

23.8764367843 rounded is 23.88

EDIT: As Sergey points out, there should be no difference between multipling double*int and double*double and dividing double/int and double/double. I can't find an example where the result is different. However on x86/x64 and other systems there is a specific machine code instruction for mixed double,int values which I believe the JVM uses.

for (int j = 0; j < 11; j++) {
    long start = System.nanoTime();
    for (double i = 1; i < 1e6; i *= 1.0000001) {
        double rounded = (double) Math.round(i * 100) / 100;
    }
    long time = System.nanoTime() - start;
    System.out.printf("double,int operations %,d%n", time);
}
for (int j = 0; j < 11; j++) {
    long start = System.nanoTime();
    for (double i = 1; i < 1e6; i *= 1.0000001) {
        double rounded = (double) Math.round(i * 100.0) / 100.0;
    }
    long time = System.nanoTime() - start;
    System.out.printf("double,double operations %,d%n", time);
}

Prints

double,int operations 613,552,212
double,int operations 661,823,569
double,int operations 659,398,960
double,int operations 659,343,506
double,int operations 653,851,816
double,int operations 645,317,212
double,int operations 647,765,219
double,int operations 655,101,137
double,int operations 657,407,715
double,int operations 654,858,858
double,int operations 648,702,279
double,double operations 1,178,561,102
double,double operations 1,187,694,386
double,double operations 1,184,338,024
double,double operations 1,178,556,353
double,double operations 1,176,622,937
double,double operations 1,169,324,313
double,double operations 1,173,162,162
double,double operations 1,169,027,348
double,double operations 1,175,080,353
double,double operations 1,182,830,988
double,double operations 1,185,028,544

Style the first <td> column of a table differently

If you've to support IE7, a more compatible solution is:

/* only the cells with no cell before (aka the first one) */
td {
    padding-left: 20px;
}
/* only the cells with at least one cell before (aka all except the first one) */
td + td {
    padding-left: 0;
}

Also works fine with li; general sibling selector ~ may be more suitable with mixed elements like a heading h1 followed by paragraphs AND a subheading and then again other paragraphs.

python's re: return True if string contains regex pattern

You can do something like this:

Using search will return a SRE_match object, if it matches your search string.

>>> import re
>>> m = re.search(u'ba[r|z|d]', 'bar')
>>> m
<_sre.SRE_Match object at 0x02027288>
>>> m.group()
'bar'
>>> n = re.search(u'ba[r|z|d]', 'bas')
>>> n.group()

If not, it will return None

Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    n.group()
AttributeError: 'NoneType' object has no attribute 'group'

And just to print it to demonstrate again:

>>> print n
None

How should I print types like off_t and size_t?

use "%zo" for off_t. (octal) or "%zu" for decimal.

How to add fixed button to the bottom right of page

This will be helpful for the right bottom rounded button

HTML :

      <a class="fixedButton" href>
         <div class="roundedFixedBtn"><i class="fa fa-phone"></i></div>
      </a>
    

CSS:

       .fixedButton{
            position: fixed;
            bottom: 0px;
            right: 0px; 
            padding: 20px;
        }
        .roundedFixedBtn{
          height: 60px;
          line-height: 80px;  
          width: 60px;  
          font-size: 2em;
          font-weight: bold;
          border-radius: 50%;
          background-color: #4CAF50;
          color: white;
          text-align: center;
          cursor: pointer;
        }
    

Here is jsfiddle link http://jsfiddle.net/vpthcsx8/11/

JavaScript/jQuery to download file via POST with JSON data

Not entirely an answer to the original post, but a quick and dirty solution for posting a json-object to the server and dynamically generating a download.

Client side jQuery:

var download = function(resource, payload) {
     $("#downloadFormPoster").remove();
     $("<div id='downloadFormPoster' style='display: none;'><iframe name='downloadFormPosterIframe'></iframe></div>").appendTo('body');
     $("<form action='" + resource + "' target='downloadFormPosterIframe' method='post'>" +
      "<input type='hidden' name='jsonstring' value='" + JSON.stringify(payload) + "'/>" +
      "</form>")
      .appendTo("#downloadFormPoster")
      .submit();
}

..and then decoding the json-string at the serverside and setting headers for download (PHP example):

$request = json_decode($_POST['jsonstring']), true);
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=export.csv');
header('Pragma: no-cache');

Installing MySQL-python

yum install mysql-devel

It worked for me.

Hiding an Excel worksheet with VBA

This can be done in a single line, as long as the worksheet is active:

ActiveSheet.Visible = xlSheetHidden

However, you may not want to do this, especially if you use any "select" operations or you use any more ActiveSheet operations.

How to check if a std::thread is still running?

Create a mutex that the running thread and the calling thread both have access to. When the running thread starts it locks the mutex, and when it ends it unlocks the mutex. To check if the thread is still running, the calling thread calls mutex.try_lock(). The return value of that is the status of the thread. (Just make sure to unlock the mutex if the try_lock worked)

One small problem with this, mutex.try_lock() will return false between the time the thread is created, and when it locks the mutex, but this can be avoided using a slightly more complex method.

Java ArrayList how to add elements at the beginning

Take this example :-

List<String> element1 = new ArrayList<>();
element1.add("two");
element1.add("three");
List<String> element2 = new ArrayList<>();
element2.add("one");
element2.addAll(element1);

jquery datatables hide column

For anyone using server-side processing and passing database values into jQuery using a hidden column, I suggest "sClass" param. You'll be able to use css display: none to hide the column while still being able to retrieve its value.

css:

th.dpass, td.dpass {display: none;}

In datatables init:

"aoColumnDefs": [ { "sClass": "dpass", "aTargets": [ 0 ] } ] // first column in visible columns array gets class "dpass"

//EDIT: remember to add your hidden class to your thead cell also