Programs & Examples On #Mutual exclusion

Mutual exclusion means that processes must always execute critical sections in time intervals that do not overlap. The mutual exclusion requirement is one of the most basic in an operating system; without it the OS cannot share resources safely.

std::unique_lock<std::mutex> or std::lock_guard<std::mutex>?

There are certain common things between lock_guard and unique_lock and certain differences.

But in the context of the question asked, the compiler does not allow using a lock_guard in combination with a condition variable, because when a thread calls wait on a condition variable, the mutex gets unlocked automatically and when other thread/threads notify and the current thread is invoked (comes out of wait), the lock is re-acquired.

This phenomenon is against the principle of lock_guard. lock_guard can be constructed only once and destructed only once.

Hence lock_guard cannot be used in combination with a condition variable, but a unique_lock can be (because unique_lock can be locked and unlocked several times).

DataFrame constructor not properly called! error

You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.

So if you want to use your code, you could do:

df = DataFrame(eval(data))

But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:

data = []
for row in result_set:
    data.append({'value': row["tag_expression"], 'key': row["tag_name"]})

But probably even this is not needed, as depending on what is exactly in your result_set you could probably:

  • provide this directly to a DataFrame: DataFrame(result_set)
  • or use the pandas read_sql_query function to do this for you (see docs on this)

Python Pandas: Get index of rows which column matches certain value

I extended this question that is how to gets the row, columnand value of all matches value?

here is solution:

import pandas as pd
import numpy as np


def search_coordinate(df_data: pd.DataFrame, search_set: set) -> list:
    nda_values = df_data.values
    tuple_index = np.where(np.isin(nda_values, [e for e in search_set]))
    return [(row, col, nda_values[row][col]) for row, col in zip(tuple_index[0], tuple_index[1])]


if __name__ == '__main__':
    test_datas = [['cat', 'dog', ''],
                  ['goldfish', '', 'kitten'],
                  ['Puppy', 'hamster', 'mouse']
                  ]
    df_data = pd.DataFrame(test_datas)
    print(df_data)
    result_list = search_coordinate(df_data, {'dog', 'Puppy'})
    print(f"\n\n{'row':<4} {'col':<4} {'name':>10}")
    [print(f"{row:<4} {col:<4} {name:>10}") for row, col, name in result_list]

Output:

          0        1       2
0       cat      dog        
1  goldfish           kitten
2     Puppy  hamster   mouse


row  col        name
0    1           dog
2    0         Puppy

USB Debugging option greyed out

Unplug your phone from the PC and go to develop options and now here you can enable USB debugging. if you connect USB and try to enable debugging it will not enable and follow TMacGyver is right it works for me using choose PC connection.

How to create a horizontal loading progress bar?

Progress Bar in Layout

<ProgressBar 
               android:id="@+id/download_progressbar"
               android:layout_width="200dp"
               android:layout_height="24dp"
               android:background="@drawable/download_progress_bg_track"
               android:progressDrawable="@drawable/download_progress_style"
               style="?android:attr/progressBarStyleHorizontal"
               android:indeterminate="false"
               android:indeterminateOnly="false" />

download_progress_style.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/progress">
    <scale 
      android:useIntrinsicSizeAsMinimum="true" 
      android:scaleWidth="100%" 
      android:drawable="@drawable/store_download_progress" />
</item>

What's the shebang/hashbang (#!) in Facebook and new Twitter URLs for?

This technique is now deprecated.

This used to tell Google how to index the page.

https://developers.google.com/webmasters/ajax-crawling/

This technique has mostly been supplanted by the ability to use the JavaScript History API that was introduced alongside HTML5. For a URL like www.example.com/ajax.html#!key=value, Google will check the URL www.example.com/ajax.html?_escaped_fragment_=key=value to fetch a non-AJAX version of the contents.

Redirect after Login on WordPress

The functions.php file doesn't have anything to do with login redirect, what you should be considering it's the wp-login.php file, you can actually change the entire login interface from there, and force users to redirect to your custom pages instead of the /wp-admin/ directory.

Open the file with Notepad if using Windows or any text editor, Prese Ctrl + F (on window) Find "wp-admin/" and change it to the folder you want it to redirect to after login, still on the same file Press Ctrl + F, find "admin_url" and the change the file name, the default file name there is "profile.php"...after just save and give a try.

if ( !$user->has_cap('edit_posts') && ( empty( $redirect_to ) || $redirect_to == 'wp-admin/' || $redirect_to == admin_url() ) )
        $redirect_to = admin_url('profile.php');
    wp_safe_redirect($redirect_to);
    exit();

Or you can use the "registration-login plugin" http://wordpress.org/extend/plugins/registration-login/, just simple edit the redirect urls and the links to where you want it to redirect after login, and you've got your very own custom profile.

how to end ng serve or firebase serve

You can use the following command to end an ongoing process:

ctrl + c

How to completely remove borders from HTML table

In a bootstrap environment here is my solution:

    <table style="border-collapse: collapse; border: none;">
        <tr style="border: none;">
            <td style="border: none;">
            </td>
        </tr>
    </table>    

How to get a specific column value from a DataTable in c#

The table normally contains multiple rows. Use a loop and use row.Field<string>(0) to access the value of each row.

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>("File");
}

You can also access it via index:

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>(0);
}

If you expect only one row, you can also use the indexer of DataRowCollection:

string file = dt.Rows[0].Field<string>(0); 

Since this fails if the table is empty, use dt.Rows.Count to check if there is a row:

if(dt.Rows.Count > 0)
    file = dt.Rows[0].Field<string>(0);

Python os.path.join on Windows

answering to your comment : "the others '//' 'c:', 'c:\\' did not work (C:\\ created two backslashes, C:\ didn't work at all)"

On windows using os.path.join('c:', 'sourcedir') will automatically add two backslashes \\ in front of sourcedir.

To resolve the path, as python works on windows also with forward slashes -> '/', simply add .replace('\\','/') with os.path.join as below:-

os.path.join('c:\\', 'sourcedir').replace('\\','/')

e.g: os.path.join('c:\\', 'temp').replace('\\','/')

output : 'C:/temp'

SwiftUI - How do I change the background color of a View?

Several possibilities : (SwiftUI / Xcode 11)

1 .background(Color.black) //for system colors

2 .background(Color("green")) //for colors you created in Assets.xcassets

  1. Otherwise you can do Command+Click on the element and change it from there.

Hope it help :)

Eclipse Intellisense?

I've get closer to VisualStudio-like behaviour by setting the "Autocomplete Trigger for Java" to

.(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

and setting delay to 0.

Now I'd like to realize how to make it autocomplete method name when I press ( as VS's Intellisense does.

css label width not taking effect

Make it a block first, then float left to stop pushing the next block in to a new line.

#report-upload-form label {
                           padding-left:26px;
                           width:125px;
                           text-transform: uppercase;
                           display:block;
                           float:left
}

How to convert an ASCII character into an int in C

A char value in C is implicitly convertible to an int. e.g, char c; ... printf("%d", c) prints the decimal ASCII value of c, and int i = c; puts the ASCII integer value of c in i. You can also explicitly convert it with (int)c. If you mean something else, such as how to convert an ASCII digit to an int, that would be c - '0', which implicitly converts c to an int and then subtracts the ASCII value of '0', namely 48 (in C, character constants such as '0' are of type int, not char, for historical reasons).

Scroll Element into View with Selenium

webElement = driver.findElement(By.xpath("bla-bla-bla"));
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", webElement);

For more examples, go here. All in Russian, but Java code is cross-cultural :)

Get refresh token google api

This is complete code in PHP using google official SDK

$client = new Google_Client();
## some need parameter
$client->setApplicationName('your application name');
$client->setClientId('****************');
$client->setClientSecret('************');
$client->setRedirectUri('http://your.website.tld/complete/url2redirect');
$client->setScopes('https://www.googleapis.com/auth/userinfo.email');
## these two lines is important to get refresh token from google api
$client->setAccessType('offline');
$client->setApprovalPrompt('force'); # this line is important when you revoke permission from your app, it will prompt google approval dialogue box forcefully to user to grant offline access

Where does Android emulator store SQLite database?

An update mentioned in the comments below:

You don't need to be on the DDMS perspective anymore, just open the File Explorer from Eclipse Window > Show View > Other... It seems the app doesn't need to be running even, I can browse around in different apps file contents. I'm running ADB version 1.0.29


Or, you can try the old approach:

Open the DDMS perspective on your Eclipse IDE

(Window > Open Perspective > Other > DDMS)

and the most important:

YOUR APPLICATION MUST BE RUNNING SO YOU CAN SEE THE HIERARCHY OF FOLDERS AND FILES.

Then in the File Explorer Tab you will follow the path :

data > data > your-package-name > databases > your-database-file.

Then select the file, click on the disket icon in the right corner of the screen to download the .db file. If you want to upload a database file to the emulator you can click on the phone icon(beside disket icon) and choose the file to upload.

If you want to see the content of the .db file, I advise you to use SQLite Database Browser, which you can download here.

PS: If you want to see the database from a real device, you must root your phone.

android splash screen sizes for ldpi,mdpi, hdpi, xhdpi displays ? - eg : 1024X768 pixels for ldpi

  • Xlarge screens are at least 960dp x 720dp
  • List item large screens are at least 640dp x 480dp
  • List item normal screens are at least 470dp x 320dp
  • List item small screens are at least 426dp x 320dp

Use this to create your images and put them in specific resource folder.

How to edit the legend entry of a chart in Excel?

There are 3 ways to do this:

1. Define the Series names directly

Right-click on the Chart and click Select Data then edit the series names directly as shown below.

enter image description here

You can either specify the values directly e.g. Series 1 or specify a range e.g. =A2

enter image description here

2. Create a chart defining upfront the series and axis labels

Simply select your data range (in similar format as I specified) and create a simple bar chart. The labels should be defined automatically. enter image description here

3. Define the legend (series names) using VBA

Similarly you can define the series names dynamically using VBA. A simple example below:

ActiveChart.ChartArea.Select
ActiveChart.FullSeriesCollection(1).Name = "=""Hello"""

This will redefine the first series name. Just change the index from (1) to e.g. (2) and so on to change the following series names. What does the VBA above do? It sets the series name to Hello as "=""Hello""" translates to ="Hello" (" have to be escaped by a preceding ").

Saving utf-8 texts with json.dumps as UTF8, not as \u escape sequence

UPDATE: This is wrong answer, but it's still useful to understand why it's wrong. See comments.

How about unicode-escape?

>>> d = {1: "??? ????", 2: u"??? ????"}
>>> json_str = json.dumps(d).decode('unicode-escape').encode('utf8')
>>> print json_str
{"1": "??? ????", "2": "??? ????"}

How to load property file from classpath?

final Properties properties = new Properties();
try (final InputStream stream =
           this.getClass().getResourceAsStream("foo.properties")) {
    properties.load(stream);
    /* or properties.loadFromXML(...) */
}

How to run python script in webpage

With your current requirement this would work :

    def start_html():
        return '<html>'

    def end_html():
        return '</html>'

    def print_html(text):
        text = str(text)
        text = text.replace('\n', '<br>')
        return '<p>' + str(text) + '</p>'
if __name__ == '__main__':
        webpage_data =  start_html()
        webpage_data += print_html("Hi Welcome to Python test page\n")
        webpage_data += fd.write(print_html("Now it will show a calculation"))
        webpage_data += print_html("30+2=")
        webpage_data += print_html(30+2)
        webpage_data += end_html()
        with open('index.html', 'w') as fd: fd.write(webpage_data)

open the index.html and you will see what you want

Java: Rotating Images

A simple way to do it without the use of such a complicated draw statement:

    //Make a backup so that we can reset our graphics object after using it.
    AffineTransform backup = g2d.getTransform();
    //rx is the x coordinate for rotation, ry is the y coordinate for rotation, and angle
    //is the angle to rotate the image. If you want to rotate around the center of an image,
    //use the image's center x and y coordinates for rx and ry.
    AffineTransform a = AffineTransform.getRotateInstance(angle, rx, ry);
    //Set our Graphics2D object to the transform
    g2d.setTransform(a);
    //Draw our image like normal
    g2d.drawImage(image, x, y, null);
    //Reset our graphics object so we can draw with it again.
    g2d.setTransform(backup);

Unknown SSL protocol error in connection

I use tortoiseGit. I had the same problem. Then in push settings I unchecked "autoload putty key", tried to push, then I checked it again, and pushed, and it worked. But seriously, I don't know why.

Remote branch is not showing up in "git branch -r"

Unfortunately, git branch -a and git branch -r do not show you all remote branches, if you haven't executed a "git fetch".

git remote show origin works consistently all the time. Also git show-ref shows all references in the Git repository. However, it works just like the git branch command.

Jackson JSON: get node name from json-tree

fields() and fieldNames() both were not working for me. And I had to spend quite sometime to find a way to iterate over the keys. There are two ways by which it can be done.

One is by converting it into a map (takes up more space):

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> result = mapper.convertValue(jsonNode, Map.class);
for (String key : result.keySet())
{
    if(key.equals(foo))
    {
        //code here
    }
}

Another, by using a String iterator:

Iterator<String> it = jsonNode.getFieldNames();
while (it.hasNext())
{
    String key = it.next();
    if (key.equals(foo))
    {
         //code here
    }
}

Exception in thread "main" java.lang.UnsupportedClassVersionError: a (Unsupported major.minor version 51.0)

I had this problem, after installing jdk7 next to Java 6. The binaries were correctly updated using update-alternatives --config java to jdk7, but the $JAVA_HOME environment variable still pointed to the old directory of Java 6.

no matching function for call to ' '

You are passing pointers (Complex*) when your function takes references (const Complex&). A reference and a pointer are entirely different things. When a function expects a reference argument, you need to pass it the object directly. The reference only means that the object is not copied.

To get an object to pass to your function, you would need to dereference your pointers:

Complex::distanta(*firstComplexNumber, *secondComplexNumber);

Or get your function to take pointer arguments.

However, I wouldn't really suggest either of the above solutions. Since you don't need dynamic allocation here (and you are leaking memory because you don't delete what you have newed), you're better off not using pointers in the first place:

Complex firstComplexNumber(81, 93);
Complex secondComplexNumber(31, 19);
Complex::distanta(firstComplexNumber, secondComplexNumber);

difference between width auto and width 100 percent

Using width:auto; + display:inline-block; in css giving awesome effect.

width : auto;
display: inline-block;

Cannot access a disposed object - How to fix?

we do check the IsDisposed property on the schedule component before using it in the Timer Tick event but it doesn't help.

If I understand that stack trace, it's not your timer which is the problem, it's one in the control itself - it might be them who are not cleaning-up properly.

Are you explicitly calling Dispose on their control?

Drag and drop a DLL to the GAC ("assembly") in windows server 2008 .net 4.0

if you have neccessary .net framework installed. Ex ; .Net 4.0 or .Net 3.5, then you can just copy Gacutil.exe from any of the machine and to the new machine.

1) Open CMD as adminstrator in new server.
2) Traverse to the folder where you copied the Gacutil.exe. For eg - C:\program files.(in my case).
3) Type the below in the cmd prompt and install.

C:\Program Files\gacutil.exe /I dllname

Are there bookmarks in Visual Studio Code?

Both VS Code extensions can be used:

  1. 'Bookmarks'
  2. 'Numbered Bookmarks'

Personally, I'm suggesting: Numbered Bookmarks, with 'navigate through all files' option:

  1. ctrl + Shift + P in VS Code
  2. In newly open field, type: Open User Settings
  3. Paste this key/value: "numberedBookmarks.navigateThroughAllFiles": "allowDuplicates" (allow duplicates of bookmarks),
  4. Or, paste this key/value: "numberedBookmarks.navigateThroughAllFiles": "replace"

NOTE

Either way, be careful with shortcuts (Ctrl+1, Ctrl+Shift+1,..) that are already assigned.

Personally, mine were in 2 conflicts, with:

  1. VS Code shortcuts, that already exists,
  2. Ditto clipboard (I've got paste on each call of bookmark)

How does C#'s random number generator work?

You can use Random.Next(int maxValue):

Return: A 32-bit signed integer greater than or equal to zero, and less than maxValue; that is, the range of return values ordinarily includes zero but not maxValue. However, if maxValue equals zero, maxValue is returned.

var r = new Random();
// print random integer >= 0 and  < 100
Console.WriteLine(r.Next(100));

For this case however you could use Random.Next(int minValue, int maxValue), like this:

// print random integer >= 1 and < 101
Console.WriteLine(r.Next(1, 101);)
// or perhaps (if you have this specific case)
Console.WriteLine(r.Next(100) + 1);

create a trusted self-signed SSL cert for localhost (for use with Express/Node)

Go to: chrome://flags/

Enable: Allow invalid certificates for resources loaded from localhost.

You don't have the green security, but you are always allowed for https://localhost in chrome.

WPF: Setting the Width (and Height) as a Percentage Value

I use two methods for relative sizing. I have a class called Relative with three attached properties To, WidthPercent and HeightPercent which is useful if I want an element to be a relative size of an element anywhere in the visual tree and feels less hacky than the converter approach - although use what works for you, that you're happy with.

The other approach is rather more cunning. Add a ViewBox where you want relative sizes inside, then inside that, add a Grid at width 100. Then if you add a TextBlock with width 10 inside that, it is obviously 10% of 100.

The ViewBox will scale the Grid according to whatever space it has been given, so if its the only thing on the page, then the Grid will be scaled out full width and effectively, your TextBlock is scaled to 10% of the page.

If you don't set a height on the Grid then it will shrink to fit its content, so it'll all be relatively sized. You'll have to ensure that the content doesn't get too tall, i.e. starts changing the aspect ratio of the space given to the ViewBox else it will start scaling the height as well. You can probably work around this with a Stretch of UniformToFill.

Return only string message from Spring MVC 3 Controller

Simplest solution:

Just add quotes, I really don't know why it's not auto-implemented by Spring boot when response type defined as application/json, but it works great.

@PostMapping("/create")
public String foo()
{
    String result = "something"
    return "\"" + result + "\"";
}

Force flushing of output to a file while bash script is still running

This isn't a function of bash, as all the shell does is open the file in question and then pass the file descriptor as the standard output of the script. What you need to do is make sure output is flushed from your script more frequently than you currently are.

In Perl for example, this could be accomplished by setting:

$| = 1;

See perlvar for more information on this.

Using npm behind corporate proxy .pac

I had run into several issues with this and finally what I did is as follows:

  1. Used Fiddler, with "Automatically Authenticate" selected
  2. In fiddler custom rules, i added

    if (m_AutoAuth) {oSession["X-AutoAuth"] = "domain\\username:password";}
    
  3. Finally in npm i set the proxy to http://localhost:8888

This worked fine.

How do I find out my python path using python?

You would probably also want this:

import sys
print(sys.path)

Or as a one liner from the terminal:

python -c "import sys; print('\n'.join(sys.path))"

Caveat: If you have multiple versions of Python installed you should use a corresponding command python2 or python3.

Adding items to end of linked list

Here is a partial solution to your linked list class, I have left the rest of the implementation to you, and also left the good suggestion to add a tail node as part of the linked list to you as well.

The node file :

public class Node 
{
    private Object data; 
    private Node next; 

    public Node(Object d) 
    { 
        data = d ;
        next = null;
    }

    public Object GetItem()
    {
        return data;
    }

    public Node GetNext()
    {
        return next;
    }

    public void SetNext(Node toAppend)
    {
        next = toAppend;
    }
}

And here is a Linked List file :

public class LL
{
    private Node head;

    public LL()
    {
        head = null;
    }

    public void AddToEnd(String x)
    {
        Node current = head;

        // as you mentioned, this is the base case
        if(current == null) {
            head = new Node(x);
            head.SetNext(null);
        }

        // you should understand this part thoroughly :
        // this is the code that traverses the list.
        // the germane thing to see is that when the 
        // link to the next node is null, we are at the 
        // end of the list.
        else {
            while(current.GetNext() != null)
                current = current.GetNext();

            // add new node at the end
        Node toAppend = new Node(x);
            current.SetNext(toAppend);
        }
    }
}

How to convert current date into string in java?

// On the form: dow mon dd hh:mm:ss zzz yyyy
new Date().toString();

How to set a time zone (or a Kind) of a DateTime value?

If you want to get advantage of your local machine timezone you can use myDateTime.ToUniversalTime() to get the UTC time from your local time or myDateTime.ToLocalTime() to convert the UTC time to the local machine's time.

// convert UTC time from the database to the machine's time
DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
var localTime = databaseUtcTime.ToLocalTime();

// convert local time to UTC for database save
var databaseUtcTime = localTime.ToUniversalTime();

If you need to convert time from/to other timezones, you may use TimeZoneInfo.ConvertTime() or TimeZoneInfo.ConvertTimeFromUtc().

// convert UTC time from the database to japanese time
DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
var japaneseTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
var japaneseTime = TimeZoneInfo.ConvertTimeFromUtc(databaseUtcTime, japaneseTimeZone);

// convert japanese time to UTC for database save
var databaseUtcTime = TimeZoneInfo.ConvertTimeToUtc(japaneseTime, japaneseTimeZone);

List of available timezones

TimeZoneInfo class on MSDN

What does the "map" method do in Ruby?

map, along with select and each is one of Ruby's workhorses in my code.

It allows you to run an operation on each of your array's objects and return them all in the same place. An example would be to increment an array of numbers by one:

[1,2,3].map {|x| x + 1 }
#=> [2,3,4]

If you can run a single method on your array's elements you can do it in a shorthand-style like so:

  1. To do this with the above example you'd have to do something like this

    class Numeric
      def plusone
        self + 1
      end
    end
    [1,2,3].map(&:plusone)
    #=> [2,3,4]
    
  2. To more simply use the ampersand shortcut technique, let's use a different example:

    ["vanessa", "david", "thomas"].map(&:upcase)
    #=> ["VANESSA", "DAVID", "THOMAS"]
    

Transforming data in Ruby often involves a cascade of map operations. Study map & select, they are some of the most useful Ruby methods in the primary library. They're just as important as each.

(map is also an alias for collect. Use whatever works best for you conceptually.)

More helpful information:

If the Enumerable object you're running each or map on contains a set of Enumerable elements (hashes, arrays), you can declare each of those elements inside your block pipes like so:

[["audi", "black", 2008], ["bmw", "red", 2014]].each do |make, color, year|
  puts "make: #{make}, color: #{color}, year: #{year}"
end
# Output:
# make: audi, color: black, year: 2008
# make: bmw, color: red, year: 2014

In the case of a Hash (also an Enumerable object, a Hash is simply an array of tuples with special instructions for the interpreter). The first "pipe parameter" is the key, the second is the value.

{:make => "audi", :color => "black", :year => 2008}.each do |k,v|
    puts "#{k} is #{v}"
end
#make is audi
#color is black
#year is 2008

To answer the actual question:

Assuming that params is a hash, this would be the best way to map through it: Use two block parameters instead of one to capture the key & value pair for each interpreted tuple in the hash.

params = {"one" => 1, "two" => 2, "three" => 3}
params.each do |k,v|
  puts "#{k}=#{v}"
end
# one=1
# two=2
# three=3

How to make a script wait for a pressed key?

os.system seems to always invoke sh, which does not recognize the s and n options for read. However the read command can be passed to bash:

 os.system("""bash -c 'read -s -n 1 -p "Press any key to continue..."'""")

List all tables in postgresql information_schema

For private schema 'xxx' in postgresql :

SELECT table_name FROM information_schema.tables 
 WHERE table_schema = 'xxx' AND table_type = 'BASE TABLE'

Without table_type = 'BASE TABLE' , you will list tables and views

phpmyadmin logs out after 1440 secs

Steps for doing this using phpMyAdmin settings without any problem or requirements to change configs in php my.ini or defining .htaccess file:

  1. Goto your phpMyAdmin install path (ex. /usr/share/phpMyAdmin/ on my centos7) and find create_tables.sql in one of its subfolders (phpMyAdmin/sql/create_tables.sql in my 4.4.9 version.) and execute whole file contents on your current phpMyAdmin site from your web browser. This will create a database named phpmyadmin which can keep all your phpMyAdmin options saved permanently.
  2. In phpMyAdmin's config.inc.php (located on /etc/phpMyAdmin/ in my centos7 server) find the commented line $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin'; and uncomment it (Now phpMyAdmin will use that custom database we generated in previous step).
  3. Goto phpMyAdmin from web browser and goto Server >> Settings >> Features >> "Login Cookie Validity" as in picture described by Pavnish and set the desired value. It works now.

References: Niccolas Answer ,PhpMyAdmin Configuration Storage, flashMarks Answer

Error 415 Unsupported Media Type: POST not reaching REST if JSON, but it does if XML

I had the same issue, as it was giving error-415-unsupported-media-type while hitting post call using json while i already had the

@Consumes(MediaType.APPLICATION_JSON) 

and request headers as in my restful web service using Jersey 2.0+

Accept:application/json
Content-Type:application/json

I resolved this issue by adding following dependencies to my project

<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.25</version>
</dependency>

this will add following jars to your library :

  1. jersey-media-json-jackson-2.25.jar
  2. jersey-entity-filtering-2.25.jar
  3. jackson-module-jaxb-annotations-2.8.4.jar
  4. jackson-jaxrs-json-provider-2.8.4.jar
  5. jackson-jaxrs-base-2.8.4.jar

I hope it will works for others too as it did for me.

How to remove .html from URL?

With .htaccess under apache you can do the redirect like this:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\.html$ /$1 [L,R=301] 

As for removing of .html from the url, simply link to the page without .html

<a href="http://www.example.com/page">page</a>

Are there other whitespace codes like &nbsp for half-spaces, em-spaces, en-spaces etc useful in HTML?

Yes, many.

Including, but not limited to:

  • non breaking space : &#160; or &nbsp;
  • narrow no-break space : &#8239; (no character reference available)
  • en space : &#8194; or &ensp;
  • em space : &#8195; or &emsp;
  • 3-per-em space : &#8196; or &emsp13;
  • 4-per-em space : &#8197; or &emsp14;
  • 6-per-em space : &#8198; (no character reference available)
  • figure space : &#8199; or &numsp; 
  • punctuation space : &#8200; or &puncsp;
  • thin space : &#8201; or &thinsp;
  • hair space : &#8202; or &hairsp;

_x000D_
_x000D_
span{background-color: red;}
_x000D_
<table>_x000D_
<tr><td>non breaking space:</td><td> <span>&#160;</span> or <span>&nbsp;</span></td></tr>_x000D_
<tr><td>narrow no-break space:</td><td> <span>&#8239;</span></td></tr>_x000D_
<tr><td>en space:</td><td> <span>&#8194;</span> or <span>&ensp;</span></td></tr>_x000D_
<tr><td>em space:</td><td> <span>&#8195;</span> or <span>&emsp;</span></td></tr>_x000D_
<tr><td>3-per-em space:</td><td> <span>&#8196;</span> or <span>&emsp13;</span></td></tr>_x000D_
<tr><td>4-per-em space:</td><td> <span>&#8197;</span> or <span>&emsp14;</span></td></tr>_x000D_
<tr><td>6-per-em space:</td><td> <span>&#8198;</span></td></tr>_x000D_
<tr><td>figure space:</td><td> <span>&#8199;</span> or <span>&numsp;</span></td></tr>_x000D_
<tr><td>punctuation space:</td><td> <span>&#8200;</span> or <span>&puncsp;</td></tr>_x000D_
<tr><td>thin space:</td><td> <span>&#8201;</span> or <span>&thinsp;</span></td></tr>_x000D_
<tr><td>hair space:</td><td> <span>&#8202;</span> or <span>&hairsp;</span></td></tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How can I set up an editor to work with Git on Windows?

I've had difficulty getting Git to cooperate with WordPad, Komodo Edit and pretty much every other editor I give it. Most open for editing, but Git clearly doesn't wait for the save/close to happen.

As a crutch, I've just been doing i.e.

git commit -m "Fixed the LoadAll method"

to keep things moving. It tends to keep my commit messages a little shorter than they probably should be, but clearly there's some work to be done on the Windows version of Git.

The GitGUI also isn't that bad. It takes a little bit of orientation, but after that, it works fairly well.

Difference between Math.Floor() and Math.Truncate()

Math.floor() will always round down ie., it returns LESSER integer. While round() will return the NEAREST integer

math.floor()

Returns the largest integer less than or equal to the specified number.

math.truncate()

Calculates the integral part of a number.

Could not create the Java virtual machine

Set the JVM memory:

export _JAVA_OPTIONS=-Xmx512M

When to use 'npm start' and when to use 'ng serve'?

npm start will run whatever you have defined for the start command of the scripts object in your package.json file.

So if it looks like this:

"scripts": {
  "start": "ng serve"
}

Then npm start will run ng serve.

How can I validate google reCAPTCHA v2 using javascript/jQuery?

I used HarveyEV's solution but misread it and did it with jQuery validate instead of Bootstrap validator.

  <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
  <script>
    $("#contactForm").validate({
      submitHandler: function (form) {
        var response = grecaptcha.getResponse();
        //recaptcha failed validation
        if (response.length == 0) {
          $('#recaptcha-error').show();
          return false;
        }
          //recaptcha passed validation
        else {
          $('#recaptcha-error').hide();
          return true;
        }
      }
    });
  </script>

Why is my CSS style not being applied?

I know this is an old post but I thought I might add a thought for people who come across a similar problem. I'm assuming that you are using ASP.NET MVC since you mentioned site.css.

Check your Bundles.config file to see if you have BundleTable.EnableOptimizations = true; If you don't, then it can be your problem since this allows the program to be bundles and "minified". Depending on if you run in debug mode or not this could have an effect.

How to redirect to previous page in Ruby On Rails?

For those who are interested, here is my implementation extending MBO's original answer (written against rails 4.2.4, ruby 2.1.5).

class ApplicationController < ActionController::Base
  after_filter :set_return_to_location

  REDIRECT_CONTROLLER_BLACKLIST = %w(
    sessions
    user_sessions
    ...
    etc.
  )

  ...

  def set_return_to_location
    return unless request.get?
    return unless request.format.html?
    return unless %w(show index edit).include?(params[:action])
    return if REDIRECT_CONTROLLER_BLACKLIST.include?(controller_name)
    session[:return_to] = request.fullpath
  end

  def redirect_back_or_default(default_path = root_path)
    redirect_to(
      session[:return_to].present? && session[:return_to] != request.fullpath ?
        session[:return_to] : default_path
    )
  end
end

Is it possible to change the content HTML5 alert messages?

Yes:

<input required title="Enter something OR ELSE." /> 

The title attribute will be used to notify the user of a problem.

request exceeds the configured maxQueryStringLength when using [Authorize]

For anyone else that may encounter this problem and it is not solved by either of the options above, this is what worked for me.

1. Click on the website in IIS
2. Double Click on Authentication under IIS
3. Enable Anonymous Authentication

I had disabled this because we were using our own Auth, but that lead to this same problem and the accepted answer did not help in any way.

Conversion from List<T> to array T[]

list.ToArray()

Will do the tric. See here for details.

Load a WPF BitmapImage from a System.Drawing.Bitmap

// at class level;
[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);    // https://stackoverflow.com/a/1546121/194717


/// <summary> 
/// Converts a <see cref="System.Drawing.Bitmap"/> into a WPF <see cref="BitmapSource"/>. 
/// </summary> 
/// <remarks>Uses GDI to do the conversion. Hence the call to the marshalled DeleteObject. 
/// </remarks> 
/// <param name="source">The source bitmap.</param> 
/// <returns>A BitmapSource</returns> 
public static System.Windows.Media.Imaging.BitmapSource ToBitmapSource(this System.Drawing.Bitmap source)
{
    var hBitmap = source.GetHbitmap();
    var result = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, System.Windows.Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());

    DeleteObject(hBitmap);

    return result;
}

Plotting a python dict in order of key values

Python dictionaries are unordered. If you want an ordered dictionary, use collections.OrderedDict

In your case, sort the dict by key before plotting,

import matplotlib.pylab as plt

lists = sorted(d.items()) # sorted by key, return a list of tuples

x, y = zip(*lists) # unpack a list of pairs into two tuples

plt.plot(x, y)
plt.show()

Here is the result. enter image description here

symfony 2 twig limit the length of the text and put three dots

It is better to use an HTML character

{{ entity.text[:50] }}&#8230;

convert string to specific datetime format?

  <%= string_to_datetime("2011-05-19 10:30:14") %>

  def string_to_datetime(string,format="%Y-%m-%d %H:%M:%S")
    DateTime.strptime(string, format).to_time unless string.blank?
  end

Dynamic Web Module 3.0 -- 3.1

Open Eclipse project properties, in Project Facets unselect "Dynamic Web Module",... Click OK Maven -> Update project

Loop through files in a folder using VBA?

Here's my interpretation as a Function Instead:

'#######################################################################
'# LoopThroughFiles
'# Function to Loop through files in current directory and return filenames
'# Usage: LoopThroughFiles ActiveWorkbook.Path, "txt" 'inputDirectoryToScanForFile
'# https://stackoverflow.com/questions/10380312/loop-through-files-in-a-folder-using-vba
'#######################################################################
Function LoopThroughFiles(inputDirectoryToScanForFile, filenameCriteria) As String

    Dim StrFile As String
    'Debug.Print "in LoopThroughFiles. inputDirectoryToScanForFile: ", inputDirectoryToScanForFile

    StrFile = Dir(inputDirectoryToScanForFile & "\*" & filenameCriteria)
    Do While Len(StrFile) > 0
        Debug.Print StrFile
        StrFile = Dir

    Loop

End Function

Catch multiple exceptions in one line (except block)

How do I catch multiple exceptions in one line (except block)

Do this:

try:
    may_raise_specific_errors():
except (SpecificErrorOne, SpecificErrorTwo) as error:
    handle(error) # might log or have some other default behavior...

The parentheses are required due to older syntax that used the commas to assign the error object to a name. The as keyword is used for the assignment. You can use any name for the error object, I prefer error personally.

Best Practice

To do this in a manner currently and forward compatible with Python, you need to separate the Exceptions with commas and wrap them with parentheses to differentiate from earlier syntax that assigned the exception instance to a variable name by following the Exception type to be caught with a comma.

Here's an example of simple usage:

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError): # the parens are necessary
    sys.exit(0)

I'm specifying only these exceptions to avoid hiding bugs, which if I encounter I expect the full stack trace from.

This is documented here: https://docs.python.org/tutorial/errors.html

You can assign the exception to a variable, (e is common, but you might prefer a more verbose variable if you have long exception handling or your IDE only highlights selections larger than that, as mine does.) The instance has an args attribute. Here is an example:

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)

Note that in Python 3, the err object falls out of scope when the except block is concluded.

Deprecated

You may see code that assigns the error with a comma. This usage, the only form available in Python 2.5 and earlier, is deprecated, and if you wish your code to be forward compatible in Python 3, you should update the syntax to use the new form:

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError), err: # don't do this in Python 2.6+
    print err
    print err.args
    sys.exit(0)

If you see the comma name assignment in your codebase, and you're using Python 2.5 or higher, switch to the new way of doing it so your code remains compatible when you upgrade.

The suppress context manager

The accepted answer is really 4 lines of code, minimum:

try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass

The try, except, pass lines can be handled in a single line with the suppress context manager, available in Python 3.4:

from contextlib import suppress

with suppress(IDontLikeYouException, YouAreBeingMeanException):
     do_something()

So when you want to pass on certain exceptions, use suppress.

Expression must have class type

It's a pointer, so instead try:

a->f();

Basically the operator . (used to access an object's fields and methods) is used on objects and references, so:

A a;
a.f();
A& ref = a;
ref.f();

If you have a pointer type, you have to dereference it first to obtain a reference:

A* ptr = new A();
(*ptr).f();
ptr->f();

The a->b notation is usually just a shorthand for (*a).b.

A note on smart pointers

The operator-> can be overloaded, which is notably used by smart pointers. When you're using smart pointers, then you also use -> to refer to the pointed object:

auto ptr = make_unique<A>();
ptr->f();

Get the value of a dropdown in jQuery

If you're using a <select>, .val() gets the 'value' of the selected <option>. If it doesn't have a value, it may fallback to the id. Put the value you want it to return in the value attribute of each <option>

Edit: See comments for clarification on what value actually is (not necessarily equal to the value attribute).

reading external sql script in python

according me, it is not possible

solution:

  1. import .sql file on mysql server

  2. after

    import mysql.connector
    import pandas as pd
    

    and then you use .sql file by convert to dataframe

c# why can't a nullable int be assigned null as a value

Another option is to use

int? accom = (accomStr == "noval" ? Convert.DBNull : Convert.ToInt32(accomStr); 

I like this one most.

EXCEL VBA, inserting blank row and shifting cells

If you want to just shift everything down you can use:

Rows(1).Insert shift:=xlShiftDown

Similarly to shift everything over:

Columns(1).Insert shift:=xlShiftRight

git undo all uncommitted or unsaved changes

I'm using source tree.... You can do revert all uncommitted changes with 2 easy steps:

1) just need to reset the workspace file status

enter image description here 2) select all unstage files (command +a), right click and select remove

enter image description here

It's that simple :D

How to apply !important using .css()?

I had the same problem trying to change a text color of a menu-item when "event". The best way I found when I had this same problem was:

First step: Create, in your CSS, a new class with this purpose, for example:

.colorw{ color: white !important;}

Last step: Apply this class using the addClass method as follows:

$('.menu-item>a').addClass('colorw');

Problem solved.

How do you attach and detach from Docker's process?

Check out also the --sig-proxy option:

docker attach --sig-proxy=false 304f5db405ec

Then use CTRL+c to detach

SQL Server : error converting data type varchar to numeric

If you are running SQL Server 2012 or newer you can also use the new TRY_PARSE() function:

Returns the result of an expression, translated to the requested data type, or null if the cast fails in SQL Server. Use TRY_PARSE only for converting from string to date/time and number types.

Or TRY_CONVERT/TRY_CAST:

Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.

@Value annotation type casting to Integer from String

This problem also occurs when you have 2 resources with the same file name; say "configurations.properties" within 2 different jar or directory path configured within the classpath. For example:

You have your "configurations.properties" in your process or web application (jar, war or ear). But another dependency (jar) have the same file "configurations.properties" in the same path. Then I suppose that Spring have no idea (@_@?) where to get the property and just sends the property name declared within the @Value annotation.

PHP Warning: include_once() Failed opening '' for inclusion (include_path='.;C:\xampp\php\PEAR')

It is because you use a relative path.

The easy way to fix this is by using the __DIR__ magic constant, like:

require_once(__DIR__."/initcontrols/config.php");

From the PHP doc:

The directory of the file. If used inside an include, the directory of the included file is returned

Change button background color using swift language

U can also play around the tintcolor and button image to indirectly change the color.

how to transfer a file through SFTP in java?

Try this code.

public void send (String fileName) {
    String SFTPHOST = "host:IP";
    int SFTPPORT = 22;
    String SFTPUSER = "username";
    String SFTPPASS = "password";
    String SFTPWORKINGDIR = "file/to/transfer";

    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;
    System.out.println("preparing the host information for sftp.");

    try {
        JSch jsch = new JSch();
        session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
        session.setPassword(SFTPPASS);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        System.out.println("Host connected.");
        channel = session.openChannel("sftp");
        channel.connect();
        System.out.println("sftp channel opened and connected.");
        channelSftp = (ChannelSftp) channel;
        channelSftp.cd(SFTPWORKINGDIR);
        File f = new File(fileName);
        channelSftp.put(new FileInputStream(f), f.getName());
        log.info("File transfered successfully to host.");
    } catch (Exception ex) {
        System.out.println("Exception found while tranfer the response.");
    } finally {
        channelSftp.exit();
        System.out.println("sftp Channel exited.");
        channel.disconnect();
        System.out.println("Channel disconnected.");
        session.disconnect();
        System.out.println("Host Session disconnected.");
    }
}   

Formatting a double to two decimal places

    double d =  3.1493745;
    string s = $"{d:0.00}"; // or $"{d:#.##}"
    Console.WriteLine(s); // Displays 3.15

Python: download a file from an FTP server

requests library doesn't support ftp links.

To download a file from FTP server you could:

import urllib 

urllib.urlretrieve('ftp://server/path/to/file', 'file')
# if you need to pass credentials:
#   urllib.urlretrieve('ftp://username:password@server/path/to/file', 'file')

Or:

import shutil
import urllib2
from contextlib import closing

with closing(urllib2.urlopen('ftp://server/path/to/file')) as r:
    with open('file', 'wb') as f:
        shutil.copyfileobj(r, f)

Python3:

import shutil
import urllib.request as request
from contextlib import closing

with closing(request.urlopen('ftp://server/path/to/file')) as r:
    with open('file', 'wb') as f:
        shutil.copyfileobj(r, f)

How to enable or disable an anchor using jQuery?

$("a").click(function(){
                alert('disabled');
                return false;

}); 

Detect if the device is iPhone X

To detect any of the devices by using simple methods. like below,

func isPhoneDevice() -> Bool {
    return UIDevice.current.userInterfaceIdiom == .phone
}

func isDeviceIPad() -> Bool {
    return UIDevice.current.userInterfaceIdiom == .pad
}

func isPadProDevice() -> Bool {
    let SCREEN_WIDTH: CGFloat = UIScreen.main.bounds.size.width
    let SCREEN_HEIGHT: CGFloat = UIScreen.main.bounds.size.height
    let SCREEN_MAX_LENGTH: CGFloat = fmax(SCREEN_WIDTH, SCREEN_HEIGHT)

    return UIDevice.current.userInterfaceIdiom == .pad && SCREEN_MAX_LENGTH == 1366.0
}

func isPhoneXandXSDevice() -> Bool {
    let SCREEN_WIDTH = CGFloat(UIScreen.main.bounds.size.width)
    let SCREEN_HEIGHT = CGFloat(UIScreen.main.bounds.size.height)
    let SCREEN_MAX_LENGTH: CGFloat = fmax(SCREEN_WIDTH, SCREEN_HEIGHT)

    return UIDevice.current.userInterfaceIdiom == .phone && SCREEN_MAX_LENGTH == 812.0
}

func isPhoneXSMaxandXRDevice() -> Bool {
    let SCREEN_WIDTH = CGFloat(UIScreen.main.bounds.size.width)
    let SCREEN_HEIGHT = CGFloat(UIScreen.main.bounds.size.height)
    let SCREEN_MAX_LENGTH: CGFloat = fmax(SCREEN_WIDTH, SCREEN_HEIGHT)

    return UIDevice.current.userInterfaceIdiom == .phone && SCREEN_MAX_LENGTH == 896.0
}

and call like this,

if isPhoneDevice() {
     // Your code
}

how to set background image in submit button?

Typically one would use one (or more) image tags, maybe in combination with setting div background images in css to act as the submit button. The actual submit would be done in javascript on the click event.

A tutorial on the subject.

Copy file(s) from one project to another using post build event...VS2010

I use it like this.

xcopy "$(TargetDir)$(TargetName).dll" "$(SolutionDir)Lib\TIRM\x86\" /F /Y 
xcopy "$(TargetDir)$(TargetName).lib" "$(SolutionDir)Lib\TIRM\x86\" /F /Y 


/F : Copy source is File   
/Y : Overwrite and don't ask me

Note the use of this. $(TargetDir) has already '\' "D:\MyProject\bin\" = $(TargetDir)

You can find macro in Command editor

enter image description here

How to check if a string "StartsWith" another string?

Here is a minor improvement to CMS's solution:

if(!String.prototype.startsWith){
    String.prototype.startsWith = function (str) {
        return !this.indexOf(str);
    }
}

"Hello World!".startsWith("He"); // true

 var data = "Hello world";
 var input = 'He';
 data.startsWith(input); // true

Checking whether the function already exists in case a future browser implements it in native code or if it is implemented by another library. For example, the Prototype Library implements this function already.

Using ! is slightly faster and more concise than === 0 though not as readable.

How do you check if a selector matches something in jQuery?

no, jquery always returns a jquery object regardless if a selector was matched or not. You need to use .length

if ( $('#someDiv').length ){

}

How to remove "onclick" with JQuery?

It is very easy using removeAttr.

$(element).removeAttr("onclick");

Sum rows in data.frame or matrix

I came here hoping to find a way to get the sum across all columns in a data table and run into issues implementing the above solutions. A way to add a column with the sum across all columns uses the cbind function:

cbind(data, total = rowSums(data))

This method adds a total column to the data and avoids the alignment issue yielded when trying to sum across ALL columns using the above solutions (see the post below for a discussion of this issue).

Adding a new column to matrix error

PHP function to make slug (URL string)

public static function slugify ($text) {

    $replace = [
        '&lt;' => '', '&gt;' => '', '&#039;' => '', '&amp;' => '',
        '&quot;' => '', 'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä'=> 'Ae',
        '&Auml;' => 'A', 'Å' => 'A', 'A' => 'A', 'A' => 'A', 'A' => 'A', 'Æ' => 'Ae',
        'Ç' => 'C', 'C' => 'C', 'C' => 'C', 'C' => 'C', 'C' => 'C', 'D' => 'D', 'Ð' => 'D',
        'Ð' => 'D', 'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'E' => 'E',
        'E' => 'E', 'E' => 'E', 'E' => 'E', 'E' => 'E', 'G' => 'G', 'G' => 'G',
        'G' => 'G', 'G' => 'G', 'H' => 'H', 'H' => 'H', 'Ì' => 'I', 'Í' => 'I',
        'Î' => 'I', 'Ï' => 'I', 'I' => 'I', 'I' => 'I', 'I' => 'I', 'I' => 'I',
        'I' => 'I', '?' => 'IJ', 'J' => 'J', 'K' => 'K', 'L' => 'K', 'L' => 'K',
        'L' => 'K', 'L' => 'K', '?' => 'K', 'Ñ' => 'N', 'N' => 'N', 'N' => 'N',
        'N' => 'N', '?' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O',
        'Ö' => 'Oe', '&Ouml;' => 'Oe', 'Ø' => 'O', 'O' => 'O', 'O' => 'O', 'O' => 'O',
        'Œ' => 'OE', 'R' => 'R', 'R' => 'R', 'R' => 'R', 'S' => 'S', 'Š' => 'S',
        'S' => 'S', 'S' => 'S', '?' => 'S', 'T' => 'T', 'T' => 'T', 'T' => 'T',
        '?' => 'T', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'Ue', 'U' => 'U',
        '&Uuml;' => 'Ue', 'U' => 'U', 'U' => 'U', 'U' => 'U', 'U' => 'U', 'U' => 'U',
        'W' => 'W', 'Ý' => 'Y', 'Y' => 'Y', 'Ÿ' => 'Y', 'Z' => 'Z', 'Ž' => 'Z',
        'Z' => 'Z', 'Þ' => 'T', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a',
        'ä' => 'ae', '&auml;' => 'ae', 'å' => 'a', 'a' => 'a', 'a' => 'a', 'a' => 'a',
        'æ' => 'ae', 'ç' => 'c', 'c' => 'c', 'c' => 'c', 'c' => 'c', 'c' => 'c',
        'd' => 'd', 'd' => 'd', 'ð' => 'd', 'è' => 'e', 'é' => 'e', 'ê' => 'e',
        'ë' => 'e', 'e' => 'e', 'e' => 'e', 'e' => 'e', 'e' => 'e', 'e' => 'e',
        'ƒ' => 'f', 'g' => 'g', 'g' => 'g', 'g' => 'g', 'g' => 'g', 'h' => 'h',
        'h' => 'h', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'i' => 'i',
        'i' => 'i', 'i' => 'i', 'i' => 'i', 'i' => 'i', '?' => 'ij', 'j' => 'j',
        'k' => 'k', '?' => 'k', 'l' => 'l', 'l' => 'l', 'l' => 'l', 'l' => 'l',
        '?' => 'l', 'ñ' => 'n', 'n' => 'n', 'n' => 'n', 'n' => 'n', '?' => 'n',
        '?' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'oe',
        '&ouml;' => 'oe', 'ø' => 'o', 'o' => 'o', 'o' => 'o', 'o' => 'o', 'œ' => 'oe',
        'r' => 'r', 'r' => 'r', 'r' => 'r', 'š' => 's', 'ù' => 'u', 'ú' => 'u',
        'û' => 'u', 'ü' => 'ue', 'u' => 'u', '&uuml;' => 'ue', 'u' => 'u', 'u' => 'u',
        'u' => 'u', 'u' => 'u', 'u' => 'u', 'w' => 'w', 'ý' => 'y', 'ÿ' => 'y',
        'y' => 'y', 'ž' => 'z', 'z' => 'z', 'z' => 'z', 'þ' => 't', 'ß' => 'ss',
        '?' => 'ss', '??' => 'iy', '?' => 'A', '?' => 'B', '?' => 'V', '?' => 'G',
        '?' => 'D', '?' => 'E', '?' => 'YO', '?' => 'ZH', '?' => 'Z', '?' => 'I',
        '?' => 'Y', '?' => 'K', '?' => 'L', '?' => 'M', '?' => 'N', '?' => 'O',
        '?' => 'P', '?' => 'R', '?' => 'S', '?' => 'T', '?' => 'U', '?' => 'F',
        '?' => 'H', '?' => 'C', '?' => 'CH', '?' => 'SH', '?' => 'SCH', '?' => '',
        '?' => 'Y', '?' => '', '?' => 'E', '?' => 'YU', '?' => 'YA', '?' => 'a',
        '?' => 'b', '?' => 'v', '?' => 'g', '?' => 'd', '?' => 'e', '?' => 'yo',
        '?' => 'zh', '?' => 'z', '?' => 'i', '?' => 'y', '?' => 'k', '?' => 'l',
        '?' => 'm', '?' => 'n', '?' => 'o', '?' => 'p', '?' => 'r', '?' => 's',
        '?' => 't', '?' => 'u', '?' => 'f', '?' => 'h', '?' => 'c', '?' => 'ch',
        '?' => 'sh', '?' => 'sch', '?' => '', '?' => 'y', '?' => '', '?' => 'e',
        '?' => 'yu', '?' => 'ya'
    ];

    // make a human readable string
    $text = strtr($text, $replace);

    // replace non letter or digits by -
    $text = preg_replace('~[^\\pL\d.]+~u', '-', $text);

    // trim
    $text = trim($text, '-');

    // remove unwanted characters
    $text = preg_replace('~[^-\w.]+~', '', $text);

    $text = strtolower($text);

    return $text;
}

How do I resolve git saying "Commit your changes or stash them before you can merge"?

This solved my error:

I am on branch : "A"

git stash

Move to master branch:

git checkout master <br>
git pull*

Move back to my branch: "A"

git checkout A <br>
git stash pop*

Is header('Content-Type:text/plain'); necessary at all?

Setting the Content-Type header will affect how a web browser treats your content. When most mainstream web browsers encounter a Content-Type of text/plain, they'll render the raw text source in the browser window (as opposed to the source rendered at HTML). It's the difference between seeing

<b>foo</b>

or

foo

Additionally, when using the XMLHttpRequest object, your Content-Type header will affect how the browser serializes the returned results. Prior to the takeover of AJAX frameworks like jQuery and Prototype, a common problem with AJAX responses was a Content-Type set to text/html instead of text/xml. Similar problems would likely occur if the Content-Type was text/plain.

How do you make sure email you send programmatically is not automatically marked as spam?

Confirm that you have the correct email address before sending out emails. If someone gives the wrong email address on sign-up, beat them over the head about it ASAP.

Always include clear "how to unsubscribe" information in EVERY email. Do not require the user to login to unsubscribe, it should be a unique url for 1-click unsubscribe.

This will prevent people from marking your mails as spam because "unsubscribing" is too hard.

Convert Datetime column from UTC to local time in select statement

You have to reformat the string as well as converting to the correct time. In this case I needed Zulu time.

Declare @Date datetime;
Declare @DateString varchar(50);
set @Date = GETDATE(); 
declare @ZuluTime datetime;

Declare @DateFrom varchar (50);
Declare @DateTo varchar (50);
set @ZuluTime = DATEADD(second, DATEDIFF(second, GETDATE(), GETUTCDATE()), @Date);
set @DateString =  FORMAT(@ZuluTime, 'yyyy-MM-ddThh:mm:ssZ', 'en-US' )  
select @DateString;

How to move table from one tablespace to another in oracle 11g

I tried many scripts but they didn't work for all objects. You can't move clustered objects from one tablespace to another. For that you will have to use expdp, so I will suggest expdp is the best option to move all objects to a different tablespace.

Below is the command:

nohup expdp \"/ as sysdba\" DIRECTORY=test_dir DUMPFILE=users.dmp LOGFILE=users.log TABLESPACES=USERS &

You can check this link for details.

How to return more than one value from a function in Python?

You separate the values you want to return by commas:

def get_name():
   # you code
   return first_name, last_name

The commas indicate it's a tuple, so you could wrap your values by parentheses:

return (first_name, last_name)

Then when you call the function you a) save all values to one variable as a tuple, or b) separate your variable names by commas

name = get_name() # this is a tuple
first_name, last_name = get_name()
(first_name, last_name) = get_name() # You can put parentheses, but I find it ugly

Return in Scala

By default the last expression of a function will be returned. In your example there is another expression after the point, where you want your return value. If you want to return anything prior to your last expression, you still have to use return.

You could modify your example like this, to return a Boolean from the first part

def balanceMain(elem: List[Char]): Boolean = {
  if (elem.isEmpty) {
    // == is a Boolean resulting function as well, so your can write it this way
    count == 0
  } else {
    // keep the rest in this block, the last value will be returned as well
    if (elem.head == "(") {
      balanceMain(elem.tail, open, count + 1)
    }
    // some more statements
    ...
    // just don't forget your Boolean in the end
    someBoolExpression
  }
}

How to make space between LinearLayout children?

Try to add Space widget after adding view like this:

layout.addView(view)
val space = Space(context)
space.minimumHeight = spaceInterval
layout.addView(space)

How to access a RowDataPacket object

Turns out they are normal objects and you can access them through user_id.

RowDataPacket is actually the name of the constructor function that creates an object, it would look like this new RowDataPacket(user_id, ...). You can check by accessing its name [0].constructor.name

If the result is an array, you would have to use [0].user_id.

Django: multiple models in one template using forms

I currently have a workaround functional (it passes my unit tests). It is a good solution to my opinion when you only want to add a limited number of fields from other models.

Am I missing something here ?

class UserProfileForm(ModelForm):
    def __init__(self, instance=None, *args, **kwargs):
        # Add these fields from the user object
        _fields = ('first_name', 'last_name', 'email',)
        # Retrieve initial (current) data from the user object
        _initial = model_to_dict(instance.user, _fields) if instance is not None else {}
        # Pass the initial data to the base
        super(UserProfileForm, self).__init__(initial=_initial, instance=instance, *args, **kwargs)
        # Retrieve the fields from the user model and update the fields with it
        self.fields.update(fields_for_model(User, _fields))

    class Meta:
        model = UserProfile
        exclude = ('user',)

    def save(self, *args, **kwargs):
        u = self.instance.user
        u.first_name = self.cleaned_data['first_name']
        u.last_name = self.cleaned_data['last_name']
        u.email = self.cleaned_data['email']
        u.save()
        profile = super(UserProfileForm, self).save(*args,**kwargs)
        return profile

Extracting substrings in Go

Go strings are not null terminated, and to remove the last char of a string you can simply do:

s = s[:len(s)-1]

How can I update a row in a DataTable in VB.NET?

The problem you're running into is that you're trying to replace an entire row object. That is not allowed by the DataTable API. Instead you have to update the values in the columns of a row object. Or add a new row to the collection.

To update the column of a particular row you can access it by name or index. For instance you could write the following code to update the column "Foo" to be the value strVerse

dtResult.Rows(i)("Foo") = strVerse

Font Awesome 5 font-family issue

Using the fontawesome-all.css file: Changing the "Brands" font-family from "Font Awesome 5 Free" to "Font Awesome 5 Brands" fixed the issues I was having.

I can't take all of the credit - I fixed my own local issue right before looking at the CDN version: https://use.fontawesome.com/releases/v5.0.6/css/all.css

They've got the issue sorted out on the CDN as well.

_x000D_
_x000D_
 @font-face {_x000D_
    font-family: 'Font Awesome 5 Brands';_x000D_
    font-style: normal;_x000D_
    font-weight: normal;_x000D_
    src: url("../webfonts/fa-brands-400.eot");_x000D_
    src: url("../webfonts/fa-brands-400.eot?#iefix") format("embedded-opentype"), url("../webfonts/fa-brands-400.woff2") format("woff2"), url("../webfonts/fa-brands-400.woff") format("woff"), url("../webfonts/fa-brands-400.ttf") format("truetype"), url("../webfonts/fa-brands-400.svg#fontawesome") format("svg"); }_x000D_
_x000D_
    .fab {_x000D_
    font-family: 'Font Awesome 5 Brands'; }_x000D_
    @font-face {_x000D_
    font-family: 'Font Awesome 5 Brands';_x000D_
    font-style: normal;_x000D_
    font-weight: 400;_x000D_
    src: url("../webfonts/fa-regular-400.eot");_x000D_
  src: url("../webfonts/fa-regular-400.eot?#iefix") format("embedded-opentype"), url("../webfonts/fa-regular-400.woff2") format("woff2"), url("../webfonts/fa-regular-400.woff") format("woff"), url("../webfonts/fa-regular-400.ttf") format("truetype"), url("../webfonts/fa-regular-400.svg#fontawesome") format("svg"); }
_x000D_
_x000D_
_x000D_

java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of

I got the same error and the issue was that I was on VPN and I didn't realize it. After disconnecting from the VPN and reconnecting to my WIFI network, the problem was resolved.

What is the definition of "interface" in object oriented programming

In my opinion, interface has a broader meaning than the one commonly associated with it in Java. I would define "interface" as a set of available operations with some common functionality, that allow controlling/monitoring a module.

In this definition I try to cover both programatic interfaces, where the client is some module, and human interfaces (GUI for example).

As others already said, an interface always has some contract behind it, in terms of inputs and outputs. The interface does not promise anything about the "how" of the operations; it only guarantees some properties of the outcome, given the current state, the selected operation and its parameters.

CodeIgniter 500 Internal Server Error

Just in case somebody else stumbles across this problem, I inherited an older CodeIgniter project and had a lot of trouble getting it to install.

I wasted a ton of time trying to create a local installation of the site and tried everything. In the end, the solution was simple.

The problem is that older CodeIgniter versions (like 1.7 and below), don't work with PHP 5.3. The solution is to switch to PHP 5.2 or something older.

Comparing strings in Java

You need both getText() - which returns an Editable and toString() - to convert that to a String for matching. So instead of: passw1.toString().equalsIgnoreCase("1234") you need passw1.getText().toString().equalsIgnoreCase("1234").

how get yesterday and tomorrow datetime in c#

Beware of adding an unwanted timezone to your results, especially if the date is going to be sent out via a Web API. Use UtcNow instead, to make it timezone-less.

LPCSTR, LPCTSTR and LPTSTR

Adding to John and Tim's answer.

Unless you are coding for Win98, there are only two of the 6+ string types you should be using in your application

  • LPWSTR
  • LPCWSTR

The rest are meant to support ANSI platforms or dual compilations. Those are not as relevant today as they used to be.

What is this: [Ljava.lang.Object;?

[Ljava.lang.Object; is the name for Object[].class, the java.lang.Class representing the class of array of Object.

The naming scheme is documented in Class.getName():

If this class object represents a reference type that is not an array type then the binary name of the class is returned, as specified by the Java Language Specification (§13.1).

If this class object represents a primitive type or void, then the name returned is the Java language keyword corresponding to the primitive type or void.

If this class object represents a class of arrays, then the internal form of the name consists of the name of the element type preceded by one or more '[' characters representing the depth of the array nesting. The encoding of element type names is as follows:

Element Type        Encoding
boolean             Z
byte                B
char                C
double              D
float               F
int                 I
long                J
short               S 
class or interface  Lclassname;

Yours is the last on that list. Here are some examples:

// xxxxx varies
System.out.println(new int[0][0][7]); // [[[I@xxxxx
System.out.println(new String[4][2]); // [[Ljava.lang.String;@xxxxx
System.out.println(new boolean[256]); // [Z@xxxxx

The reason why the toString() method on arrays returns String in this format is because arrays do not @Override the method inherited from Object, which is specified as follows:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Note: you can not rely on the toString() of any arbitrary object to follow the above specification, since they can (and usually do) @Override it to return something else. The more reliable way of inspecting the type of an arbitrary object is to invoke getClass() on it (a final method inherited from Object) and then reflecting on the returned Class object. Ideally, though, the API should've been designed such that reflection is not necessary (see Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection).


On a more "useful" toString for arrays

java.util.Arrays provides toString overloads for primitive arrays and Object[]. There is also deepToString that you may want to use for nested arrays.

Here are some examples:

int[] nums = { 1, 2, 3 };

System.out.println(nums);
// [I@xxxxx

System.out.println(Arrays.toString(nums));
// [1, 2, 3]

int[][] table = {
        { 1, },
        { 2, 3, },
        { 4, 5, 6, },
};

System.out.println(Arrays.toString(table));
// [[I@xxxxx, [I@yyyyy, [I@zzzzz]

System.out.println(Arrays.deepToString(table));
// [[1], [2, 3], [4, 5, 6]]

There are also Arrays.equals and Arrays.deepEquals that perform array equality comparison by their elements, among many other array-related utility methods.

Related questions

How to read an external local JSON file in JavaScript?

You can import It like ES6 module;

import data from "/Users/Documents/workspace/test.json"

Should I add the Visual Studio .suo and .user files to source control?

We don't commit the binary file (*.suo), but we commit the .user file. The .user file contains for example the start options for debugging the project. You can find the start options in the properties of the project in the tab "Debug". We used NUnit in some projects and configured the nunit-gui.exe as the start option for the project. Without the .user file, each team member would have to configure it separately.

Hope this helps.

npm install error from the terminal

In my case it was due to a bad URL (http:// instead of git://, no .git at the end) for one of the dependencies.

Auto-redirect to another HTML page

You can use <meta> tag refresh, and <meta> tag in <head> section

<META http-equiv="refresh" content="5;URL=your_url"> 

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

Use the zzz format specifier to get the timezone offset as hours and minutes. You also want to use the HH format specifier to get the hours in 24 hour format.

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

Result:

2011-08-09T23:49:58+02:00

Some culture settings uses periods instead of colons for time, so you might want to use literal colons instead of time separators:

DateTime.Now.ToString("yyyy-MM-ddTHH':'mm':'sszzz")

Custom Date and Time Format Strings

SQL Server - Case Statement

The query can be written slightly simpler, like this:

DECLARE @T INT = 2 

SELECT CASE 
         WHEN @T < 1 THEN 'less than one' 
         WHEN @T = 1 THEN 'one' 
         ELSE 'greater than one' 
       END T

How to provide a file download from a JSF backing bean?

Introduction

You can get everything through ExternalContext. In JSF 1.x, you can get the raw HttpServletResponse object by ExternalContext#getResponse(). In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream() without the need to grab the HttpServletResponse from under the JSF hoods.

On the response, you should set the Content-Type header so that the client knows which application to associate with the provided file. And, you should set the Content-Length header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition header to attachment if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.

Most important part is to call FacesContext#responseComplete() to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException with a message like getoutputstream() has already been called for this response when the JSF implementation calls getWriter() to render HTML.

Turn off ajax / don't use remote command!

You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink> and <h:commandButton>. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.

In case you're using e.g. PrimeFaces <p:commandXxx>, then you need to make sure that you explicitly turn off ajax via ajax="false" attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" /> in the command component.

Generic JSF 2.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();

    ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
    ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = ec.getResponseOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Generic JSF 1.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

    response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
    response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = response.getOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Common static file example

In case you need to stream a static file from the local disk file system, substitute the code as below:

File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();

// ...

Files.copy(file.toPath(), output);

Common dynamic file example

In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output there where the API being used expects an OutputStream.

E.g. iText PDF:

String fileName = "dynamic.pdf";
String contentType = "application/pdf";

// ...

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();

E.g. Apache POI HSSF:

String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";

// ...

HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();

Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.

Utility method

If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile() methods taking either a File, or an InputStream, or a byte[], and specifying whether the file should be downloaded as an attachment (true) or inline (false).

public void download() throws IOException {
    Faces.sendFile(file, true);
}

Yes, this code is complete as-is. You don't need to invoke responseComplete() and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.

What's the difference between django OneToOneField and ForeignKey?

The best and the most effective way to learn new things is to see and study real world practical examples. Suppose for a moment that you want to build a blog in django where reporters can write and publish news articles. The owner of the online newspaper wants to allow each of his reporters to publish as many articles as they want, but does not want different reporters to work on the same article. This means that when readers go and read an article they will se only one author in the article.

For example: Article by John, Article by Harry, Article by Rick. You can not have Article by Harry & Rick because the boss does not want two or more authors to work on the same article.

How can we solve this 'problem' with the help of django? The key to the solution of this problem is the django ForeignKey.

The following is the full code which can be used to implement the idea of our boss.

from django.db import models

# Create your models here.

class Reporter(models.Model):
    first_name = models.CharField(max_length=30)

    def __unicode__(self):
        return self.first_name


class Article(models.Model):
    title = models.CharField(max_length=100)
    reporter = models.ForeignKey(Reporter)

    def __unicode__(self):
        return self.title

Run python manage.py syncdb to execute the sql code and build the tables for your app in your database. Then use python manage.py shell to open a python shell.

Create the Reporter object R1.

In [49]: from thepub.models import Reporter, Article

In [50]: R1 = Reporter(first_name='Rick')

In [51]: R1.save()

Create the Article object A1.

In [5]: A1 = Article.objects.create(title='TDD In Django', reporter=R1)

In [6]: A1.save()

Then use the following piece of code to get the name of the reporter.

In [8]: A1.reporter.first_name
Out[8]: 'Rick'

Now create the Reporter object R2 by running the following python code.

In [9]: R2 = Reporter.objects.create(first_name='Harry')

In [10]: R2.save()

Now try to add R2 to the Article object A1.

In [13]: A1.reporter.add(R2)

It does not work and you will get an AttributeError saying 'Reporter' object has no attribute 'add'.

As you can see an Article object can not be related to more than one Reporter object.

What about R1? Can we attach more than one Article objects to it?

In [14]: A2 = Article.objects.create(title='Python News', reporter=R1)

In [15]: R1.article_set.all()
Out[15]: [<Article: Python News>, <Article: TDD In Django>]

This practical example shows us that django ForeignKey is used to define many-to-one relationships.

OneToOneField is used to create one-to-one relationships.

We can use reporter = models.OneToOneField(Reporter) in the above models.py file but it is not going to be useful in our example as an author will not be able to post more than one article.

Each time you want to post a new article you will have to create a new Reporter object. This is time consuming, isn't it?

I highly recommend to try the example with the OneToOneField and realize the difference. I am pretty sure that after this example you will completly know the difference between django OneToOneField and django ForeignKey.

How can I create download link in HTML?

To link to the file, do the same as any other page link:

<a href="...">link text</a>

To force things to download even if they have an embedded plugin (Windows + QuickTime = ugh), you can use this in your htaccess / apache2.conf:

AddType application/octet-stream EXTENSION

Fill Combobox from database

You will have to completely re-write your code. DisplayMember and ValueMember point to columnNames! Furthermore you should really use a using block - so the connection gets disposed (and closed) after query execution.

Instead of using a dataReader to access the values I choosed a dataTable and bound it as dataSource onto the comboBox.

using (SqlConnection conn = new SqlConnection(@"Data Source=SHARKAWY;Initial Catalog=Booking;Persist Security Info=True;User ID=sa;Password=123456"))
{
    try
    {
        string query = "select FleetName, FleetID from fleets";
        SqlDataAdapter da = new SqlDataAdapter(query, conn);
        conn.Open();
        DataSet ds = new DataSet();
        da.Fill(ds, "Fleet");
        cmbTripName.DisplayMember =  "FleetName";
        cmbTripName.ValueMember = "FleetID";
        cmbTripName.DataSource = ds.Tables["Fleet"];
    }
    catch (Exception ex)
    {
        // write exception info to log or anything else
        MessageBox.Show("Error occured!");
    }               
}

Using a dataTable may be a little bit slower than a dataReader but I do not have to create my own class. If you really have to/want to make use of a DataReader you may choose @Nattrass approach. In any case you should write a using block!

EDIT

If you want to get the current Value of the combobox try this

private void cmbTripName_SelectedIndexChanged(object sender, EventArgs e)
{
    if (cmbTripName.SelectedItem != null)
    {
        DataRowView drv = cmbTripName.SelectedItem as DataRowView;

        Debug.WriteLine("Item: " + drv.Row["FleetName"].ToString());
        Debug.WriteLine("Value: " + drv.Row["FleetID"].ToString());
        Debug.WriteLine("Value: " + cmbTripName.SelectedValue.ToString());
    }
}

Count character occurrences in a string in C++

You name it... Lambda version... :)

using namespace boost::lambda;

std::string s = "a_b_c";
std::cout << std::count_if (s.begin(), s.end(), _1 == '_') << std::endl;

You need several includes... I leave you that as an exercise...

What is the difference between Integer and int in Java?

In Java int is a primitive data type while Integer is a Helper class, it is use to convert for one data type to other.

For example:

         double doubleValue = 156.5d;
         Double doubleObject  = new Double(doubleValue);
         Byte myByteValue = doubleObject.byteValue ();
         String myStringValue = doubleObject.toString();

Primitive data types are store the fastest available memory where the Helper class is complex and store in heap memory.

reference from "David Gassner" Java Essential Training.

How can I get the source code of a Python function?

If the function is from a source file available on the filesystem, then inspect.getsource(foo) might be of help:

If foo is defined as:

def foo(arg1,arg2):         
    #do something with args 
    a = arg1 + arg2         
    return a  

Then:

import inspect
lines = inspect.getsource(foo)
print(lines)

Returns:

def foo(arg1,arg2):         
    #do something with args 
    a = arg1 + arg2         
    return a                

But I believe that if the function is compiled from a string, stream or imported from a compiled file, then you cannot retrieve its source code.

document.getElementByID is not a function

There are several things wrong with this as you can see in the other posts, but the reason you're getting that error is because you name your form getElementById. So document.getElementById now points to your form instead of the default method that javascript provides. See my fiddle for a working demo https://jsfiddle.net/jemartin80/nhjehwqk/.

function checkValues()
{
   var isFormValid, form_fname;

   isFormValid = true;
   form_fname = document.getElementById("fname");
   if (form_fname.value === "")
   {
       isFormValid = false;
   }
   isFormValid || alert("I am indicating that there is something wrong with your input.")

   return isFormValid;
}

This action could not be completed. Try Again (-22421)

The problem can not be solved with xCode Upload Process. I was facing same issues few days ago when submitting few of my apps and all apps showing same error. After many tries, I used Application Loader to upload app and it worked.

  1. First go to xcode -> product menu -> archive
  2. Select Export for Appstore
  3. Save IPA file
  4. Now Open Application loader by going to xCode -> xCode Menu -> Open Developer Tool -> Application Loader
  5. Login with the credentials of account, and select the IPA file.

Submit it! It works!

Multiline strings in VB.NET

Multiline string literals are introduced in Visual Basic 14.0 - https://roslyn.codeplex.com/discussions/571884

You can use then in the VS2015 Preview, out now - http://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs (note that you can still use VS2015 even when targeting an older version of the .NET framework)

Dim multiline = "multi
line
string"

VB strings are basically now the same as C# verbatim strings - they don't support backslash escape sequences like \n, and they do allow newlines within the string, and you escape the quote symbol with double-quotes ""

How do I set browser width and height in Selenium WebDriver?

Try something like this:

IWebDriver _driver = new FirefoxDriver();
_driver.Manage().Window.Position = new Point(0, 0);
_driver.Manage().Window.Size = new Size(1024, 768);

Not sure if it'll resize after being launched though, so maybe it's not what you want

Replace first occurrence of pattern in a string

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

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

How to connect to Oracle 11g database remotely

First, make sure the listener on database server (computer A) that receives client connection requests is running. To do so, run lsnrctl status command.

In case, if you get TNS:no listener message (see below image), it means listener service is not running. To start it, run lsnrctl start command.

enter image description here

Second, for database operations and connectivity from remote clients, the following executables must be added to the Windows Firewall exception list: (see image)

Oracle_home\bin\oracle.exe - Oracle Database executable

Oracle_home\bin\tnslsnr.exe - Oracle Listener

enter image description here

Finally, install oracle instant client on client machine (computer B) and run:

sqlplus user/password@computerA:port/XE

Rename package in Android Studio

Right click on package -> refactor and change the name.

You can also change it in the manifest. Sometimes if you change the package name, but after creating the .apk file it shows a different package name. At that time check "applicationId" in the build.gradle file.

Python find elements in one list that are not in the other

Use a list comprehension like this:

main_list = [item for item in list_2 if item not in list_1]

Output:

>>> list_1 = ["a", "b", "c", "d", "e"]
>>> list_2 = ["a", "f", "c", "m"] 
>>> 
>>> main_list = [item for item in list_2 if item not in list_1]
>>> main_list
['f', 'm']

Edit:

Like mentioned in the comments below, with large lists, the above is not the ideal solution. When that's the case, a better option would be converting list_1 to a set first:

set_1 = set(list_1)  # this reduces the lookup time from O(n) to O(1)
main_list = [item for item in list_2 if item not in set_1]

Reverse a string without using reversed() or [::-1]?

I used this:

def reverse(text):
s=""
l=len(text)
for i in range(l):
    s+=text[l-1-i]
return s

How to convert string to datetime format in pandas python?

Use to_datetime, there is no need for a format string the parser is man/woman enough to handle it:

In [51]:
pd.to_datetime(df['I_DATE'])

Out[51]:
0   2012-03-28 14:15:00
1   2012-03-28 14:17:28
2   2012-03-28 14:50:50
Name: I_DATE, dtype: datetime64[ns]

To access the date/day/time component use the dt accessor:

In [54]:
df['I_DATE'].dt.date

Out[54]:
0    2012-03-28
1    2012-03-28
2    2012-03-28
dtype: object

In [56]:    
df['I_DATE'].dt.time

Out[56]:
0    14:15:00
1    14:17:28
2    14:50:50
dtype: object

You can use strings to filter as an example:

In [59]:
df = pd.DataFrame({'date':pd.date_range(start = dt.datetime(2015,1,1), end = dt.datetime.now())})
df[(df['date'] > '2015-02-04') & (df['date'] < '2015-02-10')]

Out[59]:
         date
35 2015-02-05
36 2015-02-06
37 2015-02-07
38 2015-02-08
39 2015-02-09

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Even if your JSON is ok it could be DB charset (UTF8) problem. If your DB's charset/collation are UTF8 but PDO isn't set up properly (charset/workaround missing) some à / è / ò / ì / etc. in your DB could break your JSON encoding (still encoded but causing parsing issues). Check your connection string, it should be similar to one of these:

$pdo = new PDO('mysql:host=hostname;dbname=DBname;**charset=utf8**','username','password'); // PHP >= 5.3.6

$pdo = new PDO('mysql:host=hostname;dbname=DBname','username','password',**array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")**); // older versions

P.S. Outdated but still could be helpful for people who're stuck with "unexpected character".

What is the difference between a Relational and Non-Relational Database?

Try to explain this question in a level referring to a little bit technology

Take MongoDB and Traditional SQL for comparison, imagine the scenario of posting a Tweet on Twitter. This tweet contains 9 pictures. How do you store this tweet and its corresponding pictures?

In terms of traditional relationship SQL, you can store the tweets and pictures in separate tables, and represent the connection through building a new table.

What's more, you can set a field which is an image type, and zip the 9 pictures into a binary document and store it in this field.

Using MongoDB, you could build a document like this (similar to the concept of a table in relational SQL):

{

"id":"XXX",

"user":"XXX",

"date":"xxxx-xx-xx",

"content":{

"text":"XXXX",

"picture":["p1.png","p2.png","p3.png"]

}

Therefore, in my opinion, the main difference is about how do you store the data and the storage level of the relationships between them.

In this example, the data is the tweet and the pictures. The different mechanism about storage level of relationship between them also play a important role in the difference between both.

I hope this small example helps show the difference between SQL and NoSQL (ACID and BASE).

Here's a link of picture about the goals of NoSQL from the Internet:

http://icamchuwordpress-wordpress.stor.sinaapp.com/uploads/2015/01/dbc795f6f262e9d01fa0ab9b323b2dd1_b.png

Build .so file from .c file using gcc command line

To generate a shared library you need first to compile your C code with the -fPIC (position independent code) flag.

gcc -c -fPIC hello.c -o hello.o

This will generate an object file (.o), now you take it and create the .so file:

gcc hello.o -shared -o libhello.so

EDIT: Suggestions from the comments:

You can use

gcc -shared -o libhello.so -fPIC hello.c

to do it in one step. – Jonathan Leffler

I also suggest to add -Wall to get all warnings, and -g to get debugging information, to your gcc commands. – Basile Starynkevitch

Get the name of an object's type

I was actually looking for a similar thing and came across this question. Here is how I get types: jsfiddle

var TypeOf = function ( thing ) {

    var typeOfThing = typeof thing;

    if ( 'object' === typeOfThing ) {

        typeOfThing = Object.prototype.toString.call( thing );

        if ( '[object Object]' === typeOfThing ) {

            if ( thing.constructor.name ) {
                return thing.constructor.name;
            } 

            else if ( '[' === thing.constructor.toString().charAt(0) ) {
                typeOfThing = typeOfThing.substring( 8,typeOfThing.length - 1 );
            } 

            else {

                typeOfThing = thing.constructor.toString().match( /function\s*(\w+)/ );

                if ( typeOfThing ) { 
                    return typeOfThing[1];
                } 

                else {
                    return 'Function';
                }
            }
        } 

        else {
            typeOfThing = typeOfThing.substring( 8,typeOfThing.length - 1 );
        }
    }

    return typeOfThing.charAt(0).toUpperCase() + typeOfThing.slice(1);
}

Xampp-mysql - "Table doesn't exist in engine" #1932

I had the same issue. I had a backup of my C:\xampp\mysql\data folder. But integrating it with the newly installed xampp had issues. So I located the C:\xampp\mysql\bin\my.ini file and directed innodb_data_home_dir = "C:/xampp/mysql/data" to my backed-up data folder and it worked flawlessly.

Unique on a dataframe with only selected columns

Here are a couple dplyr options that keep non-duplicate rows based on columns id and id2:

library(dplyr)                                        
df %>% distinct(id, id2, .keep_all = TRUE)
df %>% group_by(id, id2) %>% filter(row_number() == 1)
df %>% group_by(id, id2) %>% slice(1)

How to do associative array/hashing in JavaScript

In C# the code looks like:

Dictionary<string,int> dictionary = new Dictionary<string,int>();
dictionary.add("sample1", 1);
dictionary.add("sample2", 2);

or

var dictionary = new Dictionary<string, int> {
    {"sample1", 1},
    {"sample2", 2}
};

In JavaScript:

var dictionary = {
    "sample1": 1,
    "sample2": 2
}

A C# dictionary object contains useful methods, like dictionary.ContainsKey()

In JavaScript, we could use the hasOwnProperty like:

if (dictionary.hasOwnProperty("sample1"))
    console.log("sample1 key found and its value is"+ dictionary["sample1"]);

Reload content in modal (twitter bootstrap)

I wanted the AJAX loaded content removed when the modal closed, so I adjusted the line suggested by others (coffeescript syntax):

$('#my-modal').on 'hidden.bs.modal', (event) ->
  $(this).removeData('bs.modal').children().remove()

How to dynamically remove items from ListView on a button click?

You can remove item from list view like this: or you can choose on your Button event which item have to be removed

public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_third);
     String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
                "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
                "Linux", "OS/2" };
     liste = new ArrayList<String>();
     Collections.addAll(liste, values);
     adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, liste);
     setListAdapter(adapter);
}
 @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
     liste.remove(position);
     adapter.notifyDataSetChanged();
  }
}

minimize app to system tray

this.WindowState = FormWindowState.Minimized;

preventDefault() on an <a> tag

After several operations, when the page should finally go to <a href"..."> link you can do the following:

jQuery("a").click(function(e){
    var self = jQuery(this);
    var href = self.attr('href');
    e.preventDefault();
    // needed operations

    window.location = href;
});

Disabling of EditText in Android

Use this to disable user input

android:focusable="false"

android:editable="false" This method is deprecated one.

How can I create a "Please Wait, Loading..." animation using jQuery?

I use CSS3 for animation

_x000D_
_x000D_
/************ CSS3 *************/_x000D_
.icon-spin {_x000D_
  font-size: 1.5em;_x000D_
  display: inline-block;_x000D_
  animation: spin1 2s infinite linear;_x000D_
}_x000D_
_x000D_
@keyframes spin1{_x000D_
    0%{transform:rotate(0deg)}_x000D_
    100%{transform:rotate(359deg)}_x000D_
}_x000D_
_x000D_
/************** CSS3 cross-platform ******************/_x000D_
_x000D_
.icon-spin-cross-platform {_x000D_
  font-size: 1.5em;_x000D_
  display: inline-block;_x000D_
  -moz-animation: spin 2s infinite linear;_x000D_
  -o-animation: spin 2s infinite linear;_x000D_
  -webkit-animation: spin 2s infinite linear;_x000D_
  animation: spin2 2s infinite linear;_x000D_
}_x000D_
_x000D_
@keyframes spin2{_x000D_
    0%{transform:rotate(0deg)}_x000D_
    100%{transform:rotate(359deg)}_x000D_
}_x000D_
@-moz-keyframes spin2{_x000D_
    0%{-moz-transform:rotate(0deg)}_x000D_
    100%{-moz-transform:rotate(359deg)}_x000D_
}_x000D_
@-webkit-keyframes spin2{_x000D_
    0%{-webkit-transform:rotate(0deg)}_x000D_
    100%{-webkit-transform:rotate(359deg)}_x000D_
}_x000D_
@-o-keyframes spin2{_x000D_
    0%{-o-transform:rotate(0deg)}_x000D_
    100%{-o-transform:rotate(359deg)}_x000D_
}_x000D_
@-ms-keyframes spin2{_x000D_
    0%{-ms-transform:rotate(0deg)}_x000D_
    100%{-ms-transform:rotate(359deg)}_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
<div class="row">_x000D_
  <div class="col-md-6">_x000D_
    Default CSS3_x000D_
    <span class="glyphicon glyphicon-repeat icon-spin"></span>_x000D_
  </div>_x000D_
  <div class="col-md-6">_x000D_
    Cross-Platform CSS3_x000D_
    <span class="glyphicon glyphicon-repeat icon-spin-cross-platform"></span>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to get current class name including package name in Java?

The fully-qualified name is opbtained as follows:

String fqn = YourClass.class.getName();

But you need to read a classpath resource. So use

InputStream in = YourClass.getResourceAsStream("resource.txt");

PHP foreach change original array values

function checkForm(& $fields){
    foreach($fields as $field){
        if($field['required'] && strlen($_POST[$field['name']]) <= 0){
            $fields[$field]['value'] = "Some error";
        }
    }
    return $fields;
}

This is what I would Suggest pass by reference

Is there a destructor for Java?

Nope, no destructors here. The reason is that all Java objects are heap allocated and garbage collected. Without explicit deallocation (i.e. C++'s delete operator) there is no sensible way to implement real destructors.

Java does support finalizers, but they are meant to be used only as a safeguard for objects holding a handle to native resources like sockets, file handles, window handles, etc. When the garbage collector collects an object without a finalizer it simply marks the memory region as free and that's it. When the object has a finalizer, it's first copied into a temporary location (remember, we're garbage collecting here), then it's enqueued into a waiting-to-be-finalized queue and then a Finalizer thread polls the queue with very low priority and runs the finalizer.

When the application exits, the JVM stops without waiting for the pending objects to be finalized, so there practically no guarantees that your finalizers will ever run.

MySQL SELECT WHERE datetime matches day (and not necessarily time)

You can use %:

SELECT * FROM datetable WHERE datecol LIKE '2012-12-25%'

Filtering a spark dataframe based on date

We can also use SQL kind of expression inside filter :


Note -> Here I am showing two conditions and a date range for future reference :


ordersDf.filter("order_status = 'PENDING_PAYMENT' AND order_date BETWEEN '2013-07-01' AND '2013-07-31' ")

How can I see all the "special" characters permissible in a varchar or char field in SQL Server?

EDIT based on comments:

If you have line breaks in your result set and want to remove them, make your query this way:

SELECT
    REPLACE(REPLACE(YourColumn1,CHAR(13),' '),CHAR(10),' ')
   ,REPLACE(REPLACE(YourColumn2,CHAR(13),' '),CHAR(10),' ')
   ,REPLACE(REPLACE(YourColumn3,CHAR(13),' '),CHAR(10),' ')
   --^^^^^^^^^^^^^^^           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   --only add the above code to strings that are having line breaks, not to numbers or dates
   FROM YourTable...
   WHERE ...

This will replace all the line breaks with a space character.

Run this to "get" all characters permitted in a char() and varchar():

;WITH AllNumbers AS
(
    SELECT 1 AS Number
    UNION ALL
    SELECT Number+1
        FROM AllNumbers
        WHERE Number+1<256
)
SELECT Number AS ASCII_Value,CHAR(Number) AS ASCII_Char FROM AllNumbers
OPTION (MAXRECURSION 256)

OUTPUT:

ASCII_Value ASCII_Char
----------- ----------
1           
2           
3           
4           
5           
6           
7           
8           
9               
10          

11          
12          
13          

14          
15          
16          
17          
18          
19          
20          
21          
22          
23          
24          
25          
26          
27          
28          
29          
30          
31          
32           
33          !
34          "
35          #
36          $
37          %
38          &
39          '
40          (
41          )
42          *
43          +
44          ,
45          -
46          .
47          /
48          0
49          1
50          2
51          3
52          4
53          5
54          6
55          7
56          8
57          9
58          :
59          ;
60          <
61          =
62          >
63          ?
64          @
65          A
66          B
67          C
68          D
69          E
70          F
71          G
72          H
73          I
74          J
75          K
76          L
77          M
78          N
79          O
80          P
81          Q
82          R
83          S
84          T
85          U
86          V
87          W
88          X
89          Y
90          Z
91          [
92          \
93          ]
94          ^
95          _
96          `
97          a
98          b
99          c
100         d
101         e
102         f
103         g
104         h
105         i
106         j
107         k
108         l
109         m
110         n
111         o
112         p
113         q
114         r
115         s
116         t
117         u
118         v
119         w
120         x
121         y
122         z
123         {
124         |
125         }
126         ~
127         
128         €
129         
130         ‚
131         ƒ
132         „
133         …
134         †
135         ‡
136         ˆ
137         ‰
138         Š
139         ‹
140         Œ
141         
142         Ž
143         
144         
145         ‘
146         ’
147         “
148         ”
149         •
150         –
151         —
152         ˜
153         ™
154         š
155         ›
156         œ
157         
158         ž
159         Ÿ
160          
161         ¡
162         ¢
163         £
164         ¤
165         ¥
166         ¦
167         §
168         ¨
169         ©
170         ª
171         «
172         ¬
173         ­
174         ®
175         ¯
176         °
177         ±
178         ²
179         ³
180         ´
181         µ
182         ¶
183         ·
184         ¸
185         ¹
186         º
187         »
188         ¼
189         ½
190         ¾
191         ¿
192         À
193         Á
194         Â
195         Ã
196         Ä
197         Å
198         Æ
199         Ç
200         È
201         É
202         Ê
203         Ë
204         Ì
205         Í
206         Î
207         Ï
208         Ð
209         Ñ
210         Ò
211         Ó
212         Ô
213         Õ
214         Ö
215         ×
216         Ø
217         Ù
218         Ú
219         Û
220         Ü
221         Ý
222         Þ
223         ß
224         à
225         á
226         â
227         ã
228         ä
229         å
230         æ
231         ç
232         è
233         é
234         ê
235         ë
236         ì
237         í
238         î
239         ï
240         ð
241         ñ
242         ò
243         ó
244         ô
245         õ
246         ö
247         ÷
248         ø
249         ù
250         ú
251         û
252         ü
253         ý
254         þ
255         ÿ

(255 row(s) affected)

1 = false and 0 = true?

It may very well be a mistake on the original author, however the notion that 1 is true and 0 is false is not a universal concept. In shell scripting 0 is returned for success, and any other number for failure. In other languages such as Ruby, only nil and false are considered false, and any other value is considered true, so in Ruby both 1 and 0 would be considered true.

Android Studio emulator does not come with Play Store for API 23

Now there's no need to side load any packages of execute any scripts to get the Play Store on the emulator. Starting from Android Studio 2.4 now you can create an AVD that has Play Store pre-installed on it. Currently it is supported only on the AVDs running Android 7.0 (API 24) system images.

Official Source

AVD with Play Store

Note: Compatible devices are denoted by the new Play Store column.

How to calculate cumulative normal distribution?

Alex's answer shows you a solution for standard normal distribution (mean = 0, standard deviation = 1). If you have normal distribution with mean and std (which is sqr(var)) and you want to calculate:

from scipy.stats import norm

# cdf(x < val)
print norm.cdf(val, m, s)

# cdf(x > val)
print 1 - norm.cdf(val, m, s)

# cdf(v1 < x < v2)
print norm.cdf(v2, m, s) - norm.cdf(v1, m, s)

Read more about cdf here and scipy implementation of normal distribution with many formulas here.

How to run Gulp tasks sequentially one after the other

By default, gulp runs tasks simultaneously, unless they have explicit dependencies. This isn't very useful for tasks like clean, where you don't want to depend, but you need them to run before everything else.

I wrote the run-sequence plugin specifically to fix this issue with gulp. After you install it, use it like this:

var runSequence = require('run-sequence');

gulp.task('develop', function(done) {
    runSequence('clean', 'coffee', function() {
        console.log('Run something else');
        done();
    });
});

You can read the full instructions on the package README — it also supports running some sets of tasks simultaneously.

Please note, this will be (effectively) fixed in the next major release of gulp, as they are completely eliminating the automatic dependency ordering, and providing tools similar to run-sequence to allow you to manually specify run order how you want.

However, that is a major breaking change, so there's no reason to wait when you can use run-sequence today.

Pandas: Appending a row to a dataframe and specify its index label

There is another solution. The next code is bad (although I think pandas needs this feature):

import pandas as pd

# empty dataframe
a = pd.DataFrame()
a.loc[0] = {'first': 111, 'second': 222}

But the next code runs fine:

import pandas as pd

# empty dataframe
a = pd.DataFrame()
a = a.append(pd.Series({'first': 111, 'second': 222}, name=0))

How to Set/Update State of StatefulWidget from other StatefulWidget in Flutter?

1.On Child Widget : add parameter Function paramter

class ChildWidget extends StatefulWidget {
  final Function() notifyParent;
  ChildWidget({Key key, @required this.notifyParent}) : super(key: key);
}

2.On Parent Widget : create a Function for the child to callback

refresh() {
  setState(() {});
}

3.On Parent Widget : pass parentFunction to Child Widget

new ChildWidget( notifyParent: refresh );  

4.On Child Widget : call the Parent Function

  widget.notifyParent();

Check synchronously if file/directory exists in Node.js

Using fileSystem (fs) tests will trigger error objects, which you then would need to wrap in a try/catch statement. Save yourself some effort, and use a feature introduce in the 0.4.x branch.

var path = require('path');

var dirs = ['one', 'two', 'three'];

dirs.map(function(dir) {
  path.exists(dir, function(exists) {
    var message = (exists) ? dir + ': is a directory' : dir + ': is not a directory';
    console.log(message);
  });
});

How to synchronize a static variable among threads running different instances of a class in Java?

There are several ways to synchronize access to a static variable.

  1. Use a synchronized static method. This synchronizes on the class object.

    public class Test {
        private static int count = 0;
    
        public static synchronized void incrementCount() {
            count++;
        }
    } 
    
  2. Explicitly synchronize on the class object.

    public class Test {
        private static int count = 0;
    
        public void incrementCount() {
            synchronized (Test.class) {
                count++;
            }
        }
    } 
    
  3. Synchronize on some other static object.

    public class Test {
        private static int count = 0;
        private static final Object countLock = new Object();
    
        public void incrementCount() {
            synchronized (countLock) {
                count++;
            }
        }
    } 
    

Method 3 is the best in many cases because the lock object is not exposed outside of your class.

What is the idiomatic Go equivalent of C's ternary operator?

Suppose you have the following ternary expression (in C):

int a = test ? 1 : 2;

The idiomatic approach in Go would be to simply use an if block:

var a int

if test {
  a = 1
} else {
  a = 2
}

However, that might not fit your requirements. In my case, I needed an inline expression for a code generation template.

I used an immediately evaluated anonymous function:

a := func() int { if test { return 1 } else { return 2 } }()

This ensures that both branches are not evaluated as well.

How can I add "href" attribute to a link dynamically using JavaScript?

More actual solution:

<a id="someId">Link</a>

const a = document.querySelector('#someId');
a.href = 'url';

Convert data.frame column format from character to factor

# To do it for all names
df[] <- lapply( df, factor) # the "[]" keeps the dataframe structure
 col_names <- names(df)
# to do it for some names in a vector named 'col_names'
df[col_names] <- lapply(df[col_names] , factor)

Explanation. All dataframes are lists and the results of [ used with multiple valued arguments are likewise lists, so looping over lists is the task of lapply. The above assignment will create a set of lists that the function data.frame.[<- should successfully stick back into into the dataframe, df

Another strategy would be to convert only those columns where the number of unique items is less than some criterion, let's say fewer than the log of the number of rows as an example:

cols.to.factor <- sapply( df, function(col) length(unique(col)) < log10(length(col)) )
df[ cols.to.factor] <- lapply(df[ cols.to.factor] , factor)

Java - Check Not Null/Empty else assign default value

You can use this method in the ObjectUtils class from org.apache.commons.lang3 library :

public static <T> T defaultIfNull(T object, T defaultValue)

How to put an image next to each other

Instead of using position:relative in #icons, you could just take that away and maybe add a z-index or something so the picture won't get covered up. Hope this helps.

Getting "error": "unsupported_grant_type" when trying to get a JWT by calling an OWIN OAuth secured Web Api via Postman

The response is a bit late - but in case anyone has the issue in the future...

From the screenshot above - it seems that you are adding the url data (username, password, grant_type) to the header and not to the body element.

Clicking on the body tab, and then select "x-www-form-urlencoded" radio button, there should be a key-value list below that where you can enter the request data

How to execute mongo commands through shell scripts?

Thank you printf! In a Linux environment, here's a better way to have only one file run the show. Say you have two files, mongoCmds.js with multiple commands:

use someDb
db.someColl.find()

and then the driver shell file, runMongoCmds.sh

mongo < mongoCmds.js

Instead, have just one file, runMongoCmds.sh containing

printf "use someDb\ndb.someColl.find()" | mongo

Bash's printf is much more robust than echo and allows for the \n between commands to force them on multiple lines.

List all employee's names and their managers by manager name using an inner join

Add m.Ename to your SELECT query:

select distinct e.Ename as Employee, m.mgr as reports_to, m.Ename as Manager
from EMPLOYEES e
inner join Employees m on e.mgr = m.EmpID;

jQuery Cross Domain Ajax

Unfortunately it seems that this web service returns JSON which contains another JSON - parsing contents of the inner JSON is successful. The solution is ugly but works for me. JSON.parse(...) tries to convert the entire string and fails. Assuming that you always get the answer starting with {"AuthenticateUserResult": and interesting data is after this, try:

$.ajax({
    type: 'GET',
    dataType: "text",
    crossDomain: true,
    url: "http://someotherdomain.com/service.svc",
    success: function (responseData, textStatus, jqXHR) {
        var authResult = JSON.parse(
            responseData.replace(
                '{"AuthenticateUserResult":"', ''
            ).replace('}"}', '}')
        );
        console.log("in");
    },
    error: function (responseData, textStatus, errorThrown) {
        alert('POST failed.');
    }
});

It is very important that dataType must be text to prevent auto-parsing of malformed JSON you are receiving from web service.

Basically, I'm wiping out the outer JSON by removing topmost braces and key AuthenticateUserResult along with leading and trailing quotation marks. The result is a well formed JSON, ready for parsing.

Standardize data columns in R

@BBKim pretty much gave the best answer, but it can just be done shorter. I'm surprised noone came up with it yet.

dat <- data.frame(x = rnorm(10, 30, .2), y = runif(10, 3, 5)) dat <- apply(dat, 2, function(x) (x - mean(x)) / sd(x))

vertical-align: middle doesn't work

You should set a fixed value to your span's line-height property:

.float, .twoline {
    line-height: 100px;
}

How to convert a string to integer in C?

This function will help you

int strtoint_n(char* str, int n)
{
    int sign = 1;
    int place = 1;
    int ret = 0;

    int i;
    for (i = n-1; i >= 0; i--, place *= 10)
    {
        int c = str[i];
        switch (c)
        {
            case '-':
                if (i == 0) sign = -1;
                else return -1;
                break;
            default:
                if (c >= '0' && c <= '9')   ret += (c - '0') * place;
                else return -1;
        }
    }

    return sign * ret;
}

int strtoint(char* str)
{
    char* temp = str;
    int n = 0;
    while (*temp != '\0')
    {
        n++;
        temp++;
    }
    return strtoint_n(str, n);
}

Ref: http://amscata.blogspot.com/2013/09/strnumstr-version-2.html

Can you create nested WITH clauses for Common Table Expressions?

While not strictly nested, you can use common table expressions to reuse previous queries in subsequent ones.

To do this, the form of the statement you are looking for would be

WITH x AS 
(
    SELECT * FROM MyTable
), 
y AS 
(
    SELECT * FROM x
)
SELECT * FROM y

Problems with jQuery getJSON using local files in Chrome

@Mike On Mac, type this in Terminal:

open -b com.google.chrome --args --disable-web-security

Replace all particular values in a data frame

If you want to replace multiple values in a data frame, looping through all columns might help.

Say you want to replace "" and 100:

na_codes <- c(100, "")
for (i in seq_along(df)) {
    df[[i]][df[[i]] %in% na_codes] <- NA
}

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

How to create an Explorer-like folder browser control?

It's not as easy as it seems to implement a control like that. Explorer works with shell items, not filesystem items (ex: the control panel, the printers folder, and so on). If you need to implement it i suggest to have a look at the Windows shell functions at http://msdn.microsoft.com/en-us/library/bb776426(VS.85).aspx.

"error: assignment to expression with array type error" when I assign a struct field (C)

Please check this example here: Accessing Structure Members

There is explained that the right way to do it is like this:

strcpy(s1.name , "Egzona");
printf( "Name : %s\n", s1.name);

ApiNotActivatedMapError for simple html page using google-places-api

Assuming you already have a application created under google developer console, Follow the below steps

  1. Go to the following link https://console.cloud.google.com/apis/dashboard? you will be getting the below page enter image description here
  2. Click on ENABLE APIS AND SERVICES you will be directed to following page enter image description here
  3. Select the desired option - in this case "Maps JavaScript API"
  4. Click ENABLE button as below, enter image description here

Note: Please use a server to load the html file

Something like 'contains any' for Java set?

Wouldn't Collections.disjoint(A, B) work? From the documentation:

Returns true if the two specified collections have no elements in common.

Thus, the method returns false if the collections contains any common elements.

PHP7 : install ext-dom issue

First of all, read the warning! It says do not run composer as root! Secondly, you're probably using Xammp on your local which has the required php libraries as default.

But in your server you're missing ext-dom. php-xml has all the related packages you need. So, you can simply install it by running:

sudo apt-get update
sudo apt install php-xml

Most likely you are missing mbstring too. If you get the error, install this package as well with:

sudo apt-get install php-mbstring

Then run:

composer update
composer require cviebrock/eloquent-sluggable

Is there a WebSocket client implemented for Python?

Autobahn has a good websocket client implementation for Python as well as some good examples. I tested the following with a Tornado WebSocket server and it worked.

from twisted.internet import reactor
from autobahn.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS


class EchoClientProtocol(WebSocketClientProtocol):

   def sendHello(self):
      self.sendMessage("Hello, world!")

   def onOpen(self):
      self.sendHello()

   def onMessage(self, msg, binary):
      print "Got echo: " + msg
      reactor.callLater(1, self.sendHello)


if __name__ == '__main__':

   factory = WebSocketClientFactory("ws://localhost:9000")
   factory.protocol = EchoClientProtocol
   connectWS(factory)
   reactor.run()

IllegalStateException: Can not perform this action after onSaveInstanceState with ViewPager

The exception is threw here (In FragmentActivity):

@Override
public void onBackPressed() {
    if (!mFragments.getSupportFragmentManager().popBackStackImmediate()) {
        super.onBackPressed();
    }
}

In FragmentManager.popBackStatckImmediate(),FragmentManager.checkStateLoss() is called firstly. That's the cause of IllegalStateException. See the implementation below:

private void checkStateLoss() {
    if (mStateSaved) { // Boom!
        throw new IllegalStateException(
                "Can not perform this action after onSaveInstanceState");
    }
    if (mNoTransactionsBecause != null) {
        throw new IllegalStateException(
                "Can not perform this action inside of " + mNoTransactionsBecause);
    }
}

I solve this problem simply by using a flag to mark Activity's current status. Here's my solution:

public class MainActivity extends AppCompatActivity {
    /**
     * A flag that marks whether current Activity has saved its instance state
     */
    private boolean mHasSaveInstanceState;

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

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        mHasSaveInstanceState = true;
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mHasSaveInstanceState = false;
    }

    @Override
    public void onBackPressed() {
        if (!mHasSaveInstanceState) {
            // avoid FragmentManager.checkStateLoss()'s throwing IllegalStateException
            super.onBackPressed();
        }
    }
}

How do I remove blank elements from an array?

There are already a lot of answers but here is another approach if you're in the Rails world:

 cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].select &:present?

How to style the option of an html "select" element?

You can add a class and gives font-weight:700; in option. But by using this all the text will become bold.

@RequestParam in Spring MVC handling optional parameters

Create 2 methods which handle the cases. You can instruct the @RequestMapping annotation to take into account certain parameters whilst mapping the request. That way you can nicely split this into 2 methods.

@RequestMapping (value="/submit/id/{id}", method=RequestMethod.GET, 
                 produces="text/xml", params={"logout"})
public String handleLogout(@PathVariable("id") String id, 
        @RequestParam("logout") String logout) { ... }

@RequestMapping (value="/submit/id/{id}", method=RequestMethod.GET, 
                 produces="text/xml", params={"name", "password"})
public String handleLogin(@PathVariable("id") String id, @RequestParam("name") 
        String username, @RequestParam("password") String password, 
        @ModelAttribute("submitModel") SubmitModel model, BindingResult errors) 
        throws LoginException {...}

Why does sudo change the PATH?

comment out both "Default env_reset" and "Default secure_path ..." in /etc/sudores file works for me

Regex to check with starts with http://, https:// or ftp://

Unless there is some compelling reason to use a regex, I would just use String.startsWith:

bool matches = test.startsWith("http://")
            || test.startsWith("https://") 
            || test.startsWith("ftp://");

I wouldn't be surprised if this is faster, too.

Format of the initialization string does not conform to specification starting at index 0

As I Know, whenever you have more than 1 connection string in your solution(your current project, startup project,...), you may confront with this error

this link may help you click

Random integer in VB.NET

All the answers so far have problems or bugs (plural, not just one). I will explain. But first I want to compliment Dan Tao's insight to use a static variable to remember the Generator variable so calling it multiple times will not repeat the same # over and over, plus he gave a very nice explanation. But his code suffered the same flaw that most others have, as i explain now.

MS made their Next() method rather odd. the Min parameter is the inclusive minimum as one would expect, but the Max parameter is the exclusive maximum as one would NOT expect. in other words, if you pass min=1 and max=5 then your random numbers would be any of 1, 2, 3, or 4, but it would never include 5. This is the first of two potential bugs in all code that uses Microsoft's Random.Next() method.

For a simple answer (but still with other possible but rare problems) then you'd need to use:

Private Function GenRandomInt(min As Int32, max As Int32) As Int32
    Static staticRandomGenerator As New System.Random
    Return staticRandomGenerator.Next(min, max + 1)
End Function

(I like to use Int32 rather than Integer because it makes it more clear how big the int is, plus it is shorter to type, but suit yourself.)

I see two potential problems with this method, but it will be suitable (and correct) for most uses. So if you want a simple solution, i believe this is correct.

The only 2 problems i see with this function is: 1: when Max = Int32.MaxValue so adding 1 creates a numeric overflow. altho, this would be rare, it is still a possibility. 2: when min > max + 1. when min = 10 and max = 5 then the Next function throws an error. this may be what you want. but it may not be either. or consider when min = 5 and max = 4. by adding 1, 5 is passed to the Next method, but it does not throw an error, when it really is an error, but Microsoft .NET code that i tested returns 5. so it really is not an 'exclusive' max when the max = the min. but when max < min for the Random.Next() function, then it throws an ArgumentOutOfRangeException. so Microsoft's implementation is really inconsistent and buggy too in this regard.

you may want to simply swap the numbers when min > max so no error is thrown, but it totally depends on what is desired. if you want an error on invalid values, then it is probably better to also throw the error when Microsoft's exclusive maximum (max + 1) in our code equals minimum, where MS fails to error in this case.

handling a work-around for when max = Int32.MaxValue is a little inconvenient, but i expect to post a thorough function which handles both these situations. and if you want different behavior than how i coded it, suit yourself. but be aware of these 2 issues.

Happy coding!

Edit: So i needed a random integer generator, and i decided to code it 'right'. So if anyone wants the full functionality, here's one that actually works. (But it doesn't win the simplest prize with only 2 lines of code. But it's not really complex either.)

''' <summary>
''' Generates a random Integer with any (inclusive) minimum or (inclusive) maximum values, with full range of Int32 values.
''' </summary>
''' <param name="inMin">Inclusive Minimum value. Lowest possible return value.</param>
''' <param name="inMax">Inclusive Maximum value. Highest possible return value.</param>
''' <returns></returns>
''' <remarks></remarks>
Private Function GenRandomInt(inMin As Int32, inMax As Int32) As Int32
    Static staticRandomGenerator As New System.Random
    If inMin > inMax Then Dim t = inMin : inMin = inMax : inMax = t
    If inMax < Int32.MaxValue Then Return staticRandomGenerator.Next(inMin, inMax + 1)
    ' now max = Int32.MaxValue, so we need to work around Microsoft's quirk of an exclusive max parameter.
    If inMin > Int32.MinValue Then Return staticRandomGenerator.Next(inMin - 1, inMax) + 1 ' okay, this was the easy one.
    ' now min and max give full range of integer, but Random.Next() does not give us an option for the full range of integer.
    ' so we need to use Random.NextBytes() to give us 4 random bytes, then convert that to our random int.
    Dim bytes(3) As Byte ' 4 bytes, 0 to 3
    staticRandomGenerator.NextBytes(bytes) ' 4 random bytes
    Return BitConverter.ToInt32(bytes, 0) ' return bytes converted to a random Int32
End Function

Possible heap pollution via varargs parameter

When you use varargs, it can result in the creation of an Object[] to hold the arguments.

Due to escape analysis, the JIT can optimise away this array creation. (One of the few times I have found it does so) Its not guaranteed to be optimised away, but I wouldn't worry about it unless you see its an issue in your memory profiler.

AFAIK @SafeVarargs suppresses a warning by the compiler and doesn't change how the JIT behaves.

How do you change the value inside of a textfield flutter?

You can use the text editing controller to manipulate the value inside a textfield.

var textController = new TextEditingController();

Now, create a new textfield and set textController as the controller for the textfield as shown below.

 new TextField(controller: textController)

Now, create a RaisedButton anywhere in your code and set the desired text in the onPressed method of the RaisedButton.

new RaisedButton(
       onPressed: () {
          textController.text = "New text";
       }
    ),

Error: EACCES: permission denied, access '/usr/local/lib/node_modules'

sudo chown -R $USER /usr/local/lib/node_modules

Convert InputStream to byte array in Java

Do you really need the image as a byte[]? What exactly do you expect in the byte[] - the complete content of an image file, encoded in whatever format the image file is in, or RGB pixel values?

Other answers here show you how to read a file into a byte[]. Your byte[] will contain the exact contents of the file, and you'd need to decode that to do anything with the image data.

Java's standard API for reading (and writing) images is the ImageIO API, which you can find in the package javax.imageio. You can read in an image from a file with just a single line of code:

BufferedImage image = ImageIO.read(new File("image.jpg"));

This will give you a BufferedImage, not a byte[]. To get at the image data, you can call getRaster() on the BufferedImage. This will give you a Raster object, which has methods to access the pixel data (it has several getPixel() / getPixels() methods).

Lookup the API documentation for javax.imageio.ImageIO, java.awt.image.BufferedImage, java.awt.image.Raster etc.

ImageIO supports a number of image formats by default: JPEG, PNG, BMP, WBMP and GIF. It's possible to add support for more formats (you'd need a plug-in that implements the ImageIO service provider interface).

See also the following tutorial: Working with Images

Casting int to bool in C/C++

0 values of basic types (1)(2)map to false.

Other values map to true.

This convention was established in original C, via its flow control statements; C didn't have a boolean type at the time.


It's a common error to assume that as function return values, false indicates failure. But in particular from main it's false that indicates success. I've seen this done wrong many times, including in the Windows starter code for the D language (when you have folks like Walter Bright and Andrei Alexandrescu getting it wrong, then it's just dang easy to get wrong), hence this heads-up beware beware.


There's no need to cast to bool for built-in types because that conversion is implicit. However, Visual C++ (Microsoft's C++ compiler) has a tendency to issue a performance warning (!) for this, a pure silly-warning. A cast doesn't suffice to shut it up, but a conversion via double negation, i.e. return !!x, works nicely. One can read !! as a “convert to bool” operator, much as --> can be read as “goes to”. For those who are deeply into readability of operator notation. ;-)


1) C++14 §4.12/1 “A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization (8.5), a prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.”
2) C99 and C11 §6.3.1.2/1 “When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.”