Programs & Examples On #Symbian

Symbian is a discontinued embedded operating system and software platform for smartphones.

Is it possible to play music during calls so that the partner can hear it ? Android

Note: You can play back the audio data only to the standard output device.
Currently, that is the mobile device speaker or a Bluetooth headset. You 
cannot play sound files in the conversation audio during a call.

See official link 

http://developer.android.com/guide/topics/media/mediaplayer.html

Loop through Map in Groovy?

Another option:

def map = ['a':1, 'b':2, 'c':3]
map.each{
  println it.key +" "+ it.value
}

Insert variable into Header Location PHP

header('Location: http://linkhere.com/' . $your_variable);

Mobile Redirect using htaccess

First, go to the following URL and download the mobile_detect.php file:

http://code.google.com/p/php-mobile-detect/

Insert the following code on your index or home page:

<?php
@include("Mobile_Detect.php");
$detect = new Mobile_Detect();
if ($detect->isMobile() && isset($_COOKIE['mobile']))
{
$detect = "false";
}
elseif ($detect->isMobile())
{
header("Location:http://www.yourmobiledirectory.com");
}
?>

What is the worst programming language you ever worked with?

Lingo, for Shockwave Flash (or whatever it was). Quite horrible, basic-ish thing with a bit too dynamic type system. The editor sucked, the debugger sucked. Arghh!

It probably didn't help that the app I had to take upon my shoulders was written by scriptkiddies, which used the type of a variable to steer control flow. (If it's a string, we're in mode A, so it means X, if it's an int, we're in mode B, so it means Y). $£€£@£$#"¤#" !!

I like Python, and I suppose something equally horrible could've been made there, but the community and tools are much nicer and rigorous.

Typescript: How to define type for a function callback (as any function type, not universal any) used in a method parameter

Following from Ryan's answer, I think that the interface you are looking for is defined as follows:

interface Param {
    title: string;
    callback: () => void;
}

Eclipse DDMS error "Can't bind to local 8600 for debugger"

Try killing port 8600 with this command:

fuser -k 8600/tcp

That fixed it for me.

How to generate java classes from WSDL file

Assuming that you have JAXB installed Go to the following directory C:\Program Files\jaxb\bin open command window here

> xjc -wsdl http://localhost/mywsdl/MyDWsdl.wsdl C:\Users\myname\Desktop

C:\Users\myname\Desktop is the ouput folder you can change that to your preference

http://localhost/mywsdl/MyDWsdl.wsdl is the link to the WSDL

Set size on background image with CSS?

background-size is working in Chrome 4.1, but so far I couldn't make it work in Firefox 3.6.

Open existing file, append a single line

We can use

public StreamWriter(string path, bool append);

while opening the file

string path="C:\\MyFolder\\Notes.txt"
StreamWriter writer = new StreamWriter(path, true);

First parameter is a string to hold a full file path Second parameter is Append Mode, that in this case is made true

Writing to the file can be done with:

writer.Write(string)

or

writer.WriteLine(string)

Sample Code

private void WriteAndAppend()
{
            string Path = Application.StartupPath + "\\notes.txt";
            FileInfo fi = new FileInfo(Path);
            StreamWriter SW;
            StreamReader SR;
            if (fi.Exists)
            {
                SR = new StreamReader(Path);
                string Line = "";
                while (!SR.EndOfStream) // Till the last line
                {
                    Line = SR.ReadLine();
                }
                SR.Close();
                int x = 0;
                if (Line.Trim().Length <= 0)
                {
                    x = 0;
                }
                else
                {
                    x = Convert.ToInt32(Line.Substring(0, Line.IndexOf('.')));
                }
                x++;
                SW = new StreamWriter(Path, true);
                SW.WriteLine("-----"+string.Format("{0:dd-MMM-yyyy hh:mm:ss tt}", DateTime.Now));
                SW.WriteLine(x.ToString() + "." + textBox1.Text);

            }
            else
            {
                SW = new StreamWriter(Path);
                SW.WriteLine("-----" + string.Format("{0:dd-MMM-yyyy hh:mm:ss tt}", DateTime.Now));
                SW.WriteLine("1." + textBox1.Text);
            }
            SW.Flush();
            SW.Close();
        }

How to align the checkbox and label in same line in html?

If you are using bootstrap wrap your label and input with a div of a "checkbox" or "checkbox-inline" class.

<li>
    <div class="checkbox">
        <label><input type="checkbox" value="">Option 1</label>
    </div>
</li>

Reference: https://www.w3schools.com/bootstrap/bootstrap_forms_inputs.asp

Select multiple columns using Entity Framework

It's correct way to get data in specified type:

var dataset = entities.processlists
         .Where(x => x.environmentID == environmentid && x.ProcessName == processname && x.RemoteIP == remoteip && x.CommandLine == commandlinepart)
         .Select(x => new { x.ServerName, x.ProcessID, x.Username })
         .ToList() /// To get data from database
         .Select(x => new PInfo()
              { 
                   ServerName = x.ServerName, 
                   ProcessID = x.ProcessID, 
                   Username = x.Username 
              });

For more information see: The entity cannot be constructed in a LINQ to Entities query

select into in mysql

In MySQL, It should be like this

INSERT INTO this_table_archive (col1, col2, ..., coln)
SELECT col1, col2, ..., coln
FROM this_table
WHERE entry_date < '2011-01-01 00:00:00';

MySQL Documentation

How can I easily add storage to a VirtualBox machine with XP installed?

Taked from here => forums.virtualbox.org/viewtopic.php?p=41118#p41118

You could try something like this (see also Tutorial - All about VDIs: How can I resize the partitions inside my VDI?):

  • Create a new VDI of the desired size.
  • Boot GParted Live in a VM with both old and new VDIs attached.
  • Check in the partition editor (opened automatically after booting) what your old and new disk locations are. (It'll be something like /dev/hda and /dev/hdb.)
  • Copy contents from old to new disk. This will take a fair amount of time. (Here /dev/hdX is your original disk and /dev/hdY the new one).

    dd if=/dev/hdX of=/dev/hdY

    Warning: Make sure you do not mix up your input and output disks or you'll wipe all information from your original disk! (if= specifies the input and of= specifies the output.)

  • Reboot (again with GParted-Live). Now you should be able to increase the Windows partition size on the new disk.

Once you've verified the larger VDI boots Windows fine (and disk size is as you'd expect) you can of course delete the old smaller VDI.

Edit: Instead of rebooting before you resize the partition you should be able to run partprobe and the hit CTRL+R in GParted instead.

Assign variable value inside if-statement

Yes, you can assign the value of variable inside if.

I wouldn't recommend it. The problem is, it looks like a common error where you try to compare values, but use a single = instead of == or ===.

It will be better if you do something like this:

int v;
if((v = someMethod()) != 0) 
   return true;

Object passed as parameter to another class, by value or reference?

Assuming someTestObj is a class and not a struct, the object is passed by reference, which means that both obj and someTestObj refer to the same object. E.g. changing name in one will change it in the other. However, unlike if you passed it using the ref keyword, setting obj = somethingElse will not change someTestObj.

How do I create a WPF Rounded Corner container?

I just had to do this myself, so I thought I would post another answer here.

Here is another way to create a rounded corner border and clip its inner content. This is the straightforward way by using the Clip property. It's nice if you want to avoid a VisualBrush.

The xaml:

<Border
    Width="200"
    Height="25"
    CornerRadius="11"
    Background="#FF919194"
>
    <Border.Clip>
        <RectangleGeometry
            RadiusX="{Binding CornerRadius.TopLeft, RelativeSource={RelativeSource AncestorType={x:Type Border}}}"
            RadiusY="{Binding RadiusX, RelativeSource={RelativeSource Self}}"
        >
            <RectangleGeometry.Rect>
                <MultiBinding
                    Converter="{StaticResource widthAndHeightToRectConverter}"
                >
                    <Binding
                        Path="ActualWidth"
                        RelativeSource="{RelativeSource AncestorType={x:Type Border}}"
                    />
                    <Binding
                        Path="ActualHeight"
                        RelativeSource="{RelativeSource AncestorType={x:Type Border}}"
                    />
                </MultiBinding>
            </RectangleGeometry.Rect>
        </RectangleGeometry>
    </Border.Clip>

    <Rectangle
        Width="100"
        Height="100"
        Fill="Blue"
        HorizontalAlignment="Left"
        VerticalAlignment="Center"
    />
</Border>

The code for the converter:

public class WidthAndHeightToRectConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        double width = (double)values[0];
        double height = (double)values[1];
        return new Rect(0, 0, width, height);
    }
    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Android ListView selected item stay highlighted

I found the proper way. It's very simple. In resource describe following:

android:choiceMode="singleChoice"
android:listSelector="#666666"

(or you may specify a resource link instead of color value)

Programmatical:

listView.setSelector(Drawable selector);
listView.setSelector(int resourceId);
listView.setChoiceMode(int mode);

mode can be one of these: AbsListView.CHOICE_MODE_SINGLE, AbsListView.CHOICE_MODE_MULTIPLE, AbsListView.CHOICE_MODE_NONE (default)

(AbsListView is the abstract ancestor for the ListView class)

P.S. manipulations with onItemClick and changing view background are bankrupt, because a view itself is a temporary object. Hence you must not to track a view.

If our list is long enough, the views associated with scrolled out items will be removed from hierarchy, and will be recreated when those items will shown again (with cached display options, such as background). So, the view we have tracked is now not an actual view of the item, and changing its background does nothing to the actual item view. As a result we have multiple items selected.

Passing HTML to template using Flask/Jinja2

You can also declare it HTML safe from the code:

from flask import Markup
value = Markup('<strong>The HTML String</strong>')

Then pass that value to the templates and they don't have to |safe it.

MySQL server has gone away - in exactly 60 seconds

Please see this link http://bugs.php.net/bug.php?id=45150 seems like they moved to native MYSQL support in PHP5.3 and it has some trouble working with IPV6. Try using "127.0.0.1" instead of "localhost"

How do you get the current text contents of a QComboBox?

PyQt4 can be forced to use a new API in which QString is automatically converted to and from a Python object:

import sip
sip.setapi('QString', 2)

With this API, QtCore.QString class is no longer available and self.ui.comboBox.currentText() will return a Python string or unicode object.

See Selecting Incompatible APIs from the doc.

"continue" in cursor.forEach()

Making use of JavaScripts short-circuit evaluation. If el.shouldBeProcessed returns true, doSomeLengthyOperation

elementsCollection.forEach( el => 
  el.shouldBeProcessed && doSomeLengthyOperation()
);

How to pass data from 2nd activity to 1st activity when pressed back? - android

Other answers were not working when I put setResult in onBackPressed. Commenting call to super onBackPressed and calling finish manually solves the problem:

@Override
public void onBackPressed() {
    //super.onBackPressed();
    Intent i = new Intent();
    i.putExtra(EXTRA_NON_DOWNLOADED_PAGES, notDownloaded);
    setResult(RESULT_OK, i);
    finish();
}

And in first activity:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == QUEUE_MSG) {
        if (resultCode == RESULT_OK) {
            Serializable tmp = data.getSerializableExtra(MainActivity.EXTRA_NON_DOWNLOADED_PAGES);
            if (tmp != null)
                serializable = tmp;
        }
    }
}

Receiving JSON data back from HTTP request

What I normally do, similar to answer one:

var response = await httpClient.GetAsync(completeURL); // http://192.168.0.1:915/api/Controller/Object

if (response.IsSuccessStatusCode == true)
    {
        string res = await response.Content.ReadAsStringAsync();
        var content = Json.Deserialize<Model>(res);

// do whatever you need with the JSON which is in 'content'
// ex: int id = content.Id;

        Navigate();
        return true;
    }
    else
    {
        await JSRuntime.Current.InvokeAsync<string>("alert", "Warning, the credentials you have entered are incorrect.");
        return false;
    }

Where 'model' is your C# model class.

Inheritance and init method in Python

A simple change in Num2 class like this:

super().__init__(num) 

It works in python3.

class Num:
        def __init__(self,num):
                self.n1 = num

class Num2(Num):
        def __init__(self,num):
                super().__init__(num)
                self.n2 = num*2
        def show(self):
                print (self.n1,self.n2)

mynumber = Num2(8)
mynumber.show()

Function pointer to member function

You need to use a pointer to a member function, not just a pointer to a function.

class A { 
    int f() { return 1; }
public:
    int (A::*x)();

    A() : x(&A::f) {}
};

int main() { 
   A a;
   std::cout << (a.*a.x)();
   return 0;
}

Import XXX cannot be resolved for Java SE standard classes

If the project is Maven, you can try this way :

  1. right click the "Maven Dependencies"-->"Build Path"-->"Remove from the build path";
  2. right click the project ,navigate to "Maven"--->"Update project....";

Then the import issue should be solved .

TypeScript Objects as Dictionary types as in C#

You can also use the Record type in typescript :

export interface nameInterface { 
    propName : Record<string, otherComplexInterface> 
}

How to customize listview using baseadapter

public class ListElementAdapter extends BaseAdapter{

    String[] data;
    Context context;
    LayoutInflater layoutInflater;


    public ListElementAdapter(String[] data, Context context) {
        super();
        this.data = data;
        this.context = context;
        layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {

        return data.length;
    }

    @Override
    public Object getItem(int position) {

        return null;
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {


        convertView= layoutInflater.inflate(R.layout.item, null);

        TextView txt=(TextView)convertView.findViewById(R.id.text);

        txt.setText(data[position]);



        return convertView;
    }
}

Just call ListElementAdapter in your Main Activity and set Adapter to ListView.

Print all day-dates between two dates

Essentially the same as Gringo Suave's answer, but with a generator:

from datetime import datetime, timedelta


def datetime_range(start=None, end=None):
    span = end - start
    for i in xrange(span.days + 1):
        yield start + timedelta(days=i)

Then you can use it as follows:

In: list(datetime_range(start=datetime(2014, 1, 1), end=datetime(2014, 1, 5)))
Out: 
[datetime.datetime(2014, 1, 1, 0, 0),
 datetime.datetime(2014, 1, 2, 0, 0),
 datetime.datetime(2014, 1, 3, 0, 0),
 datetime.datetime(2014, 1, 4, 0, 0),
 datetime.datetime(2014, 1, 5, 0, 0)]

Or like this:

In []: for date in datetime_range(start=datetime(2014, 1, 1), end=datetime(2014, 1, 5)):
   ...:     print date
   ...:     
2014-01-01 00:00:00
2014-01-02 00:00:00
2014-01-03 00:00:00
2014-01-04 00:00:00
2014-01-05 00:00:00

How do I pass parameters into a PHP script through a webpage?

$argv[0]; // the script name
$argv[1]; // the first parameter
$argv[2]; // the second parameter

If you want to all the script to run regardless of where you call it from (command line or from the browser) you'll want something like the following:

<?php
if ($_GET) {
    $argument1 = $_GET['argument1'];
    $argument2 = $_GET['argument2'];
} else {
    $argument1 = $argv[1];
    $argument2 = $argv[2];
}
?>

To call from command line chmod 755 /var/www/webroot/index.php and use

/usr/bin/php /var/www/webroot/index.php arg1 arg2

To call from the browser, use

http://www.mydomain.com/index.php?argument1=arg1&argument2=arg2

Google Maps setCenter()

I searched and searched and finally found that ie needs to know the map size. Set the map size to match the div size.

map = new GMap2(document.getElementById("map_canvas2"), { size: new GSize(850, 600) });

<div id="map_canvas2" style="width: 850px; height: 600px">
</div>

Interface defining a constructor signature?

One way to solve this problem i found is to seperate out the construction into a seperate factory. For example I have an abstract class called IQueueItem, and I need a way to translate that object to and from another object (CloudQueueMessage). So on the interface IQueueItem i have -

public interface IQueueItem
{
    CloudQueueMessage ToMessage();
}

Now, I also need a way for my actual queue class to translate a CloudQueueMessage back to a IQueueItem - ie the need for a static construction like IQueueItem objMessage = ItemType.FromMessage. Instead I defined another interface IQueueFactory -

public interface IQueueItemFactory<T> where T : IQueueItem
{
    T FromMessage(CloudQueueMessage objMessage);
}

Now I can finally write my generic queue class without the new() constraint which in my case was the main issue.

public class AzureQueue<T> where T : IQueueItem
{
    private IQueueItemFactory<T> _objFactory;
    public AzureQueue(IQueueItemFactory<T> objItemFactory)
    {
        _objFactory = objItemFactory;
    }


    public T GetNextItem(TimeSpan tsLease)
    {
        CloudQueueMessage objQueueMessage = _objQueue.GetMessage(tsLease);
        T objItem = _objFactory.FromMessage(objQueueMessage);
        return objItem;
    }
}

now I can create an instance that satisfies the criteria for me

 AzureQueue<Job> objJobQueue = new JobQueue(new JobItemFactory())

hopefully this helps someone else out someday, obviously a lot of internal code removed to try to show the problem and solution

Is there a way to have printf() properly print out an array (of floats, say)?

You need to go for a loop:

for (int i = 0; i < sizeof(foo) / sizeof(float); ++i)
   printf("%f", foo[i]);
printf("\n");

How to check if a variable is NULL, then set it with a MySQL stored procedure?

@last_run_time is a 9.4. User-Defined Variables and last_run_time datetime one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.

Try: SELECT last_run_time;

UPDATE

Example:

/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$

CREATE PROCEDURE `sp_test`()
BEGIN
    DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
    DECLARE last_run_time DATETIME DEFAULT NULL;
    DECLARE current_run_time DATETIME DEFAULT NOW();

    -- Define the last run time
    SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);

    -- if there is no last run time found then use yesterday as starting point
    IF(last_run_time IS NULL) THEN
        SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
    END IF;

    SELECT last_run_time;

    -- Insert variables in table2
    INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$

DELIMITER ;

how to install multiple versions of IE on the same system?

To answer your question: no, it's not possible to have multiple versions of IE (if that is what you meant) installed in a 'normal' way (i.e. not a hack, a sandbox or a VM etc). It's perfectly ok to have multiple browsers of different types installed on the same machine, such as IE8, Firefox 3 and Chrome all at once.

SandboxIE should allow you to install multiple versions of IE side-by-side (as well as other software), and this is less hassle than going down the virtual machine route.

However, from a QA point of view I'd strongly recommend installing different versions on different machines as the best option from a testing point of view. This will give you the most realistic testing environment. If you don't have the hardware for that, then virtual machines are the next best option as mentioned in some of the other answers.

Can I use if (pointer) instead of if (pointer != NULL)?

As others already answered well, they both are interchangeable.

Nonetheless, it's worth mentioning that there could be a case where you may want to use the explicit statement, i.e. pointer != NULL.

See also https://stackoverflow.com/a/60891279/2463963

UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

If you are using Windows command line to print the data, you should use

chcp 65001

This worked for me!

What are the different types of keys in RDBMS?

There is also a SURROGATE KEY: it occurs if one non prime attribute depends on another non prime attribute. that time you don't now to choose which key as primary key to split up your table. In that case use a surrogate key instead of a primary key. Usually this key is system defined and always have numeric values and its value often automatically incremented for new rows. Eg : ms acces = auto number & my SQL = identity column & oracle = sequence.

Unique device identification

It looks like the phoneGap plugin will allow you to get the device's uid.

http://docs.phonegap.com/en/3.0.0/cordova_device_device.md.html#device.uuid

Update: This is dependent on running native code. We used this solution writing javascript that was being compiled to native code for a native phone application we were creating.

Python datetime to string without microsecond component

>>> import datetime
>>> now = datetime.datetime.now()
>>> print unicode(now.replace(microsecond=0))
2011-11-03 11:19:07

how to convert a string to a bool

I know this doesn't answer your question, but just to help other people. If you are trying to convert "true" or "false" strings to boolean:

Try Boolean.Parse

bool val = Boolean.Parse("true"); ==> true
bool val = Boolean.Parse("True"); ==> true
bool val = Boolean.Parse("TRUE"); ==> true
bool val = Boolean.Parse("False"); ==> false
bool val = Boolean.Parse("1"); ==> Exception!
bool val = Boolean.Parse("diffstring"); ==> Exception!

Read line with Scanner

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication1;

import java.io.File;
import java.util.Scanner;

/**
 *
 * @author zsagga
 */
class openFile {
        private Scanner x ; 
        int count = 0 ; 
        String path = "C:\\Users\\zsagga\\Documents\\NetBeansProjects\\JavaApplication1\\src\\javaapplication1\\Readthis.txt"; 


    public void openFile() {
//                System.out.println("I'm Here");
        try {
            x = new Scanner(new File(path)); 

        } 
        catch (Exception e) {
            System.out.println("Could not find a file");
        }
    }

    public void readFile() {

        while (x.hasNextLine()){
            count ++ ;
            x.nextLine();     
        }
        System.out.println(count);
    }

    public void closeFile() {
        x.close();
    }
}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication1;

/**
 *
 * @author zsagga
 */
public class JavaApplication1 {

    public static void main(String[] args) {
        // TODO code application logic here
        openFile r =  new openFile(); 
        r.openFile(); 
        r.readFile();
        r.closeFile(); 

    }
}

How to push JSON object in to array using javascript

var postdata = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};

var data = [];
data.push(postdata);

console.log(data);

With block equivalent in C#?

Although C# doesn't have any direct equivalent for the general case, C# 3 gain object initializer syntax for constructor calls:

var foo = new Foo { Property1 = value1, Property2 = value2, etc };

See chapter 8 of C# in Depth for more details - you can download it for free from Manning's web site.

(Disclaimer - yes, it's in my interest to get the book into more people's hands. But hey, it's a free chapter which gives you more information on a related topic...)

Interfaces with static fields in java for sharing 'constants'

I do not pretend the right to be right, but lets see this small example:

public interface CarConstants {

      static final String ENGINE = "mechanical";
      static final String WHEEL  = "round";
      // ...

}

public interface ToyotaCar extends CarConstants //, ICar, ... {
      void produce();
}

public interface FordCar extends CarConstants //, ICar, ... {
      void produce();
}

// and this is implementation #1
public class CamryCar implements ToyotaCar {

      public void produce() {
           System.out.println("the engine is " + ENGINE );
           System.out.println("the wheel is " + WHEEL);
      }
}

// and this is implementation #2
public class MustangCar implements FordCar {

      public void produce() {
           System.out.println("the engine is " + ENGINE );
           System.out.println("the wheel is " + WHEEL);
      }
}

ToyotaCar doesnt know anything about FordCar, and FordCar doesnt know about ToyotaCar. principle CarConstants should be changed, but...

Constants should not be changed, because the wheel is round and egine is mechanical, but... In the future Toyota's research engineers invented electronic engine and flat wheels! Lets see our new interface

public interface InnovativeCarConstants {

          static final String ENGINE = "electronic";
          static final String WHEEL  = "flat";
          // ...
}

and now we can change our abstraction:

public interface ToyotaCar extends CarConstants

to

public interface ToyotaCar extends InnovativeCarConstants 

And now if we ever need to change the core value if the ENGINE or WHEEL we can change the ToyotaCar Interface on abstraction level, dont touching implementations

Its NOT SAFE, I know, but I still want to know that do you think about this

How to get a unique device ID in Swift?

The value of identifierForVendor changes when the user deletes all of that vendor’s apps from the device, if you want to keep the unique ID even for the subsequent fresh installations, you can try to use the following function

func vendorIdentifierForDevice()->String {
    //Get common part of Applicatoin Bundle ID, Note : getCommonPartOfApplicationBundleID is to be defined.
    let commonAppBundleID = getCommonPartOfApplicationBundleID()
    //Read from KeyChain using bunndle ID, Note : readFromKeyChain is to be defined.
    if let vendorID = readFromKeyChain(commonAppBundleID) {
        return vendorID
    } else {
        var vendorID = NSUUID().uuidString
        //Save to KeyChain using bunndle ID, Note : saveToKeyChain is to be defined.
        saveToKeyChain(commonAppBundleID, vendorID)
        return vendorID
    }
}

How to change scroll bar position with CSS?

Try this out. Hope this helps

<div id="single" dir="rtl">
    <div class="common">Single</div>
</div>

<div id="both" dir="ltr">
    <div class="common">Both</div>
</div>



#single, #both{
    width: 100px;
    height: 100px;
    overflow: auto;
    margin: 0 auto;
    border: 1px solid gray;
}


.common{
    height: 150px;
    width: 150px;
}

LINK : fatal error LNK1104: cannot open file 'D:\...\MyProj.exe'

Just to add another solution to the list, what I've found is that Visual Studio (2012 in my case) occasionally locks files under different processes.

So, on a crash, devenv.exe might still be running and holding onto the file(s). Alternatively (as I just discovered), vstestrunner or vstestdiscovery might be holding onto the file as well.

Kill all those processes and it might fix up the issue.

What's the difference between subprocess Popen and call (how can I use them)?

There are two ways to do the redirect. Both apply to either subprocess.Popen or subprocess.call.

  1. Set the keyword argument shell = True or executable = /path/to/the/shell and specify the command just as you have it there.

  2. Since you're just redirecting the output to a file, set the keyword argument

    stdout = an_open_writeable_file_object
    

    where the object points to the output file.

subprocess.Popen is more general than subprocess.call.

Popen doesn't block, allowing you to interact with the process while it's running, or continue with other things in your Python program. The call to Popen returns a Popen object.

call does block. While it supports all the same arguments as the Popen constructor, so you can still set the process' output, environmental variables, etc., your script waits for the program to complete, and call returns a code representing the process' exit status.

returncode = call(*args, **kwargs) 

is basically the same as calling

returncode = Popen(*args, **kwargs).wait()

call is just a convenience function. It's implementation in CPython is in subprocess.py:

def call(*popenargs, timeout=None, **kwargs):
    """Run command with arguments.  Wait for command to complete or
    timeout, then return the returncode attribute.

    The arguments are the same as for the Popen constructor.  Example:

    retcode = call(["ls", "-l"])
    """
    with Popen(*popenargs, **kwargs) as p:
        try:
            return p.wait(timeout=timeout)
        except:
            p.kill()
            p.wait()
            raise

As you can see, it's a thin wrapper around Popen.

Can't import org.apache.http.HttpResponse in Android Studio

According to the Apache site this is the Gradle dependency you need to include, if you use Android API 23 or newer:

dependencies {
    compile group: 'cz.msebera.android' , name: 'httpclient', version: '4.4.1.1'
}

Source: https://hc.apache.org/httpcomponents-client-4.5.x/android-port.html

How to display Wordpress search results?

Check whether your template in theme folder contains search.php and searchform.php or not.

Highlight text similar to grep, but don't filter out text

Maybe this is an XY problem, and what you are really trying to do is to highlight occurrences of words as they appear in your shell. If so, you may be able to use your terminal emulator for this. For instance, in Konsole, start Find (ctrl+shift+F) and type your word. The word will then be highlighted whenever it occurs in new or existing output until you cancel the function.

typeof operator in C

It's not exactly an operator, rather a keyword. And no, it doesn't do any runtime-magic.

How to copy a file to another path?

TO Copy The Folder I Use Two Text Box To Know The Place Of Folder And Anther Text Box To Know What The Folder To Copy It And This Is The Code

MessageBox.Show("The File is Create in The Place Of The Programe If you Don't Write The Place Of copy And You write Only Name Of Folder");// It Is To Help The User TO Know
          if (Fromtb.Text=="")
        {
            MessageBox.Show("Ples You Should Write All Text Box");
            Fromtb.Select();
            return;
        }
        else if (Nametb.Text == "")
        {
            MessageBox.Show("Ples You Should Write The Third Text Box");
            Nametb.Select();
            return;
        }
        else if (Totb.Text == "")
        {
            MessageBox.Show("Ples You Should Write The Second Text Box");
            Totb.Select();
            return;
        }

        string fileName = Nametb.Text;
        string sourcePath = @"" + Fromtb.Text;
        string targetPath = @"" + Totb.Text;


        string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
        string destFile = System.IO.Path.Combine(targetPath, fileName);


        if (!System.IO.Directory.Exists(targetPath))
        {
            System.IO.Directory.CreateDirectory(targetPath);
            //when The User Write The New Folder It Will Create 
            MessageBox.Show("The File is Create in "+" "+Totb.Text);
        }


        System.IO.File.Copy(sourceFile, destFile, true);


        if (System.IO.Directory.Exists(sourcePath))
        {
            string[] files = System.IO.Directory.GetFiles(sourcePath);


            foreach (string s in files)
            {
                fileName = System.IO.Path.GetFileName(s);
                destFile = System.IO.Path.Combine(targetPath, fileName);
                System.IO.File.Copy(s, destFile, true);

            }
            MessageBox.Show("The File is copy To " + Totb.Text);

        }

Do fragments really need an empty constructor?

Yes, as you can see the support-package instantiates the fragments too (when they get destroyed and re-opened). Your Fragment subclasses need a public empty constructor as this is what's being called by the framework.

What is difference between cacerts and keystore?

cacerts is where Java stores public certificates of root CAs. Java uses cacerts to authenticate the servers.

Keystore is where Java stores the private keys of the clients so that it can share it to the server when the server requests client authentication.

Get screenshot on Windows with Python?

You can use the ImageGrab module. ImageGrab works on Windows and macOS, and you need PIL (Pillow) to use it. Here is a little example:

from PIL import ImageGrab
snapshot = ImageGrab.grab()
save_path = "C:\\Users\\YourUser\\Desktop\\MySnapshot.jpg"
snapshot.save(save_path)

jQuery '.each' and attaching '.click' event

No need to use .each. click already binds to all div occurrences.

$('div').click(function(e) {
    ..    
});

See Demo

Note: use hard binding such as .click to make sure dynamically loaded elements don't get bound.

How to write a file with C in Linux?

You have to allocate the buffer with mallock, and give the read write the pointer to it.

#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(){
    ssize_t nrd;
    int fd; 
    int fd1;

    char* buffer = malloc(100*sizeof(char));
    fd = open("bli.txt", O_RDONLY);
    fd1 = open("bla.txt", O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
    while (nrd = read(fd,buffer,sizeof(buffer))) {
        write(fd1,buffer,nrd);
    }   

    close(fd);
    close(fd1);
    free(buffer);
    return 0;
}

Make sure that the rad file exists and contains something. It's not perfect but it works.

Python: how to capture image from webcam on click using OpenCV

i'm not too experienced with open cv but if you want the code in the for loop to be called when a key is pressed, you can use a while loop and an raw_input and a condition to prevent the loop from executing forever

import cv2

camera = cv2.VideoCapture(0)
i = 0
while i < 10:
    raw_input('Press Enter to capture')
    return_value, image = camera.read()
    cv2.imwrite('opencv'+str(i)+'.png', image)
    i += 1
del(camera)

ArrayList of String Arrays

I wouldn't use arrays. They're problematic for several reasons and you can't declare it in terms of a specific array size anyway. Try:

List<List<String>> addresses = new ArrayList<List<String>>();

But honestly for addresses, I'd create a class to model them.

If you were to use arrays it would be:

List<String[]> addresses = new ArrayList<String[]>();

ie you can't declare the size of the array.

Lastly, don't declare your types as concrete types in instances like this (ie for addresses). Use the interface as I've done above. This applies to member variables, return types and parameter types.

How do I get rid of the "cannot empty the clipboard" error?

I found this advice:

There are a few steps to solve your problem:

First thing to do is Clear items from the Office Clipboard. If the Microsoft Office Clipboard is not displayed in the task pane, click Office Clipboard on the Edit menu. On the Office Clipboard task pane, do one of the following: To clear all items, click Clear All .

Next thing is to switch off the clipboard show option. To do this, what you can do is to again display the Clipboard menu (select Office Clipboard from Edit Menu). And in the selection button "Options" at the bottom of the screen, select this particular option: "Collect Without Showing Office Clipboard"

and now, you are relieved of the bug.

Hope this helps.

here. I have the problem, but it's sporadic. I just tried the technique, and I don't see the problem, but since it's sporadic I won't know for a while if it's gone for good.

Can not find the tag library descriptor of springframework

Here is another case.

We have several portlets in different portlet application war and all of them use spring. So in order to reduce size of each war, we have created shared libraries for spring jars in the WebSphere Portal server.

However, I came across the same issue as above of not having the spring form tags being referred from the jsp files.

In order to resolve, I have copied the spring-form.tld file into the WEB-INF/ directory and redeployed the war and it worked.

Hope it helps for anyone having a similar issue as mine.

How to decode HTML entities using jQuery?

Here are still one problem: Escaped string does not look readable when assigned to input value

var string = _.escape("<img src=fake onerror=alert('boo!')>");
$('input').val(string);

Exapmle: https://jsfiddle.net/kjpdwmqa/3/

Extracting Ajax return data in jQuery

Change the .find to .filter...

How to call a web service from jQuery

You can make an AJAX request like any other requests:

$.ajax( {
type:'Get',
url:'http://mysite.com/mywebservice',
success:function(data) {
 alert(data);
}

})

PostgreSQL CASE ... END with multiple conditions

This kind of code perhaps should work for You

SELECT
 *,
 CASE
  WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
  ELSE '00'
 END AS modifiedpvc
FROM my_table;


 gid | datepose | pvc | modifiedpvc 
-----+----------+-----+-------------
   1 |     1961 | 01  | 00
   2 |     1949 |     | 01
   3 |     1990 | 02  | 00
   1 |     1981 |     | 02
   1 |          | 03  | 00
   1 |          |     | 03
(6 rows)

How to convert a Kotlin source file to a Java source file

You can compile Kotlin to bytecode, then use a Java disassembler.

The decompiling may be done inside IntelliJ Idea, or using FernFlower https://github.com/fesh0r/fernflower (thanks @Jire)

There was no automated tool as I checked a couple months ago (and no plans for one AFAIK)

Python Pandas : pivot table with aggfunc = count unique distinct

You can construct a pivot table for each distinct value of X. In this case,

for xval, xgroup in g:
    ptable = pd.pivot_table(xgroup, rows='Y', cols='Z', 
        margins=False, aggfunc=numpy.size)

will construct a pivot table for each value of X. You may want to index ptable using the xvalue. With this code, I get (for X1)

     X        
Z   Z1  Z2  Z3
Y             
Y1   2   1 NaN
Y2 NaN NaN   1

What's the purpose of the LEA instruction?

Forgive me if someone already mentioned, but in the days of x86 when memory segmentation was still relevant, you may not get the same results from these two instructions:

LEA AX, DS:[0x1234]

and

LEA AX, CS:[0x1234]

ReactJS: Maximum update depth exceeded error

if you don't need to pass arguments to function, just remove () from function like below:

<td><span onClick={this.toggle}>Details</span></td>

but if you want to pass arguments, you should do like below:

<td><span onClick={(e) => this.toggle(e,arg1,arg2)}>Details</span></td>

scrollIntoView Scrolls just too far

I add this css tips for those who not resolved this issue with solutions above :

#myDiv::before {
  display: block;
  content: " ";
  margin-top: -90px; // adjust this with your header height
  height: 90px; // adjust this with your header height
  visibility: hidden;
}

How do I show the number keyboard on an EditText in android?

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    ...
    android:inputType="number|phone"/> 

will show the large number pad as dialer.

failed to resolve com.android.support:appcompat-v7:22 and com.android.support:recyclerview-v7:21.1.2

I had such dependancy in build.gradle -

compile 'com.android.support:recyclerview-v7:+'

But it causes unstable builds. Ensure it works ok for you, and look in your android sdk manager for current version of support lib available, and replace this dependency with

def final RECYCLER_VIEW_VER = '23.1.1'
compile "com.android.support:recyclerview-v7:${RECYCLER_VIEW_VER}"

How to reference a file for variables using Bash?

even shorter using the dot:

#!/bin/bash
. CONFIG_FILE

sudo -u wwwrun svn up /srv/www/htdocs/$production
sudo -u wwwrun svn up /srv/www/htdocs/$playschool

download csv file from web api in angular js

The a.download is not supported by IE. At least at the HTML5 "supported" pages. :(

What is it exactly a BLOB in a DBMS context

They are binary large objects, you can use them to store binary data such as images or serialized objects among other things.

How to add a custom HTTP header to every WCF call?

This is similar to NimsDotNet answer but shows how to do it programmatically.

Simply add the header to the binding

var cl = new MyServiceClient();

var eab = new EndpointAddressBuilder(cl.Endpoint.Address);

eab.Headers.Add( 
      AddressHeader.CreateAddressHeader("ClientIdentification",  // Header Name
                                         string.Empty,           // Namespace
                                         "JabberwockyClient"));  // Header Value

cl.Endpoint.Address = eab.ToEndpointAddress();

How can I add spaces between two <input> lines using CSS?

You can format them as table !!

_x000D_
_x000D_
form {_x000D_
  display: table;_x000D_
}_x000D_
label {_x000D_
  display: table-row;_x000D_
}_x000D_
input {_x000D_
  display: table-cell;_x000D_
}_x000D_
p1 {_x000D_
  display: table-cell;_x000D_
}
_x000D_
<div id="header_order_form" align="center">_x000D_
  <form id="order_header" method="post">_x000D_
    <label>_x000D_
      <p1>order_no:_x000D_
        <input type="text">_x000D_
      </p1>_x000D_
      <p1>order_type:_x000D_
        <input type="text">_x000D_
      </p1>_x000D_
    </label>_x000D_
    </br>_x000D_
    </br>_x000D_
    <label>_x000D_
      <p1>_x000D_
        creation_date:_x000D_
        <input type="text">_x000D_
      </p1>_x000D_
      <p1>delivery_date:_x000D_
        <input type="text">_x000D_
      </p1>_x000D_
      <p1>billing_date:_x000D_
        <input type="text">_x000D_
      </p1>_x000D_
    </label>_x000D_
    </br>_x000D_
    </br>_x000D_
_x000D_
    <label>_x000D_
      <p1>sold_to_party:_x000D_
        <input type="text">_x000D_
      </p1>_x000D_
      <p1>sop_address:_x000D_
        <input type="text">_x000D_
      </p1>_x000D_
    </label>_x000D_
  </form>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Difference between "\n" and Environment.NewLine

You might get into trouble when you try to display multi-line message separated with "\r\n".

It is always a good practice to do things in a standard way, and use Environment.NewLine

ArrayList initialization equivalent to array initialization

Arrays.asList("Ryan", "Julie", "Bob");

How to compile a 32-bit binary on a 64-bit linux machine with gcc/cmake

In later versions of CMake, one way to do it on each target is:

set_target_properties(MyTarget PROPERTIES COMPILE_FLAGS "-m32" LINK_FLAGS "-m32")

I don't know of a way to do it globally.

Connect to Amazon EC2 file directory using Filezilla and SFTP

You can use any FTP client. I use winscp and it works just fine. In all these clients; you can specify the ssh secure key.

How can I loop through a List<T> and grab each item?

Just for completeness, there is also the LINQ/Lambda way:

myMoney.ForEach((theMoney) => Console.WriteLine("amount is {0}, and type is {1}", theMoney.amount, theMoney.type));

Setting device orientation in Swift iOS

I've been struggling all morning to get ONLY landscape left/right supported properly. I discovered something really annoying; although the "General" tab allows you to deselect "Portrait" for device orientation, you have to edit the plist itself to disable Portrait and PortraitUpsideDown INTERFACE orientations - it's the last key in the plist: "Supported Interface Orientations".

The other thing is that it seems you must use the "mask" versions of the enums (e.g., UIInterfaceOrientationMask.LandscapeLeft), not just the orientation one. The code that got it working for me (in my main viewController):

override func shouldAutorotate() -> Bool {
    return true
}

override func supportedInterfaceOrientations() -> Int {
    return Int(UIInterfaceOrientationMask.LandscapeLeft.rawValue) | Int(UIInterfaceOrientationMask.LandscapeRight.rawValue)
}

Making this combination of plist changes and code is the only way I've been able to get it working properly.

Indent starting from the second line of a paragraph with CSS

This worked for me:

p { margin-left: -2em; 
 text-indent: 2em 
 }

Importing CSV with line breaks in Excel 2007

Excel is incredibly broken when dealing with CSVs. LibreOffice does a much better job. So, I found out that:

  • The file must be encoded in UTF-8 with BOM, so consider this for all the points below
  • The best result, by far, is achieved by opening it from File Explorer
  • If you open it from within Excel there are two possible outcomes:
    • If it has only ASCII characters, it will most likely work
    • If it has non-ASCII characters, it will mess your line breaks
  • It seems to be heavily dependent on the decimal separator configured in the OS's regional settings, so you have to select the right one
  • I would bet that it may also behave differently depending on OS and Office version

How do I get an apk file from an Android device?

All these answers require multiple steps for each apk file retrieved from the device. 1. determine package name, 2. find the file, and 3. download it. I built a simple apk_grabber python script to do this for any app that matches a given regex, and then decompiles those apks into jar files.

Python, how to check if a result set is empty?

MySQLdb will not raise an exception if the result set is empty. Additionally cursor.execute() function will return a long value which is number of rows in the fetched result set. So if you want to check for empty results, your code can be re-written as

rows_count = cursor.execute(query_sql)
if rows_count > 0:
     rs = cursor.fetchall()
else:
     // handle empty result set

Delete files older than 3 months old in a directory using .NET

Here's a snippet of how to get the creation time of files in the directory and find those which have been created 3 months ago (90 days ago to be exact):

    DirectoryInfo source = new DirectoryInfo(sourceDirectoryPath);

    // Get info of each file into the directory
    foreach (FileInfo fi in source.GetFiles())
    {
        var creationTime = fi.CreationTime;

        if(creationTime < (DateTime.Now- new TimeSpan(90, 0, 0, 0)))
        {
            fi.Delete();
        }
    }

What are the possible values of the Hibernate hbm2ddl.auto configuration and what do they do

There's also the undocumented value of "none" to disable it entirely.

How to insert an item at the beginning of an array in PHP?

In case of an associative array or numbered array where you do not want to change the array keys:

$firstItem = array('foo' => 'bar');

$arr = $firstItem + $arr;

array_merge does not work as it always reindexes the array.

Enable vertical scrolling on textarea

Maybe a fixed height and overflow-y: scroll;

What is the difference between os.path.basename() and os.path.dirname()?

To summarize what was mentioned by Breno above

Say you have a variable with a path to a file

path = '/home/User/Desktop/myfile.py'

os.path.basename(path) returns the string 'myfile.py'

and

os.path.dirname(path) returns the string '/home/User/Desktop' (without a trailing slash '/')

These functions are used when you have to get the filename/directory name given a full path name.

In case the file path is just the file name (e.g. instead of path = '/home/User/Desktop/myfile.py' you just have myfile.py), os.path.dirname(path) returns an empty string.

AngularJS - value attribute for select

You can't really do this unless you build them yourself in an ng-repeat.

<select ng-model="foo">
   <option ng-repeat="item in items" value="{{item.code}}">{{item.name}}</option>
</select>

BUT... it's probably not worth it. It's better to leave it function as designed and let Angular handle the inner workings. Angular uses the index this way so you can actually use an entire object as a value. So you can use a drop down binding to select a whole value rather than just a string, which is pretty awesome:

<select ng-model="foo" ng-options="item as item.name for item in items"></select>

{{foo | json}}

C#: How do you edit items and subitems in a listview?

private void listView1_MouseDown(object sender, MouseEventArgs e)
{
    li = listView1.GetItemAt(e.X, e.Y);
    X = e.X;
    Y = e.Y;
}

private void listView1_MouseUp(object sender, MouseEventArgs e)
{
    int nStart = X;
    int spos = 0;
    int epos = listView1.Columns[1].Width;
    for (int i = 0; i < listView1.Columns.Count; i++)
    {
        if (nStart > spos && nStart < epos)
        {
            subItemSelected = i;
            break;
        }

        spos = epos;
        epos += listView1.Columns[i].Width;
    }
    li.SubItems[subItemSelected].Text = "9";
}

Java: Get month Integer from Date

If you use Java 8 date api, you can directly get it in one line!

LocalDate today = LocalDate.now();
int month = today.getMonthValue();

Simple IEnumerator use (with example)

Also you can use LINQ's Select Method:

var source = new[] { "Line 1", "Line 2" };

var result = source.Select(s => s + " roxxors");

Read more here Enumerable.Select Method

How may I reference the script tag that loaded the currently-executing script?

I've got this, which is working in FF3, IE6 & 7. The methods in the on-demand loaded scripts aren't available until page load is complete, but this is still very useful.

//handle on-demand loading of javascripts
makescript = function(url){
    var v = document.createElement('script');
    v.src=url;
    v.type='text/javascript';

    //insertAfter. Get last <script> tag in DOM
    d=document.getElementsByTagName('script')[(document.getElementsByTagName('script').length-1)];
    d.parentNode.insertBefore( v, d.nextSibling );
}

Converting a date in MySQL from string field

SELECT STR_TO_DATE(dateString, '%d/%m/%y') FROM yourTable...

Reading data from DataGridView in C#

 private void HighLightGridRows()
 {            
     Debugger.Launch();
     for (int i = 0; i < dtgvAppSettings.Rows.Count; i++)
     {
         String key = dtgvAppSettings.Rows[i].Cells["Key"].Value.ToString();
         if (key.ToLower().Contains("applicationpath") == true)
         {
             dtgvAppSettings.Rows[i].DefaultCellStyle.BackColor = Color.Yellow;
         }
     }
 }

How do I ignore all files in a folder with a Git repository in Sourcetree?

Right click on a file → IgnoreIgnore everything beneath.

If the Ignore option is grayed out then:

  1. Stage a file first
  2. Right click → Stop Tracking
  3. That file will appear in the pane below with a question mark → Right click on it→ Ignore

Enter image description here

Remove all whitespace from C# string with regex

Fastest and general way to do this (line terminators, tabs will be processed as well). Regex powerful facilities don't really needed to solve this problem, but Regex can decrease performance.

                       new string
                           (stringToRemoveWhiteSpaces
                                .Where
                                (
                                    c => !char.IsWhiteSpace(c)
                                )
                                .ToArray<char>()
                           )

OR

                       new string
                           (stringToReplaceWhiteSpacesWithSpace
                                .Select
                                (
                                    c => char.IsWhiteSpace(c) ? ' ' : c
                                )
                                .ToArray<char>()
                           )

VirtualBox error "Failed to open a session for the virtual machine"

On Ubuntu, this can also be caused by incorrect permissions. I chmod 755 Logs/ which fixed the issue.

How to Diff between local uncommitted changes and origin

I know it's not an answer to the exact question asked, but I found this question looking to diff a file in a branch and a local uncommitted file and I figured I would share

Syntax:

git diff <commit-ish>:./ -- <path>

Examples:

git diff origin/master:./ -- README.md
git diff HEAD^:./ -- README.md
git diff stash@{0}:./ -- README.md
git diff 1A2B3C4D:./ -- README.md

(Thanks Eric Boehs for a way to not have to type the filename twice)

Is it possible to append Series to rows of DataFrame without making a list first?

Maybe an easier way would be to add the pandas.Series into the pandas.DataFrame with ignore_index=True argument to DataFrame.append(). Example -

DF = DataFrame()
for sample,data in D_sample_data.items():
    SR_row = pd.Series(data.D_key_value)
    DF = DF.append(SR_row,ignore_index=True)

Demo -

In [1]: import pandas as pd

In [2]: df = pd.DataFrame([[1,2],[3,4]],columns=['A','B'])

In [3]: df
Out[3]:
   A  B
0  1  2
1  3  4

In [5]: s = pd.Series([5,6],index=['A','B'])

In [6]: s
Out[6]:
A    5
B    6
dtype: int64

In [36]: df.append(s,ignore_index=True)
Out[36]:
   A  B
0  1  2
1  3  4
2  5  6

Another issue in your code is that DataFrame.append() is not in-place, it returns the appended dataframe, you would need to assign it back to your original dataframe for it to work. Example -

DF = DF.append(SR_row,ignore_index=True)

To preserve the labels, you can use your solution to include name for the series along with assigning the appended DataFrame back to DF. Example -

DF = DataFrame()
for sample,data in D_sample_data.items():
    SR_row = pd.Series(data.D_key_value,name=sample)
    DF = DF.append(SR_row)
DF.head()

Convert char * to LPWSTR

You may use CString, CStringA, CStringW to do automatic conversions and convert between these types. Further, you may also use CStrBuf, CStrBufA, CStrBufW to get RAII pattern modifiable strings

How to detect when a youtube video finishes playing?

What you may want to do is include a script on all pages that does the following ... 1. find the youtube-iframe : searching for it by width and height by title or by finding www.youtube.com in its source. You can do that by ... - looping through the window.frames by a for-in loop and then filter out by the properties

  1. inject jscript in the iframe of the current page adding the onYoutubePlayerReady must-include-function http://shazwazza.com/post/Injecting-JavaScript-into-other-frames.aspx

  2. Add the event listeners etc..

Hope this helps

Dynamic SQL results into temp table in SQL Stored procedure

Be careful of a global temp table solution as this may fail if two users use the same routine at the same time as a global temp table can be seen by all users...

What is the exact meaning of Git Bash?

At its core, Git is a set of command line utility programs that are designed to execute on a Unix style command-line environment. Modern operating systems like Linux and macOS both include built-in Unix command line terminals. This makes Linux and macOS complementary operating systems when working with Git. Microsoft Windows instead uses Windows command prompt, a non-Unix terminal environment.

What is Git Bash?

Git Bash is an application for Microsoft Windows environments which provides an emulation layer for a Git command line experience. Bash is an acronym for Bourne Again Shell. A shell is a terminal application used to interface with an operating system through written commands. Bash is a popular default shell on Linux and macOS. Git Bash is a package that installs Bash, some common bash utilities, and Git on a Windows operating system.

source : https://www.atlassian.com/git/tutorials/git-bash

Can I run Keras model on gpu?

See if your script is running GPU in Task manager. If not, suspect your CUDA version is right one for the tensorflow version you are using, as the other answers suggested already.

Additionally, a proper CUDA DNN library for the CUDA version is required to run GPU with tensorflow. Download/extract it from here and put the DLL (e.g., cudnn64_7.dll) into CUDA bin folder (e.g., C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin).

newline character in c# string

They might be just a \r or a \n. I just checked and the text visualizer in VS 2010 displays both as newlines as well as \r\n.

This string

string test = "blah\r\nblah\rblah\nblah";

Shows up as

blah
blah
blah
blah

in the text visualizer.

So you could try

string modifiedString = originalString
    .Replace(Environment.NewLine, "<br />")
    .Replace("\r", "<br />")
    .Replace("\n", "<br />");

Difference between 'struct' and 'typedef struct' in C++?

An important difference between a 'typedef struct' and a 'struct' in C++ is that inline member initialisation in 'typedef structs' will not work.

// the 'x' in this struct will NOT be initialised to zero
typedef struct { int x = 0; } Foo;

// the 'x' in this struct WILL be initialised to zero
struct Foo { int x = 0; };

Print all key/value pairs in a Java ConcurrentHashMap

  //best and simple way to show keys and values

    //initialize map
    Map<Integer, String> map = new HashMap<Integer, String>();

   //Add some values
    map.put(1, "Hi");
    map.put(2, "Hello");

    // iterate map using entryset in for loop
    for(Entry<Integer, String> entry : map.entrySet())
    {   //print keys and values
         System.out.println(entry.getKey() + " : " +entry.getValue());
    }

   //Result : 
    1 : Hi
    2 : Hello

How can I check if PostgreSQL is installed or not via Linux script?

aptitude show postgresql | grep Version worked for me

Git with SSH on Windows

I was trying to solve my issue with some of the answers above and for some reason it didn't work. I did switch to use the git extensions and this are the steps I did follow.

  1. I went to Tools -> Settings -> SSH -> Other ssh client
  2. Set this value to C:\Program Files\Git\usr\bin\ssh.exe
  3. Apply

I guess that this steps are just the same explained above. The only difference is that I used the Git Extensions User Interface instead of the terminal. Hope this help.

Convert wchar_t to char

Here's another way of doing it, remember to use free() on the result.

char* wchar_to_char(const wchar_t* pwchar)
{
    // get the number of characters in the string.
    int currentCharIndex = 0;
    char currentChar = pwchar[currentCharIndex];

    while (currentChar != '\0')
    {
        currentCharIndex++;
        currentChar = pwchar[currentCharIndex];
    }

    const int charCount = currentCharIndex + 1;

    // allocate a new block of memory size char (1 byte) instead of wide char (2 bytes)
    char* filePathC = (char*)malloc(sizeof(char) * charCount);

    for (int i = 0; i < charCount; i++)
    {
        // convert to char (1 byte)
        char character = pwchar[i];

        *filePathC = character;

        filePathC += sizeof(char);

    }
    filePathC += '\0';

    filePathC -= (sizeof(char) * charCount);

    return filePathC;
}

Password Strength Meter

Password Strength Algorithm:

Password Length:
    5 Points: Less than 4 characters
    10 Points: 5 to 7 characters
    25 Points: 8 or more

Letters:
    0 Points: No letters
    10 Points: Letters are all lower case
    20 Points: Letters are upper case and lower case

Numbers:
    0 Points: No numbers
    10 Points: 1 number
    20 Points: 3 or more numbers

Characters:
    0 Points: No characters
    10 Points: 1 character
    25 Points: More than 1 character

Bonus:
    2 Points: Letters and numbers
    3 Points: Letters, numbers, and characters
    5 Points: Mixed case letters, numbers, and characters

Password Text Range:

    >= 90: Very Secure
    >= 80: Secure
    >= 70: Very Strong
    >= 60: Strong
    >= 50: Average
    >= 25: Weak
    >= 0: Very Weak

Settings Toggle to true or false, if you want to change what is checked in the password

var m_strUpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var m_strLowerCase = "abcdefghijklmnopqrstuvwxyz";
var m_strNumber = "0123456789";
var m_strCharacters = "!@#$%^&*?_~"

Check password


function checkPassword(strPassword)
{
    // Reset combination count
    var nScore = 0;

    // Password length
    // -- Less than 4 characters
    if (strPassword.length < 5)
    {
        nScore += 5;
    }
    // -- 5 to 7 characters
    else if (strPassword.length > 4 && strPassword.length < 8)
    {
        nScore += 10;
    }
    // -- 8 or more
    else if (strPassword.length > 7)
    {
        nScore += 25;
    }

    // Letters
    var nUpperCount = countContain(strPassword, m_strUpperCase);
    var nLowerCount = countContain(strPassword, m_strLowerCase);
    var nLowerUpperCount = nUpperCount + nLowerCount;
    // -- Letters are all lower case
    if (nUpperCount == 0 && nLowerCount != 0) 
    { 
        nScore += 10; 
    }
    // -- Letters are upper case and lower case
    else if (nUpperCount != 0 && nLowerCount != 0) 
    { 
        nScore += 20; 
    }

    // Numbers
    var nNumberCount = countContain(strPassword, m_strNumber);
    // -- 1 number
    if (nNumberCount == 1)
    {
        nScore += 10;
    }
    // -- 3 or more numbers
    if (nNumberCount >= 3)
    {
        nScore += 20;
    }

    // Characters
    var nCharacterCount = countContain(strPassword, m_strCharacters);
    // -- 1 character
    if (nCharacterCount == 1)
    {
        nScore += 10;
    }   
    // -- More than 1 character
    if (nCharacterCount > 1)
    {
        nScore += 25;
    }

    // Bonus
    // -- Letters and numbers
    if (nNumberCount != 0 && nLowerUpperCount != 0)
    {
        nScore += 2;
    }
    // -- Letters, numbers, and characters
    if (nNumberCount != 0 && nLowerUpperCount != 0 && nCharacterCount != 0)
    {
        nScore += 3;
    }
    // -- Mixed case letters, numbers, and characters
    if (nNumberCount != 0 && nUpperCount != 0 && nLowerCount != 0 && nCharacterCount != 0)
    {
        nScore += 5;
    }


    return nScore;
}

// Runs password through check and then updates GUI 


function runPassword(strPassword, strFieldID) 
{
    // Check password
    var nScore = checkPassword(strPassword);


     // Get controls
        var ctlBar = document.getElementById(strFieldID + "_bar"); 
        var ctlText = document.getElementById(strFieldID + "_text");
        if (!ctlBar || !ctlText)
            return;

        // Set new width
        ctlBar.style.width = (nScore*1.25>100)?100:nScore*1.25 + "%";

    // Color and text
    // -- Very Secure
    /*if (nScore >= 90)
    {
        var strText = "Very Secure";
        var strColor = "#0ca908";
    }
    // -- Secure
    else if (nScore >= 80)
    {
        var strText = "Secure";
        vstrColor = "#7ff67c";
    }
    // -- Very Strong
    else 
    */
    if (nScore >= 80)
    {
        var strText = "Very Strong";
        var strColor = "#008000";
    }
    // -- Strong
    else if (nScore >= 60)
    {
        var strText = "Strong";
        var strColor = "#006000";
    }
    // -- Average
    else if (nScore >= 40)
    {
        var strText = "Average";
        var strColor = "#e3cb00";
    }
    // -- Weak
    else if (nScore >= 20)
    {
        var strText = "Weak";
        var strColor = "#Fe3d1a";
    }
    // -- Very Weak
    else
    {
        var strText = "Very Weak";
        var strColor = "#e71a1a";
    }

    if(strPassword.length == 0)
    {
    ctlBar.style.backgroundColor = "";
    ctlText.innerHTML =  "";
    }
else
    {
    ctlBar.style.backgroundColor = strColor;
    ctlText.innerHTML =  strText;
}
}

// Checks a string for a list of characters
function countContain(strPassword, strCheck)
{ 
    // Declare variables
    var nCount = 0;

    for (i = 0; i < strPassword.length; i++) 
    {
        if (strCheck.indexOf(strPassword.charAt(i)) > -1) 
        { 
                nCount++;
        } 
    } 

    return nCount; 
} 

You can customize by yourself according to your requirement.

HTML code for an apostrophe

If you are looking for single quote, it is

&#39;

Using a list as a data source for DataGridView

First, I don't understand why you are adding all the keys and values count times, Index is never used.

I tried this example :

        var source = new BindingSource();
        List<MyStruct> list = new List<MyStruct> { new MyStruct("fff", "b"),  new MyStruct("c","d") };
        source.DataSource = list;
        grid.DataSource = source;

and that work pretty well, I get two columns with the correct names. MyStruct type exposes properties that the binding mechanism can use.

    class MyStruct
   {
    public string Name { get; set; }
    public string Adres { get; set; }


    public MyStruct(string name, string adress)
    {
        Name = name;
        Adres = adress;
    }
  }

Try to build a type that takes one key and value, and add it one by one. Hope this helps.

CSS z-index not working (position absolute)

I was struggling to figure it out how to put a div over an image like this: z-index working

No matter how I configured z-index in both divs (the image wrapper) and the section I was getting this:

z-index Not working

Turns out I hadn't set up the background of the section to be background: white;

so basically it's like this:

<div class="img-wrp">
  <img src="myimage.svg"/>
</div>
<section>
 <other content>
</section>

section{
  position: relative;
  background: white; /* THIS IS THE IMPORTANT PART NOT TO FORGET */
}
.img-wrp{
  position: absolute;
  z-index: -1; /* also worked with 0 but just to be sure */
}

Sending emails with Javascript

What about having a live validation on the textbox, and once it goes over 2000 (or whatever the maximum threshold is) then display 'This email is too long to be completed in the browser, please <span class="launchEmailClientLink">launch what you have in your email client</span>'

To which I'd have

.launchEmailClientLink {
cursor: pointer;
color: #00F;
}

and jQuery this into your onDomReady

$('.launchEmailClientLink').bind('click',sendMail);

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

Left Click on chart. «PivotTable Field List» will appear on right. On the right down quarter of PivotTable Field List (S Values), you see the names of the legends. Left Click on the legend name. Left Click on the «Value field settings». At the top there is «Source Name». You can’t change it. Below there is «Custom Name». Change the Custom Name as you wish. Now the legend name on the chart has the new name you gave.

How can I view a git log of just one user's commits?

This works for both git log and gitk - the 2 most common ways of viewing history.
You don't need to use the whole name:

git log --author="Jon"

will match a commit made by "Jonathan Smith"

git log --author=Jon

and

git log --author=Smith

would also work. The quotes are optional if you don't need any spaces.

Add --all if you intend to search all branches and not just the current commit's ancestors in your repo.

You can also easily match on multiple authors as regex is the underlying mechanism for this filter. So to list commits by Jonathan or Adam, you can do this:

git log --author="\(Adam\)\|\(Jon\)"

In order to exclude commits by a particular author or set of authors using regular expressions as noted in this question, you can use a negative lookahead in combination with the --perl-regexp switch:

git log --author='^(?!Adam|Jon).*$' --perl-regexp

Alternatively, you can exclude commits authored by Adam by using bash and piping:

git log --format='%H %an' | 
  grep -v Adam | 
  cut -d ' ' -f1 | 
  xargs -n1 git log -1

If you want to exclude commits commited (but not necessarily authored) by Adam, replace %an with %cn. More details about this are in my blog post here: http://dymitruk.com/blog/2012/07/18/filtering-by-author-name/

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

as you can see on the answer to this question: Conversion of a varchar data type to a datetime data type resulted in an out-of-range value

-- set the dateformat for the current session
set dateformat dmy

-- The conversion of a varchar data type 
-- to a datetime data type resulted in an out-of-range value.
select cast('2017-08-13 16:31:31'  as datetime)

-- get the current session date_format
select date_format
from sys.dm_exec_sessions
where session_id = @@spid

-- set the dateformat for the current session
set dateformat ymd

-- this should work
select cast('2017-08-13 16:31:31'  as datetime)

How to add a custom Ribbon tab using VBA?

I was able to accomplish this with VBA in Excel 2013. No special editors needed. All you need is the Visual Basic code editor which can be accessed on the Developer tab. The Developer tab is not visible by default so it needs to be enabled in File>Options>Customize Ribbon. On the Developer tab, click the Visual Basic button. The code editor will launch. Right click in the Project Explorer pane on the left. Click the insert menu and choose module. Add both subs below to the new module.

Sub LoadCustRibbon()

Dim hFile As Long
Dim path As String, fileName As String, ribbonXML As String, user As String

hFile = FreeFile
user = Environ("Username")
path = "C:\Users\" & user & "\AppData\Local\Microsoft\Office\"
fileName = "Excel.officeUI"

ribbonXML = "<mso:customUI      xmlns:mso='http://schemas.microsoft.com/office/2009/07/customui'>" & vbNewLine
ribbonXML = ribbonXML + "  <mso:ribbon>" & vbNewLine
ribbonXML = ribbonXML + "    <mso:qat/>" & vbNewLine
ribbonXML = ribbonXML + "    <mso:tabs>" & vbNewLine
ribbonXML = ribbonXML + "      <mso:tab id='reportTab' label='Reports' insertBeforeQ='mso:TabFormat'>" & vbNewLine
ribbonXML = ribbonXML + "        <mso:group id='reportGroup' label='Reports' autoScale='true'>" & vbNewLine
ribbonXML = ribbonXML + "          <mso:button id='runReport' label='PTO' "   & vbNewLine
ribbonXML = ribbonXML + "imageMso='AppointmentColor3'      onAction='GenReport'/>" & vbNewLine
ribbonXML = ribbonXML + "        </mso:group>" & vbNewLine
ribbonXML = ribbonXML + "      </mso:tab>" & vbNewLine
ribbonXML = ribbonXML + "    </mso:tabs>" & vbNewLine
ribbonXML = ribbonXML + "  </mso:ribbon>" & vbNewLine
ribbonXML = ribbonXML + "</mso:customUI>"

ribbonXML = Replace(ribbonXML, """", "")

Open path & fileName For Output Access Write As hFile
Print #hFile, ribbonXML
Close hFile

End Sub

Sub ClearCustRibbon()

Dim hFile As Long
Dim path As String, fileName As String, ribbonXML As String, user As String

hFile = FreeFile
user = Environ("Username")
path = "C:\Users\" & user & "\AppData\Local\Microsoft\Office\"
fileName = "Excel.officeUI"

ribbonXML = "<mso:customUI           xmlns:mso=""http://schemas.microsoft.com/office/2009/07/customui"">" & _
"<mso:ribbon></mso:ribbon></mso:customUI>"

Open path & fileName For Output Access Write As hFile
Print #hFile, ribbonXML
Close hFile

End Sub

Call LoadCustRibbon sub in the Wookbook open even and call the ClearCustRibbon sub in the Before_Close Event of the ThisWorkbook code file.

How does true/false work in PHP?

The best operator for strict checking is

if($foo === true){}

That way, you're really checking if its true, and not 1 or simply just set.

Rails: Missing host to link to! Please provide :host parameter or set default_url_options[:host]

You can set default url options in the Application Controller:

class ApplicationController < ActionController::Base
  def default_url_options
    {:locale => I18n.locale}
  end
end

http://guides.rubyonrails.org/action_controller_overview.html#default_url_options

Vue 2 - Mutating props vue-warn

You should not change the props's value in child component. If you really need to change it you can use .sync. Just like this

<your-component :list.sync="list"></your-component>

Vue.component('task', {
    template: '#task-template',
    props: ['list'],
    created() {
        this.$emit('update:list', JSON.parse(this.list))
    }
});
new Vue({
    el: '.container'
})

Is there a free GUI management tool for Oracle Database Express?

Try odbTools at http://odbtools.software.informer.com - it is free.

odbTools is set of integrated GUI tools to manage, administer, monitor and tune the Oracle database.

Python Unicode Encode Error

A better solution:

if type(value) == str:
    # Ignore errors even if the string is not proper UTF-8 or has
    # broken marker bytes.
    # Python built-in function unicode() can do this.
    value = unicode(value, "utf-8", errors="ignore")
else:
    # Assume the value object has proper __unicode__() method
    value = unicode(value)

If you would like to read more about why:

http://docs.plone.org/manage/troubleshooting/unicode.html#id1

Dealing with HTTP content in HTTPS pages

Sometimes like in facebook apps we can not have non-secure contents in secure page. also we can not make local those contents. for example an app which will load in iFrame is not a simple content and we can not make it local.

I think we should never load http contents in https, also we should not fallback https page to http version to prevent error dialog.

the only way which will ensure user's security is to use https version of all contents, http://web.archive.org/web/20120502131549/http://developers.facebook.com/blog/post/499/

"unrecognized import path" with go get

I had the same issue after having upgraded go1.2 to go1.4.

I renamed src to _src in my GOPATH then did a go get -v

It worked then I deleted _src.

Hope it helps.

How to set background image of a view?

simple way :

   -(void) viewDidLoad {
   self.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage       imageNamed:@"background.png"]];
    [super viewDidLoad];
    }

Android - shadow on text?

Draw 2 texts: one gray (it will be the shadow) and on top of it draw the second text (y coordinate 1px more then shadow text).

Select a random sample of results from a query result

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

if variable contains

You can use a regex:

if (/ST1/i.test(code))

How to create byte array from HttpPostedFile

Use a BinaryReader object to return a byte array from the stream like:

byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
    fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}

Download a file from NodeJS Server using Express

There are several ways to do it This is the better way

res.download('/report-12345.pdf')

or in your case this might be

app.get('/download', function(req, res){
  const file = `${__dirname}/upload-folder/dramaticpenguin.MOV`;
  res.download(file); // Set disposition and send it.
});

Know More

What is the difference between SessionState and ViewState?

Session State contains information that is pertaining to a specific session (by a particular client/browser/machine) with the server. It's a way to track what the user is doing on the site.. across multiple pages...amid the statelessness of the Web. e.g. the contents of a particular user's shopping cart is session data. Cookies can be used for session state.
View State on the other hand is information specific to particular web page. It is stored in a hidden field so that it isn't visible to the user. It is used to maintain the user's illusion that the page remembers what he did on it the last time - dont give him a clean page every time he posts back. Check this page for more.

How to get a string after a specific substring?

s1 = "hello python world , i'm a beginner "
s2 = "world"

print s1[s1.index(s2) + len(s2):]

If you want to deal with the case where s2 is not present in s1, then use s1.find(s2) as opposed to index. If the return value of that call is -1, then s2 is not in s1.

JPA: how do I persist a String into a database field, type MYSQL Text

for mysql 'text':

@Column(columnDefinition = "TEXT")
private String description;

for mysql 'longtext':

@Lob
private String description;

Virtual member call in a constructor

Another interesting thing I found is that the ReSharper error can be 'satisfied' by doing something like below which is dumb to me. However, as mentioned by many earlier, it still is not a good idea to call virtual properties/methods in constructor.

public class ConfigManager
{
   public virtual int MyPropOne { get; private set; }
   public virtual string MyPropTwo { get; private set; }

   public ConfigManager()
   {
    Setup();
   }

   private void Setup()
   {
    MyPropOne = 1;
    MyPropTwo = "test";
   }
}

Google Text-To-Speech API

You can download the Voice using Wget:D

wget -q -U Mozilla "http://translate.google.com/translate_tts?tl=en&q=Hello"

Save the output into a mp3 file:

wget -q -U Mozilla "http://translate.google.com/translate_tts?tl=en&q=Hello" -O hello.mp3

Enjoy !!

Modulo operator in Python

Same thing you'd expect from normal modulo .. e.g. 7 % 4 = 3, 7.3 % 4.0 = 3.3

Beware of floating point accuracy issues.

How to change column order in a table using sql query in sql server 2005?

This is similar to the question on ordering the records in the result of a query .. and typically no one likes the formally correct answer ;-)

So here it goes:

  • as per SQL standard, the columns in a table are not "ordered"
  • as a result, a select * does not force the columns to be returned in a particular order
  • typically, each RDBMS has a kind of "default" order (usually the order that the columns were added to the table, either in the create table' or in thealter table add ` statements
  • therefore, if you rely on the order of columns (because you are using the results of a query to poulate some other datastructure from the position of the columns), explicitly list the columns in the order you want them.

How to import module when module name has a '-' dash or hyphen in it?

If you can't rename the module to match Python naming conventions, create a new module to act as an intermediary:

 ---- foo_proxy.py ----
 tmp = __import__('foo-bar')
 globals().update(vars(tmp))

 ---- main.py ----
 from foo_proxy import * 

Checking character length in ruby

Verification, do not forget the to_s

 def nottolonng?(value)
   if value.to_s.length <=8
     return true
   else
     return false
   end
  end

How to generate random number in Bash?

Random branching of a program or yes/no; 1/0; true/false output:

if [ $RANDOM -gt 16383  ]; then              # 16383 = 32767/2 
    echo var=true/1/yes/go_hither
else 
    echo var=false/0/no/go_thither
fi

of if you lazy to remember 16383:

if (( RANDOM % 2 )); then 
    echo "yes"
else 
    echo "no"
fi

SQL ORDER BY multiple columns

yes,the sorting proceed differently. in first scenario, orders based on column1 and in addition to that process further by sorting colmun2 based on column1 .. in second scenario ,it orders completely based on column 1 only... please proceed with a simple example...u will get quickly..

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

Removing the JUnit library, and then adding it again fixed this issue for me.

Difference between database and schema

A database is the main container, it contains the data and log files, and all the schemas within it. You always back up a database, it is a discrete unit on its own.

Schemas are like folders within a database, and are mainly used to group logical objects together, which leads to ease of setting permissions by schema.

EDIT for additional question

drop schema test1

Msg 3729, Level 16, State 1, Line 1
Cannot drop schema 'test1' because it is being referenced by object 'copyme'.

You cannot drop a schema when it is in use. You have to first remove all objects from the schema.

Related reading:

  1. What good are SQL Server schemas?
  2. MSDN: User-Schema Separation

Get product id and product type in magento?

This worked for me-

if(Mage::registry('current_product')->getTypeId() == 'simple' ) {

Use getTypeId()

How do I import a specific version of a package using go get?

That worked for me

GO111MODULE=on go get -u github.com/segmentio/[email protected]

How do I run a program with commandline arguments using GDB within a Bash script?

gdb has --init-command <somefile> where somefile has a list of gdb commands to run, I use this to have //GDB comments in my code, then `

echo "file ./a.out" > run
grep -nrIH "//GDB"|
    sed "s/\(^[^:]\+:[^:]\+\):.*$/\1/g" |
    awk '{print "b" " " $1}'|
    grep -v $(echo $0|sed "s/.*\///g") >> run
gdb --init-command ./run -ex=r

as a script, which puts the command to load the debug symbols, and then generates a list of break commands to put a break point for each //GDB comment, and starts it running

OS X Framework Library not loaded: 'Image not found'

There should be a 'Run Script' into 'Build Phases' with this: '/usr/local/bin/carthage copy-frameworks'

On the 'Input Files' of that 'Run Script', you should add the path to your libraries. Like this:

Build Phases Run Script

File input 'accept' attribute - is it useful?

It is supported by Chrome. It's not supposed to be used for validation, but for type hinting the OS. If you have an accept="image/jpeg" attribute in a file upload the OS can only show files of the suggested type.

What is process.env.PORT in Node.js?

In many environments (e.g. Heroku), and as a convention, you can set the environment variable PORT to tell your web server what port to listen on.

So process.env.PORT || 3000 means: whatever is in the environment variable PORT, or 3000 if there's nothing there.

So you pass that to app.listen, or to app.set('port', ...), and that makes your server able to accept a "what port to listen on" parameter from the environment.

If you pass 3000 hard-coded to app.listen(), you're always listening on port 3000, which might be just for you, or not, depending on your requirements and the requirements of the environment in which you're running your server.

How schedule build in Jenkins?

Try this for 4 PM from Monday to Sunday

0 16 * * *

You can check the description messgage displayed while you configuring in "Build periodically' under Jenkins. (Refer the screenshot given below)

"Would last have run at Sunday, November 17, 2019 4:00:05 PM IST; would next run at Monday, November 18, 2019 4:00:05 PM IST."

Screenshot

enter image description here

The seconds in the time " Monday, November 18, 2019 4:00:05 PM IST" refers to our current system seconds.

Getting full URL of action in ASP.NET MVC

I was having an issue with this, my server was running behind a load balancer. The load balancer was terminating the SSL/TLS connection. It then passed the request to the web servers using http.

Using the Url.Action() method with Request.Url.Schema, it kept creating a http url, in my case to create a link in an automated email (which my PenTester didn't like).

I may have cheated a little, but it is exactly what I needed to force a https url:

<a href="@Url.Action("Action", "Controller", new { id = Model.Id }, "https")">Click Here</a>

I actually use a web.config AppSetting so I can use http when debugging locally, but all test and prod environments use transformation to set the https value.

LINK : fatal error LNK1561: entry point must be defined ERROR IN VC++

You can get this error if you define a project as an .exe but intent to create a .lib or a .dll

How To Include CSS and jQuery in my WordPress plugin?

See http://codex.wordpress.org/Function_Reference/wp_enqueue_script

Example

<?php
function my_init_method() {
    wp_deregister_script( 'jquery' );
    wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js');
}    

add_action('init', 'my_init_method');
?> 

Hide keyboard in react-native

const dismissKeyboard = require('dismissKeyboard');
dismissKeyboard(); //dismisses it

Approach No# 2;

Thanks to user @ricardo-stuven for pointing this out, there is another better way to dismiss the keyboard which you can see in the example in the react native docs.

Simple import Keyboard and call it's method dismiss()

How to add onload event to a div element

You can trigger some js automatically on an IMG element using onerror, and no src.

<img src onerror='alert()'>

Target a css class inside another css class

Not certain what the HTML looks like (that would help with answers). If it's

<div class="testimonials content">stuff</div>

then simply remove the space in your css. A la...

.testimonials.content { css here }

UPDATE:

Okay, after seeing HTML see if this works...

.testimonials .wrapper .content { css here }

or just

.testimonials .wrapper { css here }

or

.desc-container .wrapper { css here }

all 3 should work.

Put quotes around a variable string in JavaScript

var text = "\"http://example.com\""; 

Whatever your text, to wrap it with ", you need to put them and escape inner ones with \. Above will result in:

"http://example.com"

AttributeError: 'module' object has no attribute 'urlretrieve'

A Python 2+3 compatible solution is:

import sys

if sys.version_info[0] >= 3:
    from urllib.request import urlretrieve
else:
    # Not Python 3 - today, it is most likely to be Python 2
    # But note that this might need an update when Python 4
    # might be around one day
    from urllib import urlretrieve

# Get file from URL like this:
urlretrieve("http://www-scf.usc.edu/~chiso/oldspice/m-b1-hello.mp3")

Producer/Consumer threads using a Queue

This is a very simple code.

import java.util.*;

// @author : rootTraveller, June 2017

class ProducerConsumer {
    public static void main(String[] args) throws Exception {
        Queue<Integer> queue = new LinkedList<>();
        Integer buffer = new Integer(10);  //Important buffer or queue size, change as per need.

        Producer producerThread = new Producer(queue, buffer, "PRODUCER");
        Consumer consumerThread = new Consumer(queue, buffer, "CONSUMER");

        producerThread.start();  
        consumerThread.start();
    }   
}

class Producer extends Thread {
    private Queue<Integer> queue;
    private int queueSize ;

    public Producer (Queue<Integer> queueIn, int queueSizeIn, String ThreadName){
        super(ThreadName);
        this.queue = queueIn;
        this.queueSize = queueSizeIn;
    }

    public void run() {
        while(true){
            synchronized (queue) {
                while(queue.size() == queueSize){
                    System.out.println(Thread.currentThread().getName() + " FULL         : waiting...\n");
                    try{
                        queue.wait();   //Important
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }

                //queue empty then produce one, add and notify  
                int randomInt = new Random().nextInt(); 
                System.out.println(Thread.currentThread().getName() + " producing... : " + randomInt); 
                queue.add(randomInt); 
                queue.notifyAll();  //Important
            } //synchronized ends here : NOTE
        }
    }
}

class Consumer extends Thread {
    private Queue<Integer> queue;
    private int queueSize;

    public Consumer(Queue<Integer> queueIn, int queueSizeIn, String ThreadName){
        super (ThreadName);
        this.queue = queueIn;
        this.queueSize = queueSizeIn;
    }

    public void run() {
        while(true){
            synchronized (queue) {
                while(queue.isEmpty()){
                    System.out.println(Thread.currentThread().getName() + " Empty        : waiting...\n");
                    try {
                        queue.wait();  //Important
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }

                //queue not empty then consume one and notify
                System.out.println(Thread.currentThread().getName() + " consuming... : " + queue.remove());
                queue.notifyAll();
            } //synchronized ends here : NOTE
        }
    }
}

How to draw a rounded Rectangle on HTML Canvas?

try to add this line , when you want to get rounded corners : ctx.lineCap = "round";

Saving and Reading Bitmaps/Images from Internal memory in Android

/**
 * Created by Ilya Gazman on 3/6/2016.
 */
public class ImageSaver {

    private String directoryName = "images";
    private String fileName = "image.png";
    private Context context;
    private boolean external;

    public ImageSaver(Context context) {
        this.context = context;
    }

    public ImageSaver setFileName(String fileName) {
        this.fileName = fileName;
        return this;
    }

    public ImageSaver setExternal(boolean external) {
        this.external = external;
        return this;
    }

    public ImageSaver setDirectoryName(String directoryName) {
        this.directoryName = directoryName;
        return this;
    }

    public void save(Bitmap bitmapImage) {
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(createFile());
            bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @NonNull
    private File createFile() {
        File directory;
        if(external){
            directory = getAlbumStorageDir(directoryName);
        }
        else {
            directory = context.getDir(directoryName, Context.MODE_PRIVATE);
        }
        if(!directory.exists() && !directory.mkdirs()){
            Log.e("ImageSaver","Error creating directory " + directory);
        }

        return new File(directory, fileName);
    }

    private File getAlbumStorageDir(String albumName) {
        return new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), albumName);
    }

    public static boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state);
    }

    public static boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state) ||
                Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
    }

    public Bitmap load() {
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(createFile());
            return BitmapFactory.decodeStream(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

Usage

  • To save:

    new ImageSaver(context).
            setFileName("myImage.png").
            setDirectoryName("images").
            save(bitmap);
    
  • To load:

    Bitmap bitmap = new ImageSaver(context).
            setFileName("myImage.png").
            setDirectoryName("images").
            load();
    

Edit:

Added ImageSaver.setExternal(boolean) to support saving to external storage based on googles example.

Why does modern Perl avoid UTF-8 by default?

I think you misunderstand Unicode and its relationship to Perl. No matter which way you store data, Unicode, ISO-8859-1, or many other things, your program has to know how to interpret the bytes it gets as input (decoding) and how to represent the information it wants to output (encoding). Get that interpretation wrong and you garble the data. There isn't some magic default setup inside your program that's going to tell the stuff outside your program how to act.

You think it's hard, most likely, because you are used to everything being ASCII. Everything you should have been thinking about was simply ignored by the programming language and all of the things it had to interact with. If everything used nothing but UTF-8 and you had no choice, then UTF-8 would be just as easy. But not everything does use UTF-8. For instance, you don't want your input handle to think that it's getting UTF-8 octets unless it actually is, and you don't want your output handles to be UTF-8 if the thing reading from them can't handle UTF-8. Perl has no way to know those things. That's why you are the programmer.

I don't think Unicode in Perl 5 is too complicated. I think it's scary and people avoid it. There's a difference. To that end, I've put Unicode in Learning Perl, 6th Edition, and there's a lot of Unicode stuff in Effective Perl Programming. You have to spend the time to learn and understand Unicode and how it works. You're not going to be able to use it effectively otherwise.

What does it mean "No Launcher activity found!"

Like Gusdor said above, "Multiple action tags in a single intent-filter tag will also cause the same error." (Give him the credit! I could just kiss Gusdor for this!)
I didn't find any docs for this fact! I had added a new (USB) action and being clever, I lumped it in the same intent-filter. And it broke the launch. Like Gusdor said, one intent filter, one action! Apparently each action should go in its own intent filter.
It should look like this...

<intent-filter>
  <action android:name="android.intent.action.MAIN" />
  <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
  <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>

When I did this, WAZOO! it worked!

Install .ipa to iPad with or without iTunes

If your using the latest version of Itunes and there is no APP section Click on summary while the device is connected to you PC . Then Drag and drop the file onto the "on my device" section.

-see picture for illustrationIllustration

warning: assignment makes integer from pointer without a cast

The warning comes from the fact that you're dereferencing src in the assignment. The expression *src has type char, which is an integral type. The expression "anotherstring" has type char [14], which in this particular context is implicitly converted to type char *, and its value is the address of the first character in the array. So, you wind up trying to assign a pointer value to an integral type, hence the warning. Drop the * from *src, and it should work as expected:

src = "anotherstring";

since the type of src is char *.

Flutter: Run method on Widget build complete

If you are looking for ReactNative's componentDidMount equivalent, Flutter has it. It's not that simple but it's working just the same way. In Flutter, Widgets do not handle their events directly. Instead they use their State object to do that.

class MyWidget extends StatefulWidget{

  @override
  State<StatefulWidget> createState() => MyState(this);

  Widget build(BuildContext context){...} //build layout here

  void onLoad(BuildContext context){...} //callback when layout build done
}

class MyState extends State<MyWidget>{

  MyWidget widget;

  MyState(this.widget);

  @override
  Widget build(BuildContext context) => widget.build(context);

  @override
  void initState() => widget.onLoad(context);
}

State.initState immediately will be called once upon screen has finishes rendering the layout. And will never again be called even on hot reload if you're in debug mode, until explicitly reaches time to do so.

Changing datagridview cell color dynamically

If you want every cell in the grid to have the same background color, you can just do this:

dataGridView1.DefaultCellStyle.BackColor = Color.Green;

Difference between 2 dates in SQLite

Difference In Days

Select Cast ((
    JulianDay(ToDate) - JulianDay(FromDate)
) As Integer)

Difference In Hours

Select Cast ((
    JulianDay(ToDate) - JulianDay(FromDate)
) * 24 As Integer)

Difference In Minutes

Select Cast ((
    JulianDay(ToDate) - JulianDay(FromDate)
) * 24 * 60 As Integer)

Difference In Seconds

Select Cast ((
    JulianDay(ToDate) - JulianDay(FromDate)
) * 24 * 60 * 60 As Integer)

Bootstrap: wider input field

There is also a smaller one yet called "input-mini".

Java, return if trimmed String in List contains String

You need to iterate your list and call String#trim for searching:

String search = "A";
for(String str: myList) {
    if(str.trim().contains(search))
       return true;
}
return false;

OR if you want to perform ignore case search, then use:

search = search.toLowerCase(); // outside loop

// inside the loop
if(str.trim().toLowerCase().contains(search))

Create html documentation for C# code

This page might interest you: http://msdn.microsoft.com/en-us/magazine/dd722812.aspx

You can generate the XML documentation file using either the command-line compiler or through the Visual Studio interface. If you are compiling with the command-line compiler, use options /doc or /doc+. That will generate an XML file by the same name and in the same path as the assembly. To specify a different file name, use /doc:file.

If you are using the Visual Studio interface, there's a setting that controls whether the XML documentation file is generated. To set it, double-click My Project in Solution Explorer to open the Project Designer. Navigate to the Compile tab. Find "Generate XML documentation file" at the bottom of the window, and make sure it is checked. By default this setting is on. It generates an XML file using the same name and path as the assembly.

Using --add-host or extra_hosts with docker-compose

Basic docker-compose.yml with extra hosts:

version: '3'
services:
api:
    build: .
    ports:
        - "5003:5003"
    extra_hosts:
        - "your-host.name.com:162.242.195.82" #host and ip
        - "your-host--1.name.com your-host--2.name.com:50.31.209.229" #multiple hostnames with same ip
        

The content in the /etc/hosts file in the created container:

162.242.195.82  your-host.name.com
50.31.209.229   your-host--1.name.com your-host--2.name.com

You can check the /etc/hosts file with the following commands:

$ docker-compose -f path/to/file/docker-compose.yml run api bash  # 'api' is service name
#then inside container bash
root@f7c436910676:/app# cat /etc/hosts

How to retrieve Key Alias and Key Password for signed APK in android studio(migrated from Eclipse)

If you happen to be on MacOS and checked the "save password" box in Android Studio, you can recover the password from Keychain Access.

  1. Launch Keychain Access from Applications/Utilities.
  2. Select password in Category, on the left panel.
  3. On the search box top right, type your Android app name or part of the app name.
  4. You will see the result line, if you had saved the password.
  5. Double click on it, check the show password checkbox, give your system password when asked, and it will show your keystore password.

Leap year calculation

I found this problem in the book "Illustrated Guide to Python 3". It was in a very early chapter that only discussed the math operations, no loops, no comparisons, no conditionals. How can you tell if a given year is a leap year?

Below is what I came up with:

y = y % 400
a = y % 4
b = y % 100
c = y // 100
ly = (0**a) * ((1-(0**b)) + 0**c)   # ly is not zero for leap years, else 0

Delete the 'first' record from a table in SQL Server, without a WHERE condition

SQL-92:

DELETE Field FROM Table WHERE Field IN (SELECT TOP 1 Field FROM Table ORDER BY Field DESC)

When would you use the Builder Pattern?

Consider a restaurant. The creation of "today's meal" is a factory pattern, because you tell the kitchen "get me today's meal" and the kitchen (factory) decides what object to generate, based on hidden criteria.

The builder appears if you order a custom pizza. In this case, the waiter tells the chef (builder) "I need a pizza; add cheese, onions and bacon to it!" Thus, the builder exposes the attributes the generated object should have, but hides how to set them.

How to call function of one php file from another php file and pass parameters to it?

you can write the function in a separate file (say common-functions.php) and include it wherever needed.

function getEmployeeFullName($employeeId) {
// Write code to return full name based on $employeeId
}

You can include common-functions.php in another file as below.

include('common-functions.php');
echo 'Name of first employee is ' . getEmployeeFullName(1);

You can include any number of files to another file. But including comes with a little performance cost. Therefore include only the files which are really required.

What does the "@" symbol do in SQL?

@ is used as a prefix denoting stored procedure and function parameter names, and also variable names

Hidden Features of C#?

You can store colors in Enum.

public enum MyEnumColors : uint
{
    Normal          = 0xFF9F9F9F,
    Active          = 0xFF8EA98A,
    Error           = 0xFFFF0000
}

Facebook database design?

It's not possible to retrieve data from RDBMS for user friends data for data which cross more than half a billion at a constant time so Facebook implemented this using a hash database (no SQL) and they opensourced the database called Cassandra.

So every user has its own key and the friends details in a queue; to know how cassandra works look at this:

http://prasath.posterous.com/cassandra-55

Java code To convert byte to Hexadecimal

I am posting because none of the existing answers explain why their approaches work, which I think is really important for this problem. In some cases, this causes the proposed solution to appear unnecessarily complicated and subtle. To illustrate I will provide a fairly straightforward approach, but I'll provide a bit more detail to help illustrate why it works.

First off, what are we trying to do? We want to convert a byte value (or an array of bytes) to a string which represents a hexadecimal value in ASCII. So step one is to find out exactly what a byte in Java is:

The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.

What does this mean? A few things: First and most importantly, it means we are working with 8-bits. So for example we can write the number 2 as 0000 0010. However, since it is two's complement, we write a negative 2 like this: 1111 1110. What is also means is that converting to hex is very straightforward. That is, you simply convert each 4 bit segment directly to hex. Note that to make sense of negative numbers in this scheme you will first need to understand two's complement. If you don't already understand two's complement, you can read an excellent explanation, here: http://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html


Converting Two's Complement to Hex In General

Once a number is in two's complement it is dead simple to convert it to hex. In general, converting from binary to hex is very straightforward, and as you will see in the next two examples, you can go directly from two's complement to hex.

Examples

Example 1: Convert 2 to Hex.

1) First convert 2 to binary in two's complement:

2 (base 10) = 0000 0010 (base 2)

2) Now convert binary to hex:

0000 = 0x0 in hex
0010 = 0x2 in hex

therefore 2 = 0000 0010 = 0x02. 

Example 2: Convert -2 (in two's complement) to Hex.

1) First convert -2 to binary in two's complement:

-2 (base 10) = 0000 0010 (direct conversion to binary) 
               1111 1101 (invert bits)
               1111 1110 (add 1)
therefore: -2 = 1111 1110 (in two's complement)

2) Now Convert to Hex:

1111 = 0xF in hex
1110 = 0xE in hex

therefore: -2 = 1111 1110 = 0xFE.


Doing this In Java

Now that we've covered the concept, you'll find we can achieve what we want with some simple masking and shifting. The key thing to understand is that the byte you are trying to convert is already in two's complement. You don't do this conversion yourself. I think this is a major point of confusion on this issue. Take for example the follow byte array:

byte[] bytes = new byte[]{-2,2};

We just manually converted them to hex, above, but how can we do it in Java? Here's how:

Step 1: Create a StringBuffer to hold our computation.

StringBuffer buffer = new StringBuffer();

Step 2: Isolate the higher order bits, convert them to hex, and append them to the buffer

Given the binary number 1111 1110, we can isolate the higher order bits by first shifting them over by 4, and then zeroing out the rest of the number. Logically this is simple, however, the implementation details in Java (and many languages) introduce a wrinkle because of sign extension. Essentially, when you shift a byte value, Java first converts your value to an integer, and then performs sign extension. So while you would expect 1111 1110 >> 4 to be 0000 1111, in reality, in Java it is represented as the two's complement 0xFFFFFFFF!

So returning to our example:

1111 1110 >> 4 (shift right 4) = 1111 1111 1111 1111 1111 1111 1111 1111 (32 bit sign-extended number in two's complement)

We can then isolate the bits with a mask:

1111 1111 1111 1111 1111 1111 1111 1111 & 0xF = 0000 0000 0000 0000 0000 0000 0000 1111
therefore: 1111 = 0xF in hex. 

In Java we can do this all in one shot:

Character.forDigit((bytes[0] >> 4) & 0xF, 16);

The forDigit function just maps the number you pass it onto the set of hexadecimal numbers 0-F.

Step 3: Next we need to isolate the lower order bits. Since the bits we want are already in the correct position, we can just mask them out:

1111 1110 & 0xF = 0000 0000 0000 0000 0000 0000 0000 1110 (recall sign extension from before)
therefore: 1110 = 0xE in hex.  

Like before, in Java we can do this all in one shot:

Character.forDigit((bytes[0] & 0xF), 16);

Putting this all together we can do it as a for loop and convert the entire array:

for(int i=0; i < bytes.length; i++){
    buffer.append(Character.forDigit((bytes[i] >> 4) & 0xF, 16));
    buffer.append(Character.forDigit((bytes[i] & 0xF), 16));
}

Hopefully this explanation makes things clearer for those of you wondering exactly what is going on in the many examples you will find on the internet. Hopefully I didn't make any egregious errors, but suggestions and corrections are highly welcome!

URL for public Amazon S3 bucket

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


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


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

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

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

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

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

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

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

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


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

Delete all rows in a table based on another table

This is old I know, but just a pointer to anyone using this ass a reference. I have just tried this and if you are using Oracle, JOIN does not work in DELETE statements. You get a the following message:

ORA-00933: SQL command not properly ended.

How should I call 3 functions in order to execute them one after the other?

If method 1 has to be executed after method 2, 3, 4. The following code snippet can be the solution for this using Deferred object in JavaScript.

_x000D_
_x000D_
function method1(){_x000D_
  var dfd = new $.Deferred();_x000D_
     setTimeout(function(){_x000D_
     console.log("Inside Method - 1"); _x000D_
     method2(dfd);  _x000D_
    }, 5000);_x000D_
  return dfd.promise();_x000D_
}_x000D_
_x000D_
function method2(dfd){_x000D_
  setTimeout(function(){_x000D_
   console.log("Inside Method - 2"); _x000D_
   method3(dfd); _x000D_
  }, 3000);_x000D_
}_x000D_
_x000D_
function method3(dfd){_x000D_
  setTimeout(function(){_x000D_
   console.log("Inside Method - 3");  _x000D_
   dfd.resolve();_x000D_
  }, 3000);_x000D_
}_x000D_
_x000D_
function method4(){   _x000D_
   console.log("Inside Method - 4");  _x000D_
}_x000D_
_x000D_
var call = method1();_x000D_
_x000D_
$.when(call).then(function(cb){_x000D_
  method4();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

List of Java class file format major version numbers?

If you have a class file at build/com/foo/Hello.class, you can check what java version it is compiled at using the command:

javap -v build/com/foo/Hello.class | grep "major"

Example usage:

$ javap -v build/classes/java/main/org/aguibert/liberty/Book.class | grep major
  major version: 57

According to the table in the OP, major version 57 means the class file was compiled to JDK 13 bytecode level

Stacking DIVs on top of each other?

To add to Dave's answer:

div { position: relative; }
div div { position: absolute; top: 0; left: 0; }

Reactjs - Form input validation

Try this, example, the required property in below input tag will ensure that the name field should be submitted empty.

<input type="text" placeholder="Your Name" required />

Cannot resolve symbol HttpGet,HttpClient,HttpResponce in Android Studio

Google officially suggests to developers to use Volley library for networking related stuff Here, so Its time to switch to Volley, Happy coding

Using atan2 to find angle between two vectors

I think a better formula was posted here: http://www.mathworks.com/matlabcentral/answers/16243-angle-between-two-vectors-in-3d

angle = atan2(norm(cross(a,b)), dot(a,b))

So this formula works in 2 or 3 dimensions. For 2 dimensions this formula simplifies to the one stated above.

How do I join two lists in Java?

I can't improve on the two-liner in the general case without introducing your own utility method, but if you do have lists of Strings and you're willing to assume those Strings don't contain commas, you can pull this long one-liner:

List<String> newList = new ArrayList<String>(Arrays.asList((listOne.toString().subString(1, listOne.length() - 1) + ", " + listTwo.toString().subString(1, listTwo.length() - 1)).split(", ")));

If you drop the generics, this should be JDK 1.4 compliant (though I haven't tested that). Also not recommended for production code ;-)

Add to integers in a list

Here is an example where the things to add come from a dictionary

>>> L = [0, 0, 0, 0]
>>> things_to_add = ({'idx':1, 'amount': 1}, {'idx': 2, 'amount': 1})
>>> for item in things_to_add:
...     L[item['idx']] += item['amount']
... 
>>> L
[0, 1, 1, 0]

Here is an example adding elements from another list

>>> L = [0, 0, 0, 0]
>>> things_to_add = [0, 1, 1, 0]
>>> for idx, amount in enumerate(things_to_add):
...     L[idx] += amount
... 
>>> L
[0, 1, 1, 0]

You could also achieve the above with a list comprehension and zip

L[:] = [sum(i) for i in zip(L, things_to_add)]

Here is an example adding from a list of tuples

>>> things_to_add = [(1, 1), (2, 1)]
>>> for idx, amount in things_to_add:
...     L[idx] += amount
... 
>>> L
[0, 1, 1, 0]

How to convert JSON to string?

Try to Use JSON.stringify

Regards