Programs & Examples On #Tbucketlist

How to use onSaveInstanceState() and onRestoreInstanceState()?

  • onSaveInstanceState() is a method used to store data before pausing the activity.

Description : Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state. This state should only contain information that is not persistent or can not be reconstructed later. For example, you will never store your current position on screen because that will be computed again when a new instance of the view is placed in its view hierarchy.

  • onRestoreInstanceState() is method used to retrieve that data back.

Description : This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState. Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation. The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(Bundle).

Consider this example here:
You app has 3 edit boxes where user was putting in some info , but he gets a call so if you didn't use the above methods what all he entered will be lost.
So always save the current data in onPause() method of Activity as a bundle & in onResume() method call the onRestoreInstanceState() method .

Please see :

How to use onSavedInstanceState example please

http://www.how-to-develop-android-apps.com/tag/onrestoreinstancestate/

C# Regex for Guid

For C# .Net to find and replace any guid looking string from the given text,

Use this RegEx:

[({]?[a-fA-F0-9]{8}[-]?([a-fA-F0-9]{4}[-]?){3}[a-fA-F0-9]{12}[})]?

Example C# code:

var result = Regex.Replace(
      source, 
      @"[({]?[a-fA-F0-9]{8}[-]?([a-fA-F0-9]{4}[-]?){3}[a-fA-F0-9]{12}[})]?", 
      @"${ __UUID}", 
      RegexOptions.IgnoreCase
);

Surely works! And it matches & replaces the following styles, which are all equivalent and acceptable formats for a GUID.

"aa761232bd4211cfaacd00aa0057b243" 
"AA761232-BD42-11CF-AACD-00AA0057B243" 
"{AA761232-BD42-11CF-AACD-00AA0057B243}" 
"(AA761232-BD42-11CF-AACD-00AA0057B243)" 

PHP date() format when inserting into datetime in MySQL

Here's an alternative solution: if you have the date in PHP as a timestamp, bypass handling it with PHP and let the DB take care of transforming it by using the FROM_UNIXTIME function.

mysql> insert into a_table values(FROM_UNIXTIME(1231634282));
Query OK, 1 row affected (0.00 sec)

mysql> select * from a_table;

+---------------------+
| a_date              |
+---------------------+
| 2009-01-10 18:38:02 |
+---------------------+

Python - How do you run a .py file?

On windows platform, you have 2 choices:

  1. In a command line terminal, type

    c:\python23\python xxxx.py

  2. Open the python editor IDLE from the menu, and open xxxx.py, then press F5 to run it.

For your posted code, the error is at this line:

def main(url, out_folder="C:\asdf\"):

It should be:

def main(url, out_folder="C:\\asdf\\"):

How to count instances of character in SQL Column

try this

declare @v varchar(250) = 'test.a,1  ;hheuw-20;'
-- LF   ;
select len(replace(@v,';','11'))-len(@v)

How to test Spring Data repositories?

With JUnit5 and @DataJpaTest test will look like (kotlin code):

@DataJpaTest
@ExtendWith(value = [SpringExtension::class])
class ActivityJpaTest {

    @Autowired
    lateinit var entityManager: TestEntityManager

    @Autowired
    lateinit var myEntityRepository: MyEntityRepository

    @Test
    fun shouldSaveEntity() {
        // when
        val savedEntity = myEntityRepository.save(MyEntity(1, "test")

        // then 
        Assertions.assertNotNull(entityManager.find(MyEntity::class.java, savedEntity.id))
    }
}

You could use TestEntityManager from org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager package in order to validate entity state.

How do you concatenate Lists in C#?

Try this:

myList1 = myList1.Concat(myList2).ToList();

Concat returns an IEnumerable<T> that is the two lists put together, it doesn't modify either existing list. Also, since it returns an IEnumerable, if you want to assign it to a variable that is List<T>, you'll have to call ToList() on the IEnumerable<T> that is returned.

import .css file into .less file

since 1.5.0 u can use the 'inline' keyword.

Example: @import (inline) "not-less-compatible.css";

You will use this when a CSS file may not be Less compatible; this is because although Less supports most known standards CSS, it does not support comments in some places and does not support all known CSS hacks without modifying the CSS. So you can use this to include the file in the output so that all CSS will be in one file.

(source: http://lesscss.org/features/#import-directives-feature)

How to delete all files and folders in a directory?

To delete the folder, this is code using Text box and a button using System.IO; :

private void Deletebt_Click(object sender, EventArgs e)
{
    System.IO.DirectoryInfo myDirInfo = new DirectoryInfo(@"" + delete.Text);

    foreach (FileInfo file in myDirInfo.GetFiles())
    {
       file.Delete();
    }
    foreach (DirectoryInfo dir in myDirInfo.GetDirectories())
    {
       dir.Delete(true);
    }
}

Angular 2 filter/search list

You have to manually filter result based on change of input each time by keeping listener over input event. While doing manually filtering make sure you should maintain two copy of variable, one would be original collection copy & second would be filteredCollection copy. The advantage for going this way could save your couple of unnecessary filtering on change detection cycle. You may see a more code, but this would be more performance friendly.

Markup - HTML Template

<md-input #myInput placeholder="Item name..." [(ngModel)]="name" (input)="filterItem(myInput.value)"></md-input>

<div *ngFor="let item of filteredItems">
   {{item.name}}
</div>

Code

assignCopy(){
   this.filteredItems = Object.assign([], this.items);
}
filterItem(value){
   if(!value){
       this.assignCopy();
   } // when nothing has typed
   this.filteredItems = Object.assign([], this.items).filter(
      item => item.name.toLowerCase().indexOf(value.toLowerCase()) > -1
   )
}
this.assignCopy();//when you fetch collection from server.

Getting today's date in YYYY-MM-DD in Python?

You can use,

>>> from datetime import date
>>> date.today().__str__()
'2019-10-05'

datetimepicker is not a function jquery

I had the same problem with bootstrap datetimepicker extension. Including moment.js before datetimepicker.js was the solution.

How to declare or mark a Java method as deprecated?

Use @Deprecated on method. Don't forget about clarifying javadoc field:

/**
 * Does some thing in old style.
 *
 * @deprecated use {@link #new()} instead.  
 */
@Deprecated
public void old() {
// ...
}

Postgresql Windows, is there a default password?

Try this:

Open PgAdmin -> Files -> Open pgpass.conf

You would get the path of pgpass.conf at the bottom of the window. Go to that location and open this file, you can find your password there.

Reference

If the above does not work, you may consider trying this:

 1. edit pg_hba.conf to allow trust authorization temporarily
 2. Reload the config file (pg_ctl reload)
 3. Connect and issue ALTER ROLE / PASSWORD to set the new password
 4. edit pg_hba.conf again and restore the previous settings
 5. Reload the config file again

How to concatenate items in a list to a single string?

Without .join() method you can use this method:

my_list=["this","is","a","sentence"]

concenated_string=""
for string in range(len(my_list)):
    if string == len(my_list)-1:
        concenated_string+=my_list[string]
    else:
        concenated_string+=f'{my_list[string]}-'
print([concenated_string])
    >>> ['this-is-a-sentence']

So, range based for loop in this example , when the python reach the last word of your list, it should'nt add "-" to your concenated_string. If its not last word of your string always append "-" string to your concenated_string variable.

T-SQL How to select only Second row from a table?

with T1 as
(
  select row_number() over(order by ID) rownum, T2.ID
  from Table2 T2
)
select ID
from T1
where rownum=2

How to loop through all enum values in C#?

 Enum.GetValues(typeof(Foos))

Counting unique values in a column in pandas dataframe like in Qlik?

Count distinct values, use nunique:

df['hID'].nunique()
5

Count only non-null values, use count:

df['hID'].count()
8

Count total values including null values, use the size attribute:

df['hID'].size
8

Edit to add condition

Use boolean indexing:

df.loc[df['mID']=='A','hID'].agg(['nunique','count','size'])

OR using query:

df.query('mID == "A"')['hID'].agg(['nunique','count','size'])

Output:

nunique    5
count      5
size       5
Name: hID, dtype: int64

Uninstalling Android ADT

i got the same problem after clicking update plugins, i tried all the suggestions above and failed , the only thing that worked for my is reinstalling android studio..

How to ignore files/directories in TFS for avoiding them to go to central source repository?

It does seem a little cumbersome to ignore files (and folders) in Team Foundation Server. I've found a couple ways to do this (using TFS / Team Explorer / Visual Studio 2008). These methods work with the web site ASP project type, too.

One way is to add a new or existing item to a project (e.g. right click on project, Add Existing Item or drag and drop from Windows explorer into the solution explorer), let TFS process the file(s) or folder, then undo pending changes on the item(s). TFS will unmark them as having a pending add change, and the files will sit quietly in the project and stay out of TFS.

Another way is with the Add Items to Folder command of Source Control Explorer. This launches a small wizard, and on one of the steps you can select items to exclude (although, I think you have to add at least one item to TFS with this method for the wizard to let you continue).

You can even add a forbidden patterns check-in policy (under Team -> Team Project Settings -> Source Control... -> Check-in Policy) to disallow other people on the team from mistakenly checking in certain assets.

Angular: Cannot Get /

The way I resolved this error was by finding and fixing the error that the console reported.

Run ng build in your command line/terminal, and it should display a useful error, such as the example in red here: Property 'name' does not exist on type 'object'.

Console example

How to write to a JSON file in the correct format

With formatting

require 'json'
tempHash = {
    "key_a" => "val_a",
    "key_b" => "val_b"
}
File.open("public/temp.json","w") do |f|
  f.write(JSON.pretty_generate(tempHash))
end

Output

{
    "key_a":"val_a",
    "key_b":"val_b"
}

How to set my phpmyadmin user session to not time out so quickly?

To increase the phpMyAdmin Session Timeout, open config.inc.php in the root phpMyAdmin directory and add this setting (anywhere).

$cfg['LoginCookieValidity'] = <your_new_timeout>;

Where <your_new_timeout> is some number larger than 1800.

Note:

Always keep on mind that a short cookie lifetime is all well and good for the development server. So do not do this on your production server.

How can I get href links from HTML using Python?

Simplest way for me:

from urlextract import URLExtract
from requests import get

url = "sample.com/samplepage/"
req = requests.get(url)
text = req.text
# or if you already have the html source:
# text = "This is html for ex <a href='http://google.com/'>Google</a> <a href='http://yahoo.com/'>Yahoo</a>"
text = text.replace(' ', '').replace('=','')
extractor = URLExtract()
print(extractor.find_urls(text))

output:

['http://google.com/', 'http://yahoo.com/']

CSS property to pad text inside of div

The CSS property you are looking for is padding. The problem with padding is that it adds to the width of the original element, so if you have a div with a width of 300px, and add 10px of padding to it, the width will now be 320px (10px on the left and 10px on the right).

To prevent this you can add box-sizing: border-box; to the div, this makes it maintain the designated width, even if you add padding. So your CSS would look like this:

div {
    box-sizing: border-box;
    padding: 10px;
}

you can read more about box-sizing and it's overall browser support here:

http://www.paulirish.com/2012/box-sizing-border-box-ftw/

How to use mod operator in bash?

You must put your mathematical expressions inside $(( )).

One-liner:

for i in {1..600}; do wget http://example.com/search/link$(($i % 5)); done;

Multiple lines:

for i in {1..600}; do
    wget http://example.com/search/link$(($i % 5))
done

printf format specifiers for uint32_t and size_t

All that's needed is that the format specifiers and the types agree, and you can always cast to make that true. long is at least 32 bits, so %lu together with (unsigned long)k is always correct:

uint32_t k;
printf("%lu\n", (unsigned long)k);

size_t is trickier, which is why %zu was added in C99. If you can't use that, then treat it just like k (long is the biggest type in C89, size_t is very unlikely to be larger).

size_t sz;
printf("%zu\n", sz);  /* C99 version */
printf("%lu\n", (unsigned long)sz);  /* common C89 version */

If you don't get the format specifiers correct for the type you are passing, then printf will do the equivalent of reading too much or too little memory out of the array. As long as you use explicit casts to match up types, it's portable.

What does "Table does not support optimize, doing recreate + analyze instead" mean?

The better option is create a new table copy the rows to the destination table, drop the actual table and rename the newly created table . This method is good for small tables,

How to crop an image in OpenCV using Python

to make it easier for you here is the code that i use :

w, h = image.shape
top=10
right=50
down=15
left=80
croped_image = image[top:((w-down)+top), right:((h-left)+right)]
plt.imshow(croped_image, cmap="gray")
plt.show()

Converting map to struct

There are two steps:

  1. Convert interface to JSON Byte
  2. Convert JSON Byte to struct

Below is an example:

dbByte, _ := json.Marshal(dbContent)
_ = json.Unmarshal(dbByte, &MyStruct)

fatal error LNK1104: cannot open file 'kernel32.lib'

OS : Win10, Visual Studio 2015

Solution : Go to control panel ---> uninstall program ---MSvisual studio ----> change ---->organize = repair

and repair it. Note that you must connect to internet until repairing finish.

Good luck.

How to create a connection string in asp.net c#

string connectionstring="DataSource=severname;InitialCatlog=databasename;Uid=; password=;"
SqlConnection con=new SqlConnection(connectionstring)

Android Transparent TextView?

In case someone wants to do this in the programming way! Do the following: Update the color file in your values folder with this.

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="transparent">#00ffffff</color> <!--This is the transparency line-->
</resources>

then call the transparency programitically

your_textview.setBackgroundResource(R.color.transparent);

jquery: $(window).scrollTop() but no $(window).scrollBottom()

For the future, I've made scrollBottom into a jquery plugin, usable in the same way that scrollTop is (i.e. you can set a number and it will scroll that amount from the bottom of the page and return the number of pixels from the bottom of the page, or, return the number of pixels from the bottom of the page if no number is provided)

$.fn.scrollBottom = function(scroll){
  if(typeof scroll === 'number'){
    window.scrollTo(0,$(document).height() - $(window).height() - scroll);
    return $(document).height() - $(window).height() - scroll;
  } else {
    return $(document).height() - $(window).height() - $(window).scrollTop();
  }
}
//Basic Usage
$(window).scrollBottom(500);

SQL Query - Change date format in query to DD/MM/YYYY

SELECT CONVERT(varchar(11),Getdate(),105)

CSS Inset Borders

If box-sizing is not an option, another way to do this is just to make it a child of the sized element.

Demo

CSS

.box {
  width: 100px;
  height: 100px;
  display: inline-block;
  margin-right: 5px;
}
.border {
  border: 1px solid;
  display: block;
}
.medium { border-width: 10px; }
.large  { border-width: 25px; }


HTML

<div class="box">
  <div class="border small">A</div>
</div>
<div class="box">
  <div class="border medium">B</div>
</div>
<div class="box">
  <div class="border large">C</div>
</div>

Selecting the last value of a column

I have gone through way too many of these implementations of last-row for a specific column. Many solutions work but are slow for large or multiple datasets. One of my use cases requires me to check the last row in specific columns across multiple spreadsheets. What I have found is that taking the whole column as a range and then iterating through it is too slow, and adding a few of these together makes the script sluggish.

My "hack" has been this formula:

=ROW(index(sheet!A2:A,max(row(sheet!A2:A)*(sheet!A2:A<>""))))-1
  • Example: Add this to Cell A1, to find the last row in column A. Can be added anywhere, just make sure to manage the "-1" at the end depending on which row the formula is placed. You can also place this is another col, rather than the one you're trying to count, and you don't need to manage the -1. You could also count FROM a starting Row, like "C16:C" - will count values C16 onwards

  • This formula is reliably giving me the last row, including blanks in the middle of the dataset

  • To use this value in my GS code, I am simply reading the cell value from A1. I understand that Google is clear that spreadsheet functions like read/write are heavy (time-consuming), but this is much faster than column count last-row methods in my experience (for large datasets)

  • To make this efficient, I am getting the last row in a col once, then saving it as a global variable and incrementing in my code to track which rows I should be updating. Reading the cell every-time your loop needs to make an update will be too inefficient. Read once, iterate the value, and the A1 cell formula (above) is "storing" the updated value for the next time your function runs

Please let me know if this was helpful to you! If I encounter any issues I will comment on this answer.

Show just the current branch in Git

For completeness, echo $(__git_ps1), on Linux at least, should give you the name of the current branch surrounded by parentheses.

This may be useful is some scenarios as it is not a Git command (while depending on Git), notably for setting up your Bash command prompt to display the current branch.

For example:

/mnt/c/git/ConsoleApp1 (test-branch)> echo $(__git_ps1)
(test-branch)
/mnt/c/git/ConsoleApp1 (test-branch)> git checkout master
Switched to branch 'master'
/mnt/c/git/ConsoleApp1 (master)> echo $(__git_ps1)
(master)
/mnt/c/git/ConsoleApp1 (master)> cd ..
/mnt/c/git> echo $(__git_ps1)

/mnt/c/git>

Find duplicate entries in a column

Using:

  SELECT t.ctn_no
    FROM YOUR_TABLE t
GROUP BY t.ctn_no
  HAVING COUNT(t.ctn_no) > 1

...will show you the ctn_no value(s) that have duplicates in your table. Adding criteria to the WHERE will allow you to further tune what duplicates there are:

  SELECT t.ctn_no
    FROM YOUR_TABLE t
   WHERE t.s_ind = 'Y'
GROUP BY t.ctn_no
  HAVING COUNT(t.ctn_no) > 1

If you want to see the other column values associated with the duplicate, you'll want to use a self join:

SELECT x.*
  FROM YOUR_TABLE x
  JOIN (SELECT t.ctn_no
          FROM YOUR_TABLE t
      GROUP BY t.ctn_no
        HAVING COUNT(t.ctn_no) > 1) y ON y.ctn_no = x.ctn_no

Is there a Visual Basic 6 decompiler?

Yes I think You can get it download and separately its Help files from: vbdecompiler.org Site. and there is a Video on YouTube which explains how to Use it to Get the Code from an exe file and Save it. I hope that I helped.

How to delete multiple rows in SQL where id = (x to y)

Delete Id from table where Id in (select id from table)

Move an item inside a list?

Use the insert method of a list:

l = list(...)
l.insert(index, item)

Alternatively, you can use a slice notation:

l[index:index] = [item]

If you want to move an item that's already in the list to the specified position, you would have to delete it and insert it at the new position:

l.insert(newindex, l.pop(oldindex))

Why is this printing 'None' in the output?

Because of double print function. I suggest you to use return instead of print inside the function definition.

def lyrics():
    return "The very first line"
print(lyrics())

OR

def lyrics():
    print("The very first line")
lyrics()

Stop UIWebView from "bouncing" vertically?

One of the subviews of UIWebView should be a UIScrollView. Set its scrollEnabled property to NO and the web view will have scrolling disabled entirely.

Note: this is technically using a private API and thus your app could be rejected or crash in future OS releases. Use @try and respondsToSelector

Select a random sample of results from a query result

SELECT  *
FROM    (
        SELECT  *
        FROM    mytable
        ORDER BY
                dbms_random.value
        )
WHERE rownum <= 1000

String format currency

Personally i'm against using culture specific code, i suggest doing:

@String.Format(CultureInfo.CurrentCulture, "{0:C}", @price)

and in your web.config do:

<system.web>
    <globalization culture="en-GB" uiCulture="en-US" />
</system.web>

Additional info: https://msdn.microsoft.com/en-us/library/syy068tk(v=vs.90).aspx

How to schedule a stored procedure in MySQL

You can use mysql scheduler to run it each 5 seconds. You can find samples at http://dev.mysql.com/doc/refman/5.1/en/create-event.html

Never used it but I hope this would work:

CREATE EVENT myevent
    ON SCHEDULE EVERY 5 SECOND
    DO
      CALL delete_rows_links();

button image as form input submit button?

<div class="container-fluid login-container">
    <div class="row">
        <form (ngSubmit)="login('da')">
            <div class="col-md-4">
                    <div class="login-text">
                        Login
                    </div>
                    <div class="form-signin">
                            <input type="text" class="form-control" placeholder="Email" required>
                            <input type="password" class="form-control" placeholder="Password" required>
                    </div>
            </div>
            <div class="col-md-4">
                <div class="login-go-div">
                    <input type="image" src="../../../assets/images/svg/login-go-initial.svg" class="login-go"
                         onmouseover="this.src='../../../assets/images/svg/login-go.svg'"
                         onmouseout="this.src='../../../assets/images/svg/login-go-initial.svg'"/>
                </div>
            </div>
        </form>
    </div>
</div>

This is the working code for it.

Accessing JPEG EXIF rotation data in JavaScript on the client side

If you want it cross-browser, your best bet is to do it on the server. You could have an API that takes a file URL and returns you the EXIF data; PHP has a module for that.

This could be done using Ajax so it would be seamless to the user. If you don't care about cross-browser compatibility, and can rely on HTML5 file functionality, look into the library JsJPEGmeta that will allow you to get that data in native JavaScript.

CSS3 selector :first-of-type with class name?

This it not possible to use the CSS3 selector :first-of-type to select the first element with a given class name.

However, if the targeted element has a previous element sibling, you can combine the negation CSS pseudo-class and the adjacent sibling selectors to match an element that doesn't immediately have a previous element with the same class name :

:not(.myclass1) + .myclass1

Full working code example:

_x000D_
_x000D_
p:first-of-type {color:blue}_x000D_
p:not(.myclass1) + .myclass1 { color: red }_x000D_
p:not(.myclass2) + .myclass2 { color: green }
_x000D_
<div>_x000D_
  <div>This text should appear as normal</div>_x000D_
  <p>This text should be blue.</p>_x000D_
  <p class="myclass1">This text should appear red.</p>_x000D_
  <p class="myclass2">This text should appear green.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Virtualbox "port forward" from Guest to Host

Network communication Host -> Guest

Connect to the Guest and find out the ip address:

ifconfig 

example of result (ip address is 10.0.2.15):

eth0      Link encap:Ethernet  HWaddr 08:00:27:AE:36:99
          inet addr:10.0.2.15  Bcast:10.0.2.255  Mask:255.255.255.0

Go to Vbox instance window -> Menu -> Network adapters:

  • adapter should be NAT
  • click on "port forwarding"
  • insert new record (+ icon)
    • for host ip enter 127.0.0.1, and for guest ip address you got from prev. step (in my case it is 10.0.2.15)
    • in your case port is 8000 - put it on both, but you can change host port if you prefer

Go to host system and try it in browser:

http://127.0.0.1:8000

or your network ip address (find out on the host machine by running: ipconfig).

Network communication Guest -> Host

In this case port forwarding is not needed, the communication goes over the LAN back to the host.

On the host machine - find out your netw ip address:

ipconfig

example of result:

IP Address. . . . . . . . . . . . : 192.168.5.1

On the guest machine you can communicate directly with the host, e.g. check it with ping:

# ping 192.168.5.1
PING 192.168.5.1 (192.168.5.1) 56(84) bytes of data.
64 bytes from 192.168.5.1: icmp_seq=1 ttl=128 time=2.30 ms
...

Firewall issues?

@Stranger suggested that in some cases it would be necessary to open used port (8000 or whichever is used) in firewall like this (example for ufw firewall, I haven't tested):

sudo ufw allow 8000 

How to make a great R reproducible example

To quickly create a dput of your data you can just copy (a piece of) the data to your clipboard and run the following in R:

for data in Excel:

dput(read.table("clipboard",sep="\t",header=TRUE))

for data in a txt file:

dput(read.table("clipboard",sep="",header=TRUE))

You can change the sep in the latter if necessary. This will only work if your data is in the clipboard of course.

Composer Update Laravel

this is command for composer update please try this...

composer self-update

Cross-platform way of getting temp directory in Python

That would be the tempfile module.

It has functions to get the temporary directory, and also has some shortcuts to create temporary files and directories in it, either named or unnamed.

Example:

import tempfile

print tempfile.gettempdir() # prints the current temporary directory

f = tempfile.TemporaryFile()
f.write('something on temporaryfile')
f.seek(0) # return to beginning of file
print f.read() # reads data back from the file
f.close() # temporary file is automatically deleted here

For completeness, here's how it searches for the temporary directory, according to the documentation:

  1. The directory named by the TMPDIR environment variable.
  2. The directory named by the TEMP environment variable.
  3. The directory named by the TMP environment variable.
  4. A platform-specific location:
    • On RiscOS, the directory named by the Wimp$ScrapDir environment variable.
    • On Windows, the directories C:\TEMP, C:\TMP, \TEMP, and \TMP, in that order.
    • On all other platforms, the directories /tmp, /var/tmp, and /usr/tmp, in that order.
  5. As a last resort, the current working directory.

INSERT with SELECT

Yes, absolutely, but check your syntax.

INSERT INTO courses (name, location, gid)
SELECT name, location, 1
FROM   courses
WHERE  cid = 2

You can put a constant of the same type as gid in its place, not just 1, of course. And, I just made up the cid value.

Choose File Dialog

I have created FolderLayout which may help you. This link helped me

folderview.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView android:id="@+id/path" android:text="Path"
        android:layout_width="match_parent" android:layout_height="wrap_content"></TextView>
    <ListView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:id="@+id/list"></ListView>

</LinearLayout>

FolderLayout.java

package com.testsample.activity;




   public class FolderLayout extends LinearLayout implements OnItemClickListener {

    Context context;
    IFolderItemListener folderListener;
    private List<String> item = null;
    private List<String> path = null;
    private String root = "/";
    private TextView myPath;
    private ListView lstView;

    public FolderLayout(Context context, AttributeSet attrs) {
        super(context, attrs);

        // TODO Auto-generated constructor stub
        this.context = context;


        LayoutInflater layoutInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.folderview, this);

        myPath = (TextView) findViewById(R.id.path);
        lstView = (ListView) findViewById(R.id.list);

        Log.i("FolderView", "Constructed");
        getDir(root, lstView);

    }

    public void setIFolderItemListener(IFolderItemListener folderItemListener) {
        this.folderListener = folderItemListener;
    }

    //Set Directory for view at anytime
    public void setDir(String dirPath){
        getDir(dirPath, lstView);
    }


    private void getDir(String dirPath, ListView v) {

        myPath.setText("Location: " + dirPath);
        item = new ArrayList<String>();
        path = new ArrayList<String>();
        File f = new File(dirPath);
        File[] files = f.listFiles();

        if (!dirPath.equals(root)) {

            item.add(root);
            path.add(root);
            item.add("../");
            path.add(f.getParent());

        }
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            path.add(file.getPath());
            if (file.isDirectory())
                item.add(file.getName() + "/");
            else
                item.add(file.getName());

        }

        Log.i("Folders", files.length + "");

        setItemList(item);

    }

    //can manually set Item to display, if u want
    public void setItemList(List<String> item){
        ArrayAdapter<String> fileList = new ArrayAdapter<String>(context,
                R.layout.row, item);

        lstView.setAdapter(fileList);
        lstView.setOnItemClickListener(this);
    }


    public void onListItemClick(ListView l, View v, int position, long id) {
        File file = new File(path.get(position));
        if (file.isDirectory()) {
            if (file.canRead())
                getDir(path.get(position), l);
            else {
//what to do when folder is unreadable
                if (folderListener != null) {
                    folderListener.OnCannotFileRead(file);

                }

            }
        } else {

//what to do when file is clicked
//You can add more,like checking extension,and performing separate actions
            if (folderListener != null) {
                folderListener.OnFileClicked(file);
            }

        }
    }

    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub
        onListItemClick((ListView) arg0, arg0, arg2, arg3);
    }

}

And an Interface IFolderItemListener to add what to do when a fileItem is clicked

IFolderItemListener.java

public interface IFolderItemListener {

    void OnCannotFileRead(File file);//implement what to do folder is Unreadable
    void OnFileClicked(File file);//What to do When a file is clicked
}

Also an xml to define the row

row.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rowtext" android:layout_width="fill_parent"
    android:textSize="23sp" android:layout_height="match_parent"/>

How to Use in your Application

In your xml,

folders.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="horizontal" android:weightSum="1">
    <com.testsample.activity.FolderLayout android:layout_height="match_parent" layout="@layout/folderview"
        android:layout_weight="0.35"
        android:layout_width="200dp" android:id="@+id/localfolders"></com.testsample.activity.FolderLayout></LinearLayout>

In Your Activity,

SampleFolderActivity.java

public class SampleFolderActivity extends Activity implements IFolderItemListener {

    FolderLayout localFolders;

    /** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        localFolders = (FolderLayout)findViewById(R.id.localfolders);
        localFolders.setIFolderItemListener(this);
            localFolders.setDir("./sys");//change directory if u want,default is root   

    }

    //Your stuff here for Cannot open Folder
    public void OnCannotFileRead(File file) {
        // TODO Auto-generated method stub
        new AlertDialog.Builder(this)
        .setIcon(R.drawable.icon)
        .setTitle(
                "[" + file.getName()
                        + "] folder can't be read!")
        .setPositiveButton("OK",
                new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog,
                            int which) {


                    }
                }).show();

    }


    //Your stuff here for file Click
    public void OnFileClicked(File file) {
        // TODO Auto-generated method stub
        new AlertDialog.Builder(this)
        .setIcon(R.drawable.icon)
        .setTitle("[" + file.getName() + "]")
        .setPositiveButton("OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int which) {


                    }

                }).show();
    }

}

Import the libraries needed. Hope these help you...

How to create a new file in unix?

Try > workdirectory/filename.txt

This would:

  • truncate the file if it exists
  • create if it doesn't exist

You can consider it equivalent to:

rm -f workdirectory/filename.txt; touch workdirectory/filename.txt

How to determine total number of open/active connections in ms sql server 2005

see sp_who it gives you more details than just seeing the number of connections

in your case i would do something like this

 DECLARE @temp TABLE(spid int , ecid int, status varchar(50),
                     loginname varchar(50),   
                     hostname varchar(50),
blk varchar(50), dbname varchar(50), cmd varchar(50), request_id int) 
INSERT INTO @temp  

EXEC sp_who

SELECT COUNT(*) FROM @temp WHERE dbname = 'DB NAME'

How to add items to a spinner in Android?

Add a spinner to the XML layout, and then add this code to the Java file:

Spinner spinner;
spinner = (Spinner) findViewById(R.id.spinner1) ;
java.util.ArrayList<String> strings = new java.util.ArrayList<>();
strings.add("Mobile") ;
strings.add("Home");
strings.add("Work");
SpinnerAdapter spinnerAdapter = new SpinnerAdapter(AddMember.this, R.layout.support_simple_spinner_dropdown_item, strings);
spinner.setAdapter(spinnerAdapter);

Java int to String - Integer.toString(i) vs new Integer(i).toString()

Although I like fhucho's recommendation of

String.valueOf(i)

The irony is that this method actually calls

Integer.toString(i)

Thus, use String.valueOf(i) if you like how it reads and you don't need radix, but also knowing that it is less efficient than Integer.toString(i).

What is the difference between String and string in C#?

Lower case string is an alias for System.String. They are the same in C#.

There's a debate over whether you should use the System types (System.Int32, System.String, etc.) types or the C# aliases (int, string, etc). I personally believe you should use the C# aliases, but that's just my personal preference.

Bootstrap modal z-index

The problem almost always has something to do with "nested" z-indexes. As an Example:

<div style="z-index:1">
  some content A
  <div style="z-index:1000000000">
    some content B
  </div>
</div>
<div style="z-index:10">
  Some content C
</div>

if you look at the z-index only you would expect B,C,A, but because B is nested in a div that is expressly set to 1, it will show up as C,B,A.

Setting position:fixed locks the z-index for that element and all its children, which is why changing that can solve the problem.

The solution is to find the parent element that has the z-index set and either adjust the setting or move the content so the layers and their parent containers stack up the way you want. Firebug in Firefox has a tab in the far right named "Layout" and you can quickly go up the parent elements and see where the z-index is set.

CodeIgniter Active Record not equal

It worked fine with me,

$this->db->where("your_id !=",$your_id);

Or try this one,

$this->db->where("your_id <>",$your_id);

Or try this one,

$this->db->where("your_id IS NOT NULL");

all will work.

Cannot authenticate into mongo, "auth fails"

You may need to upgrade your mongo shell. I had version 2.4.9 of the mongo shell locally, and I got this error trying to connect to a mongo 3 database. Upgrading the shell version to 3 solved the problem.

Does Python have a toString() equivalent, and can I convert a db.Model element to String?

str() is the equivalent.

However you should be filtering your query. At the moment your query is all() Todo's.

todos = Todo.all().filter('author = ', users.get_current_user().nickname()) 

or

todos = Todo.all().filter('author = ', users.get_current_user())

depending on what you are defining author as in the Todo model. A StringProperty or UserProperty.

Note nickname is a method. You are passing the method and not the result in template values.

Difference between return and exit in Bash functions

From man bash on return [n];

Causes a function to stop executing and return the value specified by n to its caller. If n is omitted, the return status is that of the last command executed in the function body.

... on exit [n]:

Cause the shell to exit with a status of n. If n is omitted, the exit status is that of the last command executed. A trap on EXIT is executed before the shell terminates.

EDIT:

As per your edit of the question, regarding exit codes, return has nothing to do with exit codes. Exit codes are intended for applications/scripts, not functions. So in this regard, the only keyword that sets the exit code of the script (the one that can be caught by the calling program using the $? shell variable) is exit.

EDIT 2:

My last statement referring exit is causing some comments. It was made to differentiate return and exit for the understanding of the OP, and in fact, at any given point of a program/shell script, exit is the only way of ending the script with an exit code to the calling process.

Every command executed in the shell produces a local "exit code": it sets the $? variable to that code, and can be used with if, && and other operators to conditionally execute other commands.

These exit codes (and the value of the $? variable) are reset by each command execution.

Incidentally, the exit code of the last command executed by the script is used as the exit code of the script itself as seen by the calling process.

Finally, functions, when called, act as shell commands with respect to exit codes. The exit code of the function (within the function) is set by using return. So when in a function return 0 is run, the function execution terminates, giving an exit code of 0.

How to simulate a touch event in Android?

Here is a monkeyrunner script that sends touch and drags to an application. I have been using this to test that my application can handle rapid repetitive swipe gestures.

# This is a monkeyrunner jython script that opens a connection to an Android
# device and continually sends a stream of swipe and touch gestures.
#
# See http://developer.android.com/guide/developing/tools/monkeyrunner_concepts.html
#
# usage: monkeyrunner swipe_monkey.py
#

# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice

# Connects to the current device
device = MonkeyRunner.waitForConnection()

# A swipe left from (x1, y) to (x2, y) in 2 steps
y = 400
x1 = 100
x2 = 300
start = (x1, y)
end = (x2, y)
duration = 0.2
steps = 2
pause = 0.2

for i in range(1, 250):
    # Every so often inject a touch to spice things up!
    if i % 9 == 0:
        device.touch(x2, y, 'DOWN_AND_UP')
        MonkeyRunner.sleep(pause)
    # Swipe right
    device.drag(start, end, duration, steps)
    MonkeyRunner.sleep(pause)
    # Swipe left
    device.drag(end, start, duration, steps)
    MonkeyRunner.sleep(pause)

Add button to a layout programmatically

This line:

layout = (LinearLayout) findViewById(R.id.statsviewlayout);

Looks for the "statsviewlayout" id in your current 'contentview'. Now you've set that here:

setContentView(new GraphTemperature(getApplicationContext()));

And i'm guessing that new "graphTemperature" does not set anything with that id.

It's a common mistake to think you can just find any view with findViewById. You can only find a view that is in the XML (or appointed by code and given an id).

The nullpointer will be thrown because the layout you're looking for isn't found, so

layout.addView(buyButton);

Throws that exception.

addition: Now if you want to get that view from an XML, you should use an inflater:

layout = (LinearLayout) View.inflate(this, R.layout.yourXMLYouWantToLoad, null);

assuming that you have your linearlayout in a file called "yourXMLYouWantToLoad.xml"

How to use an environment variable inside a quoted string in Bash

If unsure, you might use the 'cols' request on the terminal, and forget COLUMNS:

COLS=$(tput cols)

LINQ: Distinct values

I'm a bit late to the answer, but you may want to do this if you want the whole element, not only the values you want to group by:

var query = doc.Elements("whatever")
               .GroupBy(element => new {
                             id = (int) element.Attribute("id"),
                             category = (int) element.Attribute("cat") })
               .Select(e => e.First());

This will give you the first whole element matching your group by selection, much like Jon Skeets second example using DistinctBy, but without implementing IEqualityComparer comparer. DistinctBy will most likely be faster, but the solution above will involve less code if performance is not an issue.

How can I send large messages with Kafka (over 15MB)?

Minor changes required for Kafka 0.10 and the new consumer compared to laughing_man's answer:

  • Broker: No changes, you still need to increase properties message.max.bytes and replica.fetch.max.bytes. message.max.bytes has to be equal or smaller(*) than replica.fetch.max.bytes.
  • Producer: Increase max.request.size to send the larger message.
  • Consumer: Increase max.partition.fetch.bytes to receive larger messages.

(*) Read the comments to learn more about message.max.bytes<=replica.fetch.max.bytes

CSS Background image not loading

i can bring a little help here... it seems that when you use say background-image: url("/images/image.jpg"); or background-image: url("images/image.jpg"); or background-image: url("../images/image.jpg"); different browsers appear to see this differently. the first the browser seems to see this as domain.com/images/image.jpg.... the second the browser sees at domain.com/css/images/image.jpg.... and the final the browser sees as domain.com/PathToImageFile/image.jpg... hopes this helps

Common sources of unterminated string literal

Whitespace is another issue I find, causes this error. Using a function to trim the whitespace may help.

How to get a substring of text?

Since you tagged it Rails, you can use truncate:

http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-truncate

Example:

 truncate(@text, :length => 17)

Excerpt is nice to know too, it lets you display an excerpt of a text Like so:

 excerpt('This is an example', 'an', :radius => 5)
 # => ...s is an exam...

http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-excerpt

Zero an array in C code

int arr[20] = {0};

C99 [$6.7.8/21]

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.


Aligning a button to the center

For me it worked using flexbox, which is in my opinion the cleanest solution.

Add a css class around the parent div / element with :

.parent {
display: flex;
}

and for the button use:

.button {
justify-content: center;
}

You should use a parent div, otherwise the button doesn't 'know' what the middle of the page / element is.

If this is not working, try :

#wrapper {
    display:flex;
    justify-content: center;
}

Show/Hide Table Rows using Javascript classes

Well one way to do it would be to just put a class on the "parent" rows and remove all the ids and inline onclick attributes:

<table id="products">
    <thead>
    <tr>
        <th>Product</th>
        <th>Price</th>
        <th>Destination</th>
        <th>Updated on</th>
    </tr>
    </thead>
    <tbody>
    <tr class="parent">
        <td>Oranges</td>
        <td>100</td>
        <td><a href="#">+ On Store</a></td>
        <td>22/10</td>
    </tr>
    <tr>
        <td></td>
        <td>120</td>
        <td>City 1</td>
        <td>22/10</td>
    </tr>
    <tr>
        <td></td>
        <td>140</td>
        <td>City 2</td>
        <td>22/10</td>
    </tr>
    ...etc.
    </tbody>
</table>

And then have some CSS that hides all non-parents:

tbody tr {
    display : none;          // default is hidden
}
tr.parent {
    display : table-row;     // parents are shown
}
tr.open {
    display : table-row;     // class to be given to "open" child rows
}

That greatly simplifies your html. Note that I've added <thead> and <tbody> to your markup to make it easy to hide data rows and ignore heading rows.

With jQuery you can then simply do this:

// when an anchor in the table is clicked
$("#products").on("click","a",function(e) {
    // prevent default behaviour
    e.preventDefault();
    // find all the following TR elements up to the next "parent"
    // and toggle their "open" class
    $(this).closest("tr").nextUntil(".parent").toggleClass("open");
});

Demo: http://jsfiddle.net/CBLWS/1/

Or, to implement something like that in plain JavaScript, perhaps something like the following:

document.getElementById("products").addEventListener("click", function(e) {
    // if clicked item is an anchor
    if (e.target.tagName === "A") {
        e.preventDefault();
        // get reference to anchor's parent TR
        var row = e.target.parentNode.parentNode;
        // loop through all of the following TRs until the next parent is found
        while ((row = nextTr(row)) && !/\bparent\b/.test(row.className))
            toggle_it(row);
    }
});

function nextTr(row) {
    // find next sibling that is an element (skip text nodes, etc.)
    while ((row = row.nextSibling) && row.nodeType != 1);
    return row;
}

function toggle_it(item){ 
     if (/\bopen\b/.test(item.className))       // if item already has the class
         item.className = item.className.replace(/\bopen\b/," "); // remove it
     else                                       // otherwise
         item.className += " open";             // add it
}

Demo: http://jsfiddle.net/CBLWS/

Either way, put the JavaScript in a <script> element that is at the end of the body, so that it runs after the table has been parsed.

TransactionRequiredException Executing an update/delete query

I am not sure if this will help your situation (that is if it stills exists), however, after scouring the web for a similar issue.

I was creating a native query from a persistence EntityManager to perform an update.

Query query = entityManager.createNativeQuery(queryString);

I was receiving the following error:

caused by: javax.persistence.TransactionRequiredException: Executing an update/delete query

Many solutions suggest adding @Transactional to your method. Just doing this did not change the error.

Some solutions suggest asking the EntityManager for a EntityTransaction so that you can call begin and commit yourself. This throws another error:

caused by: java.lang.IllegalStateException: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead

I then tried a method which most sites say is for use application managed entity managers and not container managed (which I believe Spring is) and that was joinTransaction().

Having @Transactional decorating the method and then calling joinTransaction() on EntityManager object just prior to calling query.executeUpdate() and my native query update worked.

I hope this helps someone else experiencing this issue.

Android global variable

There are a few different ways you can achieve what you are asking for.

1.) Extend the application class and instantiate your controller and model objects there.

public class FavoriteColorsApplication extends Application {

    private static FavoriteColorsApplication application;
    private FavoriteColorsService service;

    public FavoriteColorsApplication getInstance() {
        return application;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        application = this;
        application.initialize();
    }

    private void initialize() {
        service = new FavoriteColorsService();
    }

    public FavoriteColorsService getService() {
        return service;
    }

}

Then you can call the your singleton from your custom Application object at any time:

public class FavoriteColorsActivity extends Activity {

private FavoriteColorsService service = null;
private ArrayAdapter<String> adapter;
private List<String> favoriteColors = new ArrayList<String>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_favorite_colors);

    service = ((FavoriteColorsApplication) getApplication()).getService();
    favoriteColors = service.findAllColors();

    ListView lv = (ListView) findViewById(R.id.favoriteColorsListView);
    adapter = new ArrayAdapter<String>(this, R.layout.favorite_colors_list_item,
            favoriteColors);
    lv.setAdapter(adapter);
}

2.) You can have your controller just create a singleton instance of itself:

public class Controller {
    private static final String TAG = "Controller";
    private static sController sController;
    private Dao mDao;

    private Controller() {
        mDao = new Dao();    
    }

    public static Controller create() {
        if (sController == null) {
            sController = new Controller();
        }
        return sController;
    }
}

Then you can just call the create method from any Activity or Fragment and it will create a new controller if one doesn't already exist, otherwise it will return the preexisting controller.

3.) Finally, there is a slick framework created at Square which provides you dependency injection within Android. It is called Dagger. I won't go into how to use it here, but it is very slick if you need that sort of thing.

I hope I gave enough detail in regards to how you can do what you are hoping for.

Fastest way to copy a file in Node.js

Same mechanism, but this adds error handling:

function copyFile(source, target, cb) {
  var cbCalled = false;

  var rd = fs.createReadStream(source);
  rd.on("error", function(err) {
    done(err);
  });
  var wr = fs.createWriteStream(target);
  wr.on("error", function(err) {
    done(err);
  });
  wr.on("close", function(ex) {
    done();
  });
  rd.pipe(wr);

  function done(err) {
    if (!cbCalled) {
      cb(err);
      cbCalled = true;
    }
  }
}

Subtract two dates in SQL and get days of the result

How about

Select I.Fee
From Item I
WHERE  (days(GETDATE()) - days(I.DateCreated) < 365)

justify-content property isn't working

Screenshot

Go to inspect element and check if .justify-content-center is listed as a class name under 'Styles' tab. If not, probably you are using bootstrap v3 in which justify-content-center is not defined.

If so, please update bootstrap, worked for me.

C# Change A Button's Background Color

WinForm:

private void button1_Click(object sender, EventArgs e)
{
   button2.BackColor = Color.Red;
}

WPF:

private void button1_Click(object sender, RoutedEventArgs e)
{
   button2.Background = Brushes.Blue;
}

Java: Calculating the angle between two points in degrees

Based on Saad Ahmed's answer, here is a method that can be used for any two points.

public static double calculateAngle(double x1, double y1, double x2, double y2)
{
    double angle = Math.toDegrees(Math.atan2(x2 - x1, y2 - y1));
    // Keep angle between 0 and 360
    angle = angle + Math.ceil( -angle / 360 ) * 360;

    return angle;
}

How to debug Angular JavaScript Code

Maybe you can use Angular Augury A Google Chrome Dev Tools extension for debugging Angular 2 and above applications.

How to send email via Django?

My site is hosted on Godaddy and I have a private email registered on the same. These are the settings which worked for me:

In settings.py:

EMAIL_HOST = 'mail.domain.com'
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'abcdef'
DEFAULT_FROM_EMAIL = '[email protected]'
SERVER_EMAIL = '[email protected]'
EMAIL_PORT = 25
EMAIL_USE_TLS = False

In shell:

from django.core.mail import EmailMessage
email = EmailMessage('Subject', 'Body', to=['[email protected]'])
email.send()

Then I got "1" as the O/P i.e. Success. And I received the mail too. :)

  • What is the meaning of domain.com?

Swift 3: Display Image from URL

Using Alamofire worked out for me on Swift 3:

Step 1:

Integrate using pods.

pod 'Alamofire', '~> 4.4'

pod 'AlamofireImage', '~> 3.3'

Step 2:

import AlamofireImage

import Alamofire

Step 3:

Alamofire.request("https://httpbin.org/image/png").responseImage { response in

if let image = response.result.value {
    print("image downloaded: \(image)")
self.myImageview.image = image
}
}

Prevent scroll-bar from adding-up to the Width of page on Chrome

Probably

html {
    width: 100vw;
}

is just what you want.

How to pass props to {this.props.children}

Method 1 - clone children

const Parent = (props) => {
   const attributeToAddOrReplace= "Some Value"
   const childrenWithAdjustedProps = React.Children.map(props.children, child =>
      React.cloneElement(child, { attributeToAddOrReplace})
   );

   return <div>{childrenWithAdjustedProps }</div>
}

Method 2 - use composable context

Context allows you to pass a prop to a deep child component without explicitly passing it as a prop through the components in between.

Context comes with drawbacks:

  1. Data doesn't flow in the regular way - via props.
  2. Using context creates a contract between the consumer and the provider. It might be more difficult to understand and replicate the requirements needed to reuse a component.

Using a composable context

export const Context = createContext<any>(null);

export const ComposableContext = ({ children, ...otherProps }:{children:ReactNode, [x:string]:any}) => {
    const context = useContext(Context)
    return(
      <Context.Provider {...context} value={{...context, ...otherProps}}>{children}</Context.Provider>
    );
}

function App() {
  return (
      <Provider1>
            <Provider2> 
                <Displayer />
            </Provider2>
      </Provider1>
  );
}

const Provider1 =({children}:{children:ReactNode}) => (
    <ComposableContext greeting="Hello">{children}</ComposableContext>
)

const Provider2 =({children}:{children:ReactNode}) => (
    <ComposableContext name="world">{children}</ComposableContext>
)

const Displayer = () => {
  const context = useContext(Context);
  return <div>{context.greeting}, {context.name}</div>;
};

What is the alternative for ~ (user's home directory) on Windows command prompt?

You can also do cd ......\ as many times as there are folders that takes you to home directory. For example, if you are in cd:\windows\syatem32, then cd ....\ takes you to the home, that is c:\

How to make a SIMPLE C++ Makefile

I've always thought this was easier to learn with a detailed example, so here's how I think of makefiles. For each section you have one line that's not indented and it shows the name of the section followed by dependencies. The dependencies can be either other sections (which will be run before the current section) or files (which if updated will cause the current section to be run again next time you run make).

Here's a quick example (keep in mind that I'm using 4 spaces where I should be using a tab, Stack Overflow won't let me use tabs):

a3driver: a3driver.o
    g++ -o a3driver a3driver.o

a3driver.o: a3driver.cpp
    g++ -c a3driver.cpp

When you type make, it will choose the first section (a3driver). a3driver depends on a3driver.o, so it will go to that section. a3driver.o depends on a3driver.cpp, so it will only run if a3driver.cpp has changed since it was last run. Assuming it has (or has never been run), it will compile a3driver.cpp to a .o file, then go back to a3driver and compile the final executable.

Since there's only one file, it could even be reduced to:

a3driver: a3driver.cpp
    g++ -o a3driver a3driver.cpp

The reason I showed the first example is that it shows the power of makefiles. If you need to compile another file, you can just add another section. Here's an example with a secondFile.cpp (which loads in a header named secondFile.h):

a3driver: a3driver.o secondFile.o
    g++ -o a3driver a3driver.o secondFile.o

a3driver.o: a3driver.cpp
    g++ -c a3driver.cpp

secondFile.o: secondFile.cpp secondFile.h
    g++ -c secondFile.cpp

This way if you change something in secondFile.cpp or secondFile.h and recompile, it will only recompile secondFile.cpp (not a3driver.cpp). Or alternately, if you change something in a3driver.cpp, it won't recompile secondFile.cpp.

Let me know if you have any questions about it.

It's also traditional to include a section named "all" and a section named "clean". "all" will usually build all of the executables, and "clean" will remove "build artifacts" like .o files and the executables:

all: a3driver ;

clean:
    # -f so this will succeed even if the files don't exist
    rm -f a3driver a3driver.o

EDIT: I didn't notice you're on Windows. I think the only difference is changing the -o a3driver to -o a3driver.exe.

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve

I had this issue with offline mode enable. I disabled offline mode and synced.

  • Open the Preferences, by clicking File > Settings.
  • In the left pane, click Build, Execution, Deployment > Gradle.
  • Uncheck the Offline work.
  • Apply changes and sync project again.

How to use setInterval and clearInterval?

clearInterval is one option:

var interval = setInterval(doStuff, 2000); // 2000 ms = start after 2sec 
function doStuff() {
  alert('this is a 2 second warning');
  clearInterval(interval);
}

How do I get console input in javascript?

As you mentioned, prompt works for browsers all the way back to IE:

var answer = prompt('question', 'defaultAnswer');

prompt in IE

For Node.js > v7.6, you can use console-read-write, which is a wrapper around the low-level readline module:

const io = require('console-read-write');

async function main() {
  // Simple readline scenario
  io.write('I will echo whatever you write!');
  io.write(await io.read());

  // Simple question scenario
  io.write(`hello ${await io.ask('Who are you?')}!`);

  // Since you are not blocking the IO, you can go wild with while loops!
  let saidHi = false;
  while (!saidHi) {
    io.write('Say hi or I will repeat...');
    saidHi = await io.read() === 'hi';
  }

  io.write('Thanks! Now you may leave.');
}

main();
// I will echo whatever you write!
// > ok
// ok
// Who are you? someone
// hello someone!
// Say hi or I will repeat...
// > no
// Say hi or I will repeat...
// > ok
// Say hi or I will repeat...
// > hi
// Thanks! Now you may leave.

Disclosure I'm author and maintainer of console-read-write

For SpiderMonkey, simple readline as suggested by @MooGoo and @Zaz.

iOS Launching Settings -> Restrictions URL Scheme

Works Fine for App Notification settings on IOS 10 (tested)

if(&UIApplicationOpenSettingsURLString != nil){
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}

Setting the default ssh key location

If you are only looking to point to a different location for you identity file, the you can modify your ~/.ssh/config file with the following entry:

IdentityFile ~/.foo/identity

man ssh_config to find other config options.

How do I do redo (i.e. "undo undo") in Vim?

Practically speaking, the :undolist is hard to use and Vim’s :earlier and :later time tracking of changes is only usable for course-grain fixes.

Given that, I resort to a plug-in that combines these features to provide a visual tree of browsable undos, called “Gundo.”

Obviously, this is something to use only when you need a fine-grained fix, or you are uncertain of the exact state of the document you wish to return to. See: Gundo. Graph your Vim undo tree in style

Getting command-line password input in Python

15.7. getpass — Portable password input

#!/usr/bin/python3
from getpass import getpass
passwd = getpass("password: ")
print(passwd)

You can read more here

How can I write a regex which matches non greedy?

The other answers here presuppose that you have a regex engine which supports non-greedy matching, which is an extension introduced in Perl 5 and widely copied to other modern languages; but it is by no means ubiquitous.

Many older or more conservative languages and editors only support traditional regular expressions, which have no mechanism for controlling greediness of the repetition operator * - it always matches the longest possible string.

The trick then is to limit what it's allowed to match in the first place. Instead of .* you seem to be looking for

[^>]*

which still matches as many of something as possible; but the something is not just . "any character", but instead "any character which isn't >".

Depending on your application, you may or may not want to enable an option to permit "any character" to include newlines.

Even if your regular expression engine supports non-greedy matching, it's better to spell out what you actually mean. If this is what you mean, you should probably say this, instead of rely on non-greedy matching to (hopefully, probably) Do What I Mean.

For example, a regular expression with a trailing context after the wildcard like .*?><br/> will jump over any nested > until it finds the trailing context (here, ><br/>) even if that requires straddling multiple > instances and newlines if you let it, where [^>]*><br/> (or even [^\n>]*><br/> if you have to explicitly disallow newline) obviously can't and won't do that.

Of course, this is still not what you want if you need to cope with <img title="quoted string with > in it" src="other attributes"> and perhaps <img title="nested tags">, but at that point, you should finally give up on using regular expressions for this like we all told you in the first place.

How do you run a single query through mysql from the command line?

here's how you can do it with a cool shell trick:

mysql -uroot -p -hslavedb.mydomain.com mydb_production <<< 'select * from users'

'<<<' instructs the shell to take whatever follows it as stdin, similar to piping from echo.

use the -t flag to enable table-format output

MySQL - SELECT WHERE field IN (subquery) - Extremely slow why?

The subquery is being run for each row because it is a correlated query. One can make a correlated query into a non-correlated query by selecting everything from the subquery, like so:

SELECT * FROM
(
    SELECT relevant_field
    FROM some_table
    GROUP BY relevant_field
    HAVING COUNT(*) > 1
) AS subquery

The final query would look like this:

SELECT *
FROM some_table
WHERE relevant_field IN
(
    SELECT * FROM
    (
        SELECT relevant_field
        FROM some_table
        GROUP BY relevant_field
        HAVING COUNT(*) > 1
    ) AS subquery
)

A url resource that is a dot (%2E)

It's actually not really clearly stated in the standard (RFC 3986) whether a percent-encoded version of . or .. is supposed to have the same this-folder/up-a-folder meaning as the unescaped version. Section 3.3 only talks about “The path segments . and ..”, without clarifying whether they match . and .. before or after pct-encoding.

Personally I find Firefox's interpretation that %2E does not mean . most practical, but unfortunately all the other browsers disagree. This would mean that you can't have a path component containing only . or ...

I think the only possible suggestion is “don't do that”! There are other path components that are troublesome too, typically due to server limitations: %2F, %00 and %5C sequences in paths may also be blocked by some web servers, and the empty path segment can also cause problems. So in general it's not possible to fit all possible byte sequences into a path component.

Oracle insert if not exists statement

MERGE INTO OPT
USING
    (SELECT 1 "one" FROM dual) 
ON
    (OPT.email= '[email protected]' and OPT.campaign_id= 100) 
WHEN NOT matched THEN
INSERT (email, campaign_id)
VALUES ('[email protected]',100) 
;

What does it mean with bug report captured in android tablet?

It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.

Edit: This is what the forums say:

By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.

To disable:

/system/bin/bugmailer.sh must be deleted/renamed.

There should be a folder on your SD card called "bug reports".

Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948

And this one: http://forum.xda-developers.com/showthread.php?t=1405639

How do synchronized static methods work in Java and can I use it for loading Hibernate entities?

If it is something to do with the data in your database, why not utilize database isolation locking to achieve?

How to center an element in the middle of the browser window?

Hope this helps. Trick is to use absolute positioning and configure the top and left columns. Of course "dead center" will depend on the size of the object/div you are embedding, so you will need to do some work. For a login window I used the following - it also has some safety with max-width and max-height that may actually be of use to you in your example. Configure the values below to your requirement.

div#wrapper {
    border: 0;
    width: 65%;
    text-align: left;
    position: absolute;
    top:  20%;
    left: 18%;
    height: 50%;
    min-width: 600px;
    max-width: 800px;
}

calling a function from class in python - different way

Your methods don't refer to an object (that is, self), so you should use the @staticmethod decorator:

class MathsOperations:
    @staticmethod
    def testAddition (x, y):
        return x + y

    @staticmethod
    def testMultiplication (a, b):
        return a * b

How to Solve the XAMPP 1.7.7 - PHPMyAdmin - MySQL Error #2002 in Ubuntu

  1. Open config.default.php file under phpmyadmin/libraries/
  2. Find $cfg['Servers'][$i]['host'] = 'localhost'; Change to $cfg['Servers'][$i]['host'] = '127.0.0.1';
  3. refresh your phpmyadmin page, login

Initialization of an ArrayList in one line

If you need a simple list of size 1:

List<String> strings = new ArrayList<String>(Collections.singletonList("A"));

If you need a list of several objects:

List<String> strings = new ArrayList<String>();
Collections.addAll(strings,"A","B","C","D");

Java regex email

Modification of Armer B. answer which didn't validate emails ending with '.co.uk'

public static boolean emailValidate(String email) {
    Matcher matcher = Pattern.compile("^([\\w-\\.]+){1,64}@([\\w&&[^_]]+){2,255}(.[a-z]{2,3})+$|^$", Pattern.CASE_INSENSITIVE).matcher(email);

    return matcher.find();
}

tell pip to install the dependencies of packages listed in a requirement file

Given your comment to the question (where you say that executing the install for a single package works as expected), I would suggest looping over your requirement file. In bash:

#!/bin/sh
while read p; do
  pip install $p
done < requirements.pip

HTH!

adb connection over tcp not working now

Thanks to sud007 for this answer. In my case, I only need this part of the solution:

In CMD/Terminal:

$ adb kill-server

$ adb tcpip 5555
restarting in TCP mode port: 5555

$ adb connect 192.168.XXX.XXX

This bug brings more errors than unable to connect to 192.168.XXX.XXX:5555: Connection refused. In my case, I could connect to the device, but when you try to run the app. AndroidStudio stay in Installing APK forever. In this case, I needed to restart the phone too.

How to measure height, width and distance of object using camera?

First of all i will say Nice Thaught to develop such app.

Now i am not sure about it, but if you can able to get the face-detection like thing for any object in android camera so with help of that you can achieve that things.

Well i am not sure about it but still have give some view so you can get idea of it.

All the Best. :))

Convert a List<T> into an ObservableCollection<T>

The Observable Collection constructor will take an IList or an IEnumerable.

If you find that you are going to do this a lot you can make a simple extension method:

    public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> enumerable)
    {
        return new ObservableCollection<T>(enumerable);
    }

How to compile .c file with OpenSSL includes?

If the OpenSSL headers are in the openssl sub-directory of the current directory, use:

gcc -I. -o Opentest Opentest.c -lcrypto

The pre-processor looks to create a name such as "./openssl/ssl.h" from the "." in the -I option and the name specified in angle brackets. If you had specified the names in double quotes (#include "openssl/ssl.h"), you might never have needed to ask the question; the compiler on Unix usually searches for headers enclosed in double quotes in the current directory automatically, but it does not do so for headers enclosed in angle brackets (#include <openssl/ssl.h>). It is implementation defined behaviour.

You don't say where the OpenSSL libraries are - you might need to add an appropriate option and argument to specify that, such as '-L /opt/openssl/lib'.

PHP: Inserting Values from the Form into MySQL

<!DOCTYPE html>
<?php
$con = new mysqli("localhost","root","","form");

?>



<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript">
$(document).ready(function(){
 //$("form").submit(function(e){

     $("#btn1").click(function(e){
     e.preventDefault();
    // alert('here');
        $(".apnew").append('<input type="text" placeholder="Enter youy Name" name="e1[]"/><br>');

    });
    //}
});
</script>

</head>

<body>
<h2><b>Register Form<b></h2>
<form method="post" enctype="multipart/form-data">
<table>
<tr><td>Name:</td><td><input type="text" placeholder="Enter youy Name" name="e1[]"/>
<div class="apnew"></div><button id="btn1">Add</button></td></tr>
<tr><td>Image:</td><td><input type="file"  name="e5[]" multiple="" accept="image/jpeg,image/gif,image/png,image/jpg"/></td></tr>

<tr><td>Address:</td><td><textarea  cols="20" rows="4" name="e2"></textarea></td></tr>
<tr><td>Contact:</td><td><div id="textnew"><input  type="number"  maxlength="10" name="e3"/></div></td></tr>
<tr><td>Gender:</td><td><input type="radio"  name="r1" value="Male" checked="checked"/>Male<input type="radio"  name="r1" value="feale"/>Female</td></tr>
<tr><td><input  id="submit" type="submit" name="t1" value="save" /></td></tr>
</table>
<?php
//echo '<pre>';print_r($_FILES);exit();
if(isset($_POST['t1']))
{
$values = implode(", ", $_POST['e1']);
$imgarryimp=array();
foreach($_FILES["e5"]["tmp_name"] as $key=>$val){


move_uploaded_file($_FILES["e5"]["tmp_name"][$key],"images/".$_FILES["e5"]["name"][$key]);

                     $fname = $_FILES['e5']['name'][$key];
                     $imgarryimp[]=$fname;
                     //echo $fname;

                     if(strlen($fname)>0)
                      {
                         $img = $fname;
                      }
                      $d="insert into form(name,address,contact,gender,image)values('$values','$_POST[e2]','$_POST[e3]','$_POST[r1]','$img')";

       if($con->query($d)==TRUE)
         {
         echo "Yoy Data Save Successfully!!!";
         }
}
exit;





                      // echo $values;exit;
                      //foreach($_POST['e1'] as $row) 
    //{ 

    $d="insert into form(name,address,contact,gender,image)values('$values','$_POST[e2]','$_POST[e3]','$_POST[r1]','$img')";

       if($con->query($d)==TRUE)
         {
         echo "Yoy Data Save Successfully!!!";
         }
    //}
    //exit;


}
?>

</form>

<table>
<?php 
$t="select * from form";
$y=$con->query($t);
foreach ($y as $q);
{
?>
<tr>
<td>Name:<?php echo $q['name'];?></td>
<td>Address:<?php echo $q['address'];?></td>
<td>Contact:<?php echo $q['contact'];?></td>
<td>Gender:<?php echo $q['gender'];?></td>
</tr>
<?php }?>
</table>

</body>
</html>

How to pass a value from one Activity to another in Android?

Its simple If you are passing String X from A to B.
A--> B

In Activity A
1) Create Intent
2) Put data in intent using putExtra method of intent
3) Start activity

Intent i = new Intent(A.this, B.class);
i.putExtra("MY_kEY",X);

In Activity B
inside onCreate method
1) Get intent object
2) Get stored value using key(MY_KEY)

Intent intent = getIntent();
String result = intent.getStringExtra("MY_KEY");

This is the standard way to send data from A to B. you can send any data type, it could be int, boolean, ArrayList, String[]. Based on the datatype you stored in Activity as key, value pair retrieving method might differ like if you are passing int value then you will call

intent.getIntExtra("KEY");

You can even send Class objects too but for that, you have to make your class object implement the Serializable or Parceable interface.

TransactionTooLargeException

How much data you can send across size. If data exceeds a certain amount in size then you might get TransactionTooLargeException. Suppose you are trying to send bitmap across the activity and if the size exceeds certain data size then you might see this exception.

System.web.mvc missing

I have the same situation: Visual Studio 2010, no NuGet installed, and an ASP.NET application using System.Web.Mvc version 3.

What worked for me, was to set each C# project that uses System.Web.Mvc, to go to References in the Solution Explorer, and set properties on System.Web.Mvc, with Copy Local to true, and Specific Version to false - the last one caused the Version field to show the current version on that machine.

Math constant PI value in C

The closest thing C does to "computing p" in a way that's directly visible to applications is acos(-1) or similar. This is almost always done with polynomial/rational approximations for the function being computed (either in C, or by the FPU microcode).

However, an interesting issue is that computing the trigonometric functions (sin, cos, and tan) requires reduction of their argument modulo 2p. Since 2p is not a diadic rational (and not even rational), it cannot be represented in any floating point type, and thus using any approximation of the value will result in catastrophic error accumulation for large arguments (e.g. if x is 1e12, and 2*M_PI differs from 2p by e, then fmod(x,2*M_PI) differs from the correct value of 2p by up to 1e12*e/p times the correct value of x mod 2p. That is to say, it's completely meaningless.

A correct implementation of C's standard math library simply has a gigantic very-high-precision representation of p hard coded in its source to deal with the issue of correct argument reduction (and uses some fancy tricks to make it not-quite-so-gigantic). This is how most/all C versions of the sin/cos/tan functions work. However, certain implementations (like glibc) are known to use assembly implementations on some cpus (like x86) and don't perform correct argument reduction, leading to completely nonsensical outputs. (Incidentally, the incorrect asm usually runs about the same speed as the correct C code for small arguments.)

Combine two tables for one output

You'll need to use UNION to combine the results of two queries. In your case:

SELECT ChargeNum, CategoryID, SUM(Hours)
FROM KnownHours
GROUP BY ChargeNum, CategoryID
UNION ALL
SELECT ChargeNum, 'Unknown' AS CategoryID, SUM(Hours)
FROM UnknownHours
GROUP BY ChargeNum

Note - If you use UNION ALL as in above, it's no slower than running the two queries separately as it does no duplicate-checking.

Handler vs AsyncTask vs Thread

Thread:

You can use the new Thread for long-running background tasks without impacting UI Thread. From java Thread, you can't update UI Thread.

Since normal Thread is not much useful for Android architecture, helper classes for threading have been introduced.

You can find answers to your queries in Threading performance documentation page.

Handler:

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue.

There are two main uses for a Handler:

  1. To schedule messages and runnables to be executed as some point in the future;

  2. To enqueue an action to be performed on a different thread than your own.

AsyncTask:

AsyncTask enables proper and easy use of the UI thread. This class allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

Drawbacks:

  1. By default, an app pushes all of the AsyncTask objects it creates into a single thread. Therefore, they execute in serial fashion, and—as with the main thread—an especially long work packet can block the queue. Due to this reason, use AsyncTask to handle work items shorter than 5ms in duration.

  2. AsyncTask objects are also the most common offenders for implicit-reference issues. AsyncTask objects present risks related to explicit references, as well.

HandlerThread:

You may need a more traditional approach to executing a block of work on a long-running thread (unlike AsyncTask, which should be used for 5ms workload), and some ability to manage that workflow manually. A handler thread is effectively a long-running thread that grabs work from a queue and operates on it.

ThreadPoolExecutor:

This class manages the creation of a group of threads, sets their priorities, and manages how work is distributed among those threads. As workload increases or decreases, the class spins up or destroys more threads to adjust to the workload.

If the workload is more and single HandlerThread is not suffice, you can go for ThreadPoolExecutor

However I would like to have a socket connection run in service. Should this be run in a handler or a thread, or even an AsyncTask? UI interaction is not necessary at all. Does it make a difference in terms of performance which I use?

Since UI interaction is not required, you may not go for AsyncTask. Normal threads are not much useful and hence HandlerThread is the best option. Since you have to maintain socket connection, Handler on the main thread is not useful at all. Create a HandlerThread and get a Handler from the looper of HandlerThread.

 HandlerThread handlerThread = new HandlerThread("SocketOperation");
 handlerThread.start();
 Handler requestHandler = new Handler(handlerThread.getLooper());
 requestHandler.post(myRunnable); // where myRunnable is your Runnable object. 

If you want to communicate back to UI thread, you can use one more Handler to process response.

final Handler responseHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            //txtView.setText((String) msg.obj);
            Toast.makeText(MainActivity.this,
                    "Foreground task is completed:"+(String)msg.obj,
                    Toast.LENGTH_LONG)
                    .show();
        }
    };

in your Runnable, you can add

responseHandler.sendMessage(msg);

More details about implementation can be found here:

Android: Toast in a thread

Restful API service

Lets say I want to start the service on an event - onItemClicked() of a button. The Receiver mechanism would not work in that case because :-
a) I passed the Receiver to the service (as in Intent extra) from onItemClicked()
b) Activity moves to the background. In onPause() I set the receiver reference within the ResultReceiver to null to avoid leaking the Activity.
c) Activity gets destroyed.
d) Activity gets created again. However at this point the Service will not be able to make a callback to the Activity as that receiver reference is lost.
The mechanism of a limited broadcast or a PendingIntent seems to be more usefull in such scenarios- refer to Notify activity from service

Kill some processes by .exe file name

Quick Answer:

foreach (var process in Process.GetProcessesByName("whatever"))
{
    process.Kill();
}

(leave off .exe from process name)

Allowing Java to use an untrusted certificate for SSL/HTTPS connection

Another option is to get a ".pem" (public key) file for that particular server, and install it locally into the heart of your JRE's "cacerts" file (use the keytool helper application), then it will be able to download from that server without complaint, without compromising the entire SSL structure of your running JVM and enabling download from other unknown cert servers...

How to view the SQL queries issued by JPA?

EclipseLink to output the SQL(persistence.xml config):

<property name="eclipselink.logging.level.sql" value="FINE" />

Correct way of looping through C++ arrays

string texts[] = {"Apple", "Banana", "Orange"};
for( unsigned int a = 0; a < sizeof(texts); a = a + 1 )
{
    cout << "value of a: " << texts[a] << endl;
}

Nope. Totally a wrong way of iterating through an array. sizeof(texts) is not equal to the number of elements in the array!

The modern, C++11 ways would be to:

  • use std::array if you want an array whose size is known at compile-time; or
  • use std::vector if its size depends on runtime

Then use range-for when iterating.

#include <iostream>
#include <array>


int main() {
    std::array<std::string, 3> texts = {"Apple", "Banana", "Orange"};
    // ^ An array of 3 elements with the type std::string

    for(const auto& text : texts) {   // Range-for!
        std::cout << text << std::endl;
    }
}

Live example


You may ask, how is std::array better than the ol' C array? The answer is that it has the additional safety and features of other standard library containers, mostly closely resembling std::vector. Further, The answer is that it doesn't have the quirks of decaying to pointers and thus losing type information, which, once you lose the original array type, you can't use range-for or std::begin/end on it.

What's the difference between console.dir and console.log?

From the firebug site http://getfirebug.com/logging/

Calling console.dir(object) will log an interactive listing of an object's properties, like > a miniature version of the DOM tab.

How to remove padding around buttons in Android?

That's not padding, it's the shadow around the button in its background drawable. Create your own background and it will disappear.

How to make external HTTP requests with Node.js

You can use the built-in http module to do an http.request().

However if you want to simplify the API you can use a module such as superagent

Using Mockito to mock classes with generic parameters

Here is an interesting case: method receieves generic collection and returns generic collection of same base type. For example:

Collection<? extends Assertion> map(Collection<? extends Assertion> assertions);

This method can be mocked with combination of Mockito anyCollectionOf matcher and the Answer.

when(mockedObject.map(anyCollectionOf(Assertion.class))).thenAnswer(
     new Answer<Collection<Assertion>>() {
         @Override
         public Collection<Assertion> answer(InvocationOnMock invocation) throws Throwable {
             return new ArrayList<Assertion>();
         }
     });

How to navigate back to the last cursor position in Visual Studio Code?

?+U Undo last cursor operation

You can also try ctrl+-

BTW all the shortcuts is here https://code.visualstudio.com/shortcuts/keyboard-shortcuts-macos.pdf This is really useful!

HTML select drop-down with an input field

You can use input text with "list" attribute, which refers to the datalist of values.

_x000D_
_x000D_
<input type="text" name="city" list="cityname">_x000D_
    <datalist id="cityname">_x000D_
      <option value="Boston">_x000D_
      <option value="Cambridge">_x000D_
    </datalist>
_x000D_
_x000D_
_x000D_

This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist

Formatting DataBinder.Eval data

After some searching on the Internet I found that it is in fact very much possible to call a custom method passing the DataBinder.Eval value.

The custom method can be written in the code behind file, but has to be declared public or protected. In my question above, I had mentioned that I tried to write the custom method in the code behind but was getting a run time error. The reason for this was that I had declared the method to be private.

So, in summary the following is a good way to use DataBinder.Eval value to get your desired output:

default.aspx

<asp:Label ID="lblNewsDate" runat="server" Text='<%# GetDateInHomepageFormat(DataBinder.Eval(Container.DataItem, "publishedDate")) )%>'></asp:Label>

default.aspx.cs code:

public partial class _Default : System.Web.UI.Page
{

    protected string GetDateInHomepageFormat(DateTime d)
    {

        string retValue = "";

        // Do all processing required and return value

        return retValue;
    }
}

Hope this helps others as well.

Relative path in HTML

You say your website is in http://localhost/mywebsite, and let's say that your image is inside a subfolder named pictures/:

Absolute path

If you use an absolute path, / would point to the root of the site, not the root of the document: localhost in your case. That's why you need to specify your document's folder in order to access the pictures folder:

"/mywebsite/pictures/picture.png"

And it would be the same as:

"http://localhost/mywebsite/pictures/picture.png"

Relative path

A relative path is always relative to the root of the document, so if your html is at the same level of the directory, you'd need to start the path directly with your picture's directory name:

"pictures/picture.png"

But there are other perks with relative paths:

dot-slash (./)

Dot (.) points to the same directory and the slash (/) gives access to it:

So this:

"pictures/picture.png"

Would be the same as this:

"./pictures/picture.png"

Double-dot-slash (../)

In this case, a double dot (..) points to the upper directory and likewise, the slash (/) gives you access to it. So if you wanted to access a picture that is on a directory one level above of the current directory your document is, your URL would look like this:

"../picture.png"

You can play around with them as much as you want, a little example would be this:

Let's say you're on directory A, and you want to access directory X.

- root
   |- a
      |- A
   |- b
   |- x
      |- X

Your URL would look either:

Absolute path

"/x/X/picture.png"

Or:

Relative path

"./../x/X/picture.png"

How can I make an svg scale with its parent container?

Adjusting the currentScale attribute works in IE ( I tested with IE 11), but not in Chrome.

How to get the <html> tag HTML with JavaScript / jQuery?

if you want to get an attribute of an HTML element with jQuery you can use .attr();

so $('html').attr('someAttribute'); will give you the value of someAttribute of the element html

http://api.jquery.com/attr/

Additionally:

there is a jQuery plugin here: http://plugins.jquery.com/project/getAttributes

that allows you to get all attributes from an HTML element

Use different Python version with virtualenv

The -p approach works well, but you do have to remember to use it every time. If your goal is to switch to a newer version of Python generally, that's a pain and can also lead to mistakes.

Your other option is to set an environment variable that does the same thing as -p. Set this via your ~/.bashrc file or wherever you manage environment variables for your login sessions:

export VIRTUALENV_PYTHON=/path/to/desired/version

Then virtualenv will use that any time you don't specify -p on the command line.

ReactJS call parent method

2019 Update with react 16+ and ES6

Posting this since React.createClass is deprecated from react version 16 and the new Javascript ES6 will give you more benefits.

Parent

import React, {Component} from 'react';
import Child from './Child';
  
export default class Parent extends Component {

  es6Function = (value) => {
    console.log(value)
  }

  simplifiedFunction (value) {
    console.log(value)
  }

  render () {
  return (
    <div>
    <Child
          es6Function = {this.es6Function}
          simplifiedFunction = {this.simplifiedFunction} 
        />
    </div>
    )
  }

}

Child

import React, {Component} from 'react';

export default class Child extends Component {

  render () {
  return (
    <div>
    <h1 onClick= { () =>
            this.props.simplifiedFunction(<SomethingThatYouWantToPassIn>)
          }
        > Something</h1>
    </div>
    )
  }
}

Simplified stateless child as ES6 constant

import React from 'react';

const Child = () => {
  return (
    <div>
    <h1 onClick= { () =>
        this.props.es6Function(<SomethingThatYouWantToPassIn>)
      }
      > Something</h1>
    </div>
  )

}
export default Child;

Track a new remote branch created on GitHub

If you don't have an existing local branch, it is truly as simple as:

git fetch
git checkout <remote-branch-name>

For instance if you fetch and there is a new remote tracking branch called origin/feature/Main_Page, just do this:

git checkout feature/Main_Page

This creates a local branch with the same name as the remote branch, tracking that remote branch. If you have multiple remotes with the same branch name, you can use the less ambiguous:

git checkout -t <remote>/<remote-branch-name>

If you already made the local branch and don't want to delete it, see How do you make an existing Git branch track a remote branch?.

show all tags in git log

Note about tag of tag (tagging a tag), which is at the origin of your issue, as Charles Bailey correctly pointed out in the comment:

Make sure you study this thread, as overriding a signed tag is not as easy:

  • if you already pushed a tag, the git tag man page seriously advised against a simple git tag -f B to replace a tag name "A"
  • don't try to recreate a signed tag with git tag -f (see the thread extract below)

    (it is about a corner case, but quite instructive about tags in general, and it comes from another SO contributor Jakub Narebski):

Please note that the name of tag (heavyweight tag, i.e. tag object) is stored in two places:

  • in the tag object itself as a contents of 'tag' header (you can see it in output of "git show <tag>" and also in output of "git cat-file -p <tag>", where <tag> is heavyweight tag, e.g. v1.6.3 in git.git repository),
  • and also is default name of tag reference (reference in "refs/tags/*" namespace) pointing to a tag object.
    Note that the tag reference (appropriate reference in the "refs/tags/*" namespace) is purely local matter; what one repository has in 'refs/tags/v0.1.3', other can have in 'refs/tags/sub/v0.1.3' for example.

So when you create signed tag 'A', you have the following situation (assuming that it points at some commit)

  35805ce   <--- 5b7b4ead  <=== refs/tags/A
  (commit)       tag A
                 (tag)

Please also note that "git tag -f A A" (notice the absence of options forcing it to be an annotated tag) is a noop - it doesn't change the situation.

If you do "git tag -f -s A A": note that you force owerwriting a tag (so git assumes that you know what you are doing), and that one of -s / -a / -m options is used to force annotated tag (creation of tag object), you will get the following situation

  35805ce   <--- 5b7b4ea  <--- ada8ddc  <=== refs/tags/A
  (commit)       tag A         tag A
                 (tag)         (tag)

Note also that "git show A" would show the whole chain down to the non-tag object...

PHP check whether property exists in object or class

Using array_key_exists() on objects is Deprecated in php 7.4

Instead either isset() or property_exists() should be used

reference : php.net

Where does gcc look for C and C++ header files?

You can create a file that attempts to include a bogus system header. If you run gcc in verbose mode on such a source, it will list all the system include locations as it looks for the bogus header.

$ echo "#include <bogus.h>" > t.c; gcc -v t.c; rm t.c

[..]

#include "..." search starts here:
#include <...> search starts here:
 /usr/local/include
 /usr/lib/gcc/i686-apple-darwin9/4.0.1/include
 /usr/include
 /System/Library/Frameworks (framework directory)
 /Library/Frameworks (framework directory)
End of search list.

[..]

t.c:1:32: error: bogus.h: No such file or directory

Delete duplicate records from a SQL table without a primary key

ITS easy use below query

WITH Dups AS
(
  SELECT col1,col2,col3,
ROW_NUMBER() OVER(PARTITION BY col1,col2,col3 ORDER BY (SELECT 0)) AS rn
 FROM mytable
)
DELETE FROM Dups WHERE rn > 1

Get size of an Iterable in Java

This is perhaps a bit late, but may help someone. I come across similar issue with Iterable in my codebase and solution was to use for each without explicitly calling values.iterator();.

int size = 0;
for(T value : values) {
   size++;
}

Converting float to char*

char* str=NULL;
int len = asprintf(&str, "%g", float_var);
if (len == -1)
  fprintf(stderr, "Error converting float: %m\n");
else
  printf("float is %s\n", str);
free(str);

Where is my .vimrc file?

From cmd (Windows):

C\Users\You> `vim foo.txt`

Now in Vim, enter command mode by typing: ":" (i.e. Shift + ;)

:tabedit $HOME/.vimrc

Picking a random element from a set

List asList = new ArrayList(mySet);
Collections.shuffle(asList);
return asList.get(0);

Avoid synchronized(this) in Java?

This is really just supplementary to the other answers, but if your main objection to using private objects for locking is that it clutters your class with fields that are not related to the business logic then Project Lombok has @Synchronized to generate the boilerplate at compile-time:

@Synchronized
public int foo() {
    return 0;
}

compiles to

private final Object $lock = new Object[0];

public int foo() {
    synchronized($lock) {
        return 0;
    }
}

Jquery check if element is visible in viewport

You can write a jQuery function like this to determine if an element is in the viewport.

Include this somewhere after jQuery is included:

$.fn.isInViewport = function() {
    var elementTop = $(this).offset().top;
    var elementBottom = elementTop + $(this).outerHeight();

    var viewportTop = $(window).scrollTop();
    var viewportBottom = viewportTop + $(window).height();

    return elementBottom > viewportTop && elementTop < viewportBottom;
};

Sample usage:

$(window).on('resize scroll', function() {
    if ($('#Something').isInViewport()) {
        // do something
    } else {
        // do something else
    }
});

Note that this only checks the top and bottom positions of elements, it doesn't check if an element is outside of the viewport horizontally.

How to hide column of DataGridView when using custom DataSource?

If you want to use the BrowsableAttribute, then you can look for it at runtime on the model and hide the column accordingly:

private void Form_Load(object sender, EventArgs e)
{
    //add this line after your DataGridView initialization
    HideColumns<MyModel>(myDvg);
}

private void HideColumns<T>(DataGridView dvg)
{
    var type = typeof(T);
    foreach (var column in dvg.Columns.Cast<DataGridViewColumn>())
        column.Visible = IsBrowsable(type.GetProperty(column.Name));
}

private bool IsBrowsable(PropertyInfo propertyInfo)
{
    var attribute = propertyInfo.GetCustomAttributes(true).FirstOrDefault(att => att.GetType() == typeof(BrowsableAttribute));
    return attribute == null || (attribute as BrowsableAttribute).Browsable;
}

Call PHP function from jQuery?

Thanks all. I took bits of each of your solutions and made my own.

The final working solution is:

<script type="text/javascript">
    $(document).ready(function(){
        $.ajax({
            url: '<?php bloginfo('template_url'); ?>/functions/twitter.php',
            data: "tweets=<?php echo $ct_tweets; ?>&account=<?php echo $ct_twitter; ?>",
            success: function(data) {
                $('#twitter-loader').remove();
                $('#twitter-container').html(data);
            }
        });
   });
</script>

Run PowerShell scripts on remote PC

After further investigating on PSExec tool, I think I got the answer. I need to add -i option to tell PSExec to launch process on remote in interactive mode:

PSExec \\RPC001 -i -u myID -p myPWD PowerShell C:\script\StartPS.ps1 par1 par2

Without -i, powershell.exe is running on the remote in waiting mode. Interesting point is that if I run a simple bat (without PS in bat), it works fine. Maybe this is something special for PS case? Welcome comments and explanations.

Insert new item in array on any position in PHP

You can try it, use this method to make it easy

/**
 * array insert element on position
 * 
 * @link https://vector.cool
 * 
 * @since 1.01.38
 *
 * @param array $original
 * @param mixed $inserted
 * @param int   $position
 * @return array
 */
function array_insert(&$original, $inserted, int $position): array
{
    array_splice($original, $position, 0, array($inserted));
    return $original;
}


$columns = [
    ['name' => '????', 'column' => 'item_name'],
    ['name' => '????', 'column' => 'start_time'],
    ['name' => '????', 'column' => 'full_name'],
    ['name' => '????', 'column' => 'phone'],
    ['name' => '????', 'column' => 'create_time']
];
$col = ['name' => '????', 'column' => 'user_id'];
$columns = array_insert($columns, $col, 3);
print_r($columns);

Print out:

Array
(
    [0] => Array
        (
            [name] => ????
            [column] => item_name
        )
    [1] => Array
        (
            [name] => ????
            [column] => start_time
        )
    [2] => Array
        (
            [name] => ????
            [column] => full_name
        )
    [3] => Array
        (
            [name] => ????1
            [column] => num_of_people
        )
    [4] => Array
        (
            [name] => ????
            [column] => phone
        )
    [5] => Array
        (
            [name] => ????
            [column] => user_id
        )
    [6] => Array
        (
            [name] => ????
            [column] => create_time
        )
)

How do I uniquely identify computers visiting my web site?

You can use fingerprintjs2

new Fingerprint2().get(function(result, components) {
  console.log(result) // a hash, representing your device fingerprint
  console.log(components) // an array of FP components
  //submit hash and JSON object to the server 
})

After that you can check all your users against existing and check JSON similarity, so even if their fingerprint mutates, you still can track them

Dump a NumPy array into a csv file

In Python we use csv.writer() module to write data into csv files. This module is similar to the csv.reader() module.

import csv

person = [['SN', 'Person', 'DOB'],
['1', 'John', '18/1/1997'],
['2', 'Marie','19/2/1998'],
['3', 'Simon','20/3/1999'],
['4', 'Erik', '21/4/2000'],
['5', 'Ana', '22/5/2001']]

csv.register_dialect('myDialect',
delimiter = '|',
quoting=csv.QUOTE_NONE,
skipinitialspace=True)

with open('dob.csv', 'w') as f:
    writer = csv.writer(f, dialect='myDialect')
    for row in person:
       writer.writerow(row)

f.close()

A delimiter is a string used to separate fields. The default value is comma(,).

"element.dispatchEvent is not a function" js error caught in firebug of FF3.0

Change the following line

$(document).ready(function() {

To

jQuery.noConflict();
jQuery(document).ready(function($) {

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock'

A lot of other helpful responses here, but nothing fixed this for me. Ultimately nothing I found on this site or others would get any version of MySQL from Homebrew working for me.

It was super painless to just download the DMG from https://dev.mysql.com/downloads/file/?id=479114 (find the appropriate version you need) and let the wizard install it for me. The only other manual step was adding /usr/local/mysql/bin to my PATH.

I'd recommend this option if brew is giving you trouble.

Update - if this still doesn't fix it, try completely purging mysql before installing via DMG. Follow these instructions: https://gist.github.com/vitorbritto/0555879fe4414d18569d

How do I get the height of a div's full content with jQuery?

We can also use -

$('#x').prop('scrollHeight') <!-- Height -->
$('#x').prop('scrollWidth')  <!-- Width -->

AWK to print field $2 first, then field $1

The awk is ok. I'm guessing the file is from a windows system and has a CR (^m ascii 0x0d) on the end of the line.

This will cause the cursor to go to the start of the line after $2.

Use dos2unix or vi with :se ff=unix to get rid of the CRs.

How can I get the domain name of my site within a Django template?

What about this approach? Works for me. It is also used in django-registration.

def get_request_root_url(self):
    scheme = 'https' if self.request.is_secure() else 'http'
    site = get_current_site(self.request)
    return '%s://%s' % (scheme, site)

How to get the xml node value in string

You should use .Load and not .LoadXML

MSDN Link

"The LoadXml method is for loading an XML string directly. You want to use the Load method instead."

ref : Link

Replace preg_replace() e modifier with preg_replace_callback

You shouldn't use flag e (or eval in general).

You can also use T-Regx library

pattern('(^|_)([a-z])')->replace($word)->by()->group(2)->callback('strtoupper');

if condition in sql server update query

Something like this should work:

UPDATE
    table_Name
SET 
  column_A = CASE WHEN @flag = '1' THEN column_A + @new_value ELSE column_A END,
  column_B = CASE WHEN @flag = '0' THEN column_B + @new_value ELSE column_B END
WHERE
    ID = @ID

How to execute a java .class from the command line

If you have in your java source

package mypackage;

and your class is hello.java with

public class hello {

and in that hello.java you have

 public static void main(String[] args) {

Then (after compilation) changeDir (cd) to the directory where your hello.class is. Then

java -cp . mypackage.hello

Mind the current directory and the package name before the class name. It works for my on linux mint and i hope on the other os's also

Thanks Stack overflow for a wealth of info.

How to change the docker image installation directory?

For Those looking in 2020. The following is for Windows 10 Machine:

  1. In the global Actions pane of Hyper-V Manager click Hyper-V Settings…
  2. Under Virtual Hard Disks change the location from the default to your desired location.
  3. Under Virtual Machines change the location from the default to your desired location, and click apply.

enter image description here

  1. Click OK to close the Hyper-V Settings page.

Using jQuery to compare two arrays of Javascript objects

The nice one liner from Sudhakar R as jQuery global method.

/**
 * Compare two arrays if they are equal even if they have different order.
 *
 * @link https://stackoverflow.com/a/7726509
 */
jQuery.extend({
  /**
   * @param {array} a
   *   First array to compare.
   * @param {array} b
   *   Second array to compare.
   * @return {boolean}
   *   True if both arrays are equal, otherwise false.
   */
  arrayCompare: function (a, b) {
    return $(a).not(b).get().length === 0 && $(b).not(a).get().length === 0;
  }
});

postgresql port confusion 5433 or 5432?

For me in PgAdmin 4 on Mac OS High Sierra, Clicking the PostrgreSQL10 database under Servers in the left column, then the Properties tab, showed 5433 as the port under Connection. (I don't know why, because I chose 5432 during install). Anyway, I clicked the Edit icon under the Properties tab, change that to 5432, saved, and that solved the problem. Go figure.

How to import data from one sheet to another

VLookup

You can do it with a simple VLOOKUP formula. I've put the data in the same sheet, but you can also reference a different worksheet. For the price column just change the last value from 2 to 3, as you are referencing the third column of the matrix "A2:C4". VLOOKUP example

External Reference

To reference a cell of the same Workbook use the following pattern:

<Sheetname>!<Cell>

Example:

Table1!A1

To reference a cell of a different Workbook use this pattern:

[<Workbook_name>]<Sheetname>!<Cell>

Example:

[MyWorkbook]Table1!A1

How do I measure execution time of a command on the Windows command line?

Since others are recommending installing things like freeware and PowerShell, you could also install Cygwin, which would give you access to many basic Unix commands like time:

abe@abe-PC:~$ time sleep 5

real    0m5.012s
user    0m0.000s
sys 0m0.000s

Not sure how much overhead Cygwin adds.

Can I use a :before or :after pseudo-element on an input field?

The biggest misunderstanding here is the meaning of the words before and after. They do not refer to the element itself, but to the content in the element. So element:before is before the content, and element:after is after the content, but both are still inside the original element.

The input element has no content in the CSS view, and so has no :before or :after pseudo content. This is true of many other void or replaced elements.

There is no pseudo element referring to outside the element.

In a different universe, these pseudo elements might have been called something else to make this distinction clearer. And someone might even have proposed a pseudo element which is genuinely outside the element. So far, this is not the case in this universe.

Load HTML File Contents to Div [without the use of iframes]

2019
Using fetch

<script>
fetch('page.html')
  .then(data => data.text())
  .then(html => document.getElementById('elementID').innerHTML = html);
</script>

<div id='elementID'> </div>

fetch needs to receive a http or https link, this means that it won't work locally.

Note: As Altimus Prime said, it is a feature for modern browsers

How can I get the values of data attributes in JavaScript code?

Try this instead of your code:

var type=$("#the-span").attr("data-type");
alert(type);

Proper way to make HTML nested list?

Have you thought about using the TAG "dt" instead of "ul" for nesting lists? It's inherit style and structure allow you to have a title per section and it automatically tabulates the content that goes inside.

<dl>
  <dt>Coffee</dt>
    <dd>Black hot drink</dd>
  <dt>Milk</dt>
    <dd>White cold drink</dd>
</dl>

VS

<ul>
   <li>Choice A</li>
   <li>Choice B
      <ul>
         <li>Sub 1</li>
         <li>Sub 2</li>
      </ul>
   </li>
</ul>

How can I find a specific file from a Linux terminal?

Solution: Use unix command find

The find utility recursively descends the directory tree for each path listed, evaluating an expression (composed of the 'primaries' and 'operands') in terms of each file in the tree.

  • You can make the find action be more efficient and smart by controlling it with regular expressions queries, file types, size thresholds, depths dimensions in subtree, groups, ownership, timestamps , modification/creation date and more.
  • In addition you can use operators and combine find requests such as or/not/and etc...

The Traditional Formula would be :

find <path> -flag <valueOfFlag>

Easy Examples

1.Find by Name - Find all package.json from my current location subtree hierarchy.

find . -name "package.json"

2.Find by Name and Type - find all node_modules directories from ALL file system (starting from root hierarchy )

sudo find / -name "node_modules" -type d

Complex Examples:

More Useful examples which can demonstrate the power of flag options and operators:

3.Regex and File Type - Find all javascript controllers variation names (using regex) javascript Files only in my app location.

find /user/dev/app -name "*contoller-*\.js" -type f

-type f means file -name related to regular expression to any variation of controller string and dash with .js at the end

4.Depth - Find all routes patterns directories in app directory no more than 3 dimensions ( app/../../.. only and no more deeper)

find app -name "*route*" -type d  -maxdepth 3

-type d means directory -name related to regular expression to any variation of route string -maxdepth making the finder focusing on 3 subtree depth and no more <yourSearchlocation>/depth1/depth2/depth3)

5.File Size , Ownership and OR Operator - Find all files with names 'sample' or 'test' under ownership of root user that greater than 1 Mega and less than 5 Mega.

find . \( -name "test" -or -name "sample" \)  -user root -size +1M -size -5M

-size threshold representing the range between more than (+) and less than (-) -user representing the file owner -or operator filters query for both regex matches

6.Empty Files - find all empty directories in file system

find / -type d -empty

7.Time Access, Modification and creation of files - find all files that were created/modified/access in directory in 10 days

# creation (c)
find /test -name "*.groovy" -ctime -10d
# modification (m)
find /test -name "*.java" -mtime -10d
# access (a)
find /test -name "*.js" -atime -10d

8.Modification Size Filter - find all files that were modified exactly between a week ago to 3 weeks ago and less than 500kb and present their sizes as a list

find /test -name "*.java" -mtime -3w -mtime +1w -size -500k | xargs du -h

Solving Quadratic Equation

one liner solve quadratic equation

from math import sqrt
s = lambda a,b,c: {(-b-sqrt(d))/2*a,(-b+sqrt(d))/2*a} if (d:=b**2-4*a*c)>=0 else {}
roots_set = s(int(input('a=')),int(input('b=')),int(input('c=')))
print(roots_set,f'number of roots {len(roots_set)}')

one line python solve quadratic equations video

Remove HTML Tags from an NSString on the iPhone

You can use like below

-(void)myMethod
 {

 NSString* htmlStr = @"<some>html</string>";
 NSString* strWithoutFormatting = [self stringByStrippingHTML:htmlStr];

 }

 -(NSString *)stringByStrippingHTML:(NSString*)str
 {
   NSRange r;
   while ((r = [str rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location     != NSNotFound)
  {
     str = [str stringByReplacingCharactersInRange:r withString:@""];
 }
  return str;
 }

How to create a user in Django?

Bulk user creation with set_password

I you are creating several test users, bulk_create is much faster, but we can't use create_user with it.

set_password is another way to generate the hashed passwords:

def users_iterator():
    for i in range(nusers):
        is_superuser = (i == 0)
        user = User(
            first_name='First' + str(i),
            is_staff=is_superuser,
            is_superuser=is_superuser,
            last_name='Last' + str(i),
            username='user' + str(i),
        )
        user.set_password('asdfqwer')
        yield user

class Command(BaseCommand):
    def handle(self, **options):
        User.objects.bulk_create(iter(users_iterator()))

Question specific about password hashing: How to use Bcrypt to encrypt passwords in Django

Tested in Django 1.9.

Argument list too long error for rm, cp, mv commands

I found that for extremely large lists of files (>1e6), these answers were too slow. Here is a solution using parallel processing in python. I know, I know, this isn't linux... but nothing else here worked.

(This saved me hours)

# delete files
import os as os
import glob
import multiprocessing as mp

directory = r'your/directory'
os.chdir(directory)


files_names = [i for i in glob.glob('*.{}'.format('pdf'))]

# report errors from pool

def callback_error(result):
    print('error', result)

# delete file using system command
def delete_files(file_name):
     os.system('rm -rf ' + file_name)

pool = mp.Pool(12)  
# or use pool = mp.Pool(mp.cpu_count())


if __name__ == '__main__':
    for file_name in files_names:
        print(file_name)
        pool.apply_async(delete_files,[file_name], error_callback=callback_error)

How to amend older Git commit?

You can use git rebase --interactive, using the edit command on the commit you want to amend.

Can Twitter Bootstrap alerts fade in as well as out?

For 2.3 and above, just add:

$(".alert").fadeOut(3000 );

bootstrap:

<div class="alert success fade in" data-alert="alert" >
    <a class="close" data-dismiss="alert" href="#">&times;</a>
    // code 
</div>

Works in all browsers.

How do I update a GitHub forked repository?

A lot of answers end up moving your fork one commit ahead of the parent repository. This answer summarizes the steps found here which will move your fork to the same commit as the parent.

  1. Change directory to your local repository.

    • Switch to master branch if you are not git checkout master
  2. Add the parent as a remote repository, git remote add upstream <repo-location>

  3. Issue git fetch upstream
  4. Issue git rebase upstream/master

    • At this stage you check that commits what will be merged by typing git status
  5. Issue git push origin master

For more information about these commands, refer to step 3.

Unique constraint on multiple columns

If the table is already created in the database, then you can add a unique constraint later on by using this SQL query:

ALTER TABLE dbo.User
  ADD CONSTRAINT ucCodes UNIQUE (fcode, scode, dcode)

Check if a number has a decimal place/is a whole number

Number.isInteger(23);  // true
Number.isInteger(1.5); // false
Number.isInteger("x"); // false: 

Number.isInteger() is part of the ES6 standard and not supported in IE11.

It returns false for NaN, Infinity and non-numeric arguments while x % 1 != 0 returns true.

How to add new DataRow into DataTable?

You can try with this code - based on Rows.Add method

DataTable table = new DataTable();
DataRow row = table.NewRow();
table.Rows.Add(row);

Link : https://msdn.microsoft.com/en-us/library/9yfsd47w.aspx

JPA or JDBC, how are they different?

JDBC is a much lower-level (and older) specification than JPA. In it's bare essentials, JDBC is an API for interacting with a database using pure SQL - sending queries and retrieving results. It has no notion of objects or hierarchies. When using JDBC, it's up to you to translate a result set (essentially a row/column matrix of values from one or more database tables, returned by your SQL query) into Java objects.

Now, to understand and use JDBC it's essential that you have some understanding and working knowledge of SQL. With that also comes a required insight into what a relational database is, how you work with it and concepts such as tables, columns, keys and relationships. Unless you have at least a basic understanding of databases, SQL and data modelling you will not be able to make much use of JDBC since it's really only a thin abstraction on top of these things.

How to convert a string or integer to binary in Ruby?

I asked a similar question. Based on @sawa's answer, the most succinct way to represent an integer in a string in binary format is to use the string formatter:

"%b" % 245
=> "11110101"

You can also choose how long the string representation to be, which might be useful if you want to compare fixed-width binary numbers:

1.upto(10).each { |n| puts "%04b" % n }
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010

Error with multiple definitions of function

You have #include "fun.cpp" in mainfile.cpp so compiling with:

g++ -o hw1 mainfile.cpp

will work, however if you compile by linking these together like

g++ -g -std=c++11 -Wall -pedantic   -c -o fun.o fun.cpp
g++ -g -std=c++11 -Wall -pedantic   -c -o mainfile.o mainfile.cpp

As they mention above, adding #include "fun.hpp" will need to be done or it won't work. However, your case with the funct() function is slightly different than my problem.

I had this issue when doing a HW assignment and the autograder compiled by the lower bash recipe, yet locally it worked using the upper bash.

No visible cause for "Unexpected token ILLEGAL"

I had the same problem on my mac and found it was because the Mac was replacing the standard quotes with curly quotes which are illegal javascript characters.

To fix this I had to change the settings on my mac System Preferences=>Keyboard=>Text(tab) uncheck use smart quotes and dashes (default was checked).

Visual Studio Code includePath

My c_cpp_properties.json config-

{
    "configurations": [
        {
            "name": "Win32",
            "compilerPath": "C:/MinGW/bin/g++.exe",
            "includePath": [
                "C:/MinGW/lib/gcc/mingw32/9.2.0/include/c++"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "cStandard": "c17",
            "cppStandard": "c++17",
            "intelliSenseMode": "windows-gcc-x64"
       }
    ],
    "version": 4
}

Git On Custom SSH Port

Above answers are nice and great, but not clear for new git users like me. So after some investigation, i offer this new answer.

1 what's the problem with the ssh config file way?

When the config file does not exists, you can create one. Besides port the config file can include other ssh config option:user IdentityFile and so on, the config file looks like

Host mydomain.com
    User git
    Port 12345

If you are running linux, take care the config file must have strict permission: read/write for the user, and not accessible by others

2 what about the ssh url way?

It's cool, the only thing we should know is that there two syntaxes for ssh url in git

  • standard syntax ssh://[user@]host.xz[:port]/path/to/repo.git/
  • scp like syntax [user@]host.xz:path/to/repo.git/

By default Gitlab and Github will show the scp like syntax url, and we can not give the custom ssh port. So in order to change ssh port, we need use the standard syntax

How to get the Full file path from URI

  public String getPath(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    cursor.moveToFirst();
    String document_id = cursor.getString(0);
    document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
    cursor.close();

    cursor = getContentResolver().query(
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
    cursor.moveToFirst();
    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
    cursor.close();

    return path;
}

Using this method we can get string filepath from Uri.

How to set proxy for wget?

wget uses environment variables somthing like this at command line can work:

export http_proxy=http://your_ip_proxy:port/
export https_proxy=$http_proxy
export ftp_proxy=$http_proxy
export dns_proxy=$http_proxy
export rsync_proxy=$http_proxy
export no_proxy="localhost,127.0.0.1,localaddress,.localdomain.com"

Does mobile Google Chrome support browser extensions?

Just use a different browser. Follow the steps given below to install Chrome extensions on your Android device.

Step 1: Open Google Play Store and download Yandex Browser. Install the browser on your phone.

Step 2: In the URL box of your new browser, open 'chrome.google.com/webstore’ by entering the same in the URL address.

Step 3: Look for the Chrome extension that you want and once you have it, tap on 'Add to Chrome.’

The added Chrome extension will now be automatically added to the Yandex browser.

Sorting an IList in C#

Is this a valid solution?

        IList<string> ilist = new List<string>();
        ilist.Add("B");
        ilist.Add("A");
        ilist.Add("C");

        Console.WriteLine("IList");
        foreach (string val in ilist)
            Console.WriteLine(val);
        Console.WriteLine();

        List<string> list = (List<string>)ilist;
        list.Sort();
        Console.WriteLine("List");
        foreach (string val in list)
            Console.WriteLine(val);
        Console.WriteLine();

        list = null;

        Console.WriteLine("IList again");
        foreach (string val in ilist)
            Console.WriteLine(val);
        Console.WriteLine();

The result was: IList B A C

List A B C

IList again A B C