Programs & Examples On #Wwsapi

0

Disabling browser print options (headers, footers, margins) from page?

Since you mentioned "within their browser" and firefox, if you are using Internet Explorer, you can disable the page header/footer by temporarily setting of the value in the registry, see here for an example. AFAIK I have not heard of a way to do this within other browsers. Both Daniel's and Mickel's answers seems to collide with each other, I guess that there could be a similar setting somewhere in the registry for firefox to remove headers/footers or customize them. Have you checked it out?

Can an interface extend multiple interfaces in Java?

You can extend multiple Interfaces but you cannot extend multiple classes.

The reason that it is not possible in Java to extending multiple classes, is the bad experience from C++ where this is possible.

The alternative for multipe inheritance is that a class can implement multiple interfaces (or an Interface can extend multiple Interfaces)

Animate an element's width from 0 to 100%, with it and it's wrapper being only as wide as they need to be, without a pre-set width, in CSS3 or jQuery

Got it to work by transitioning the padding as well as the width.

JSFiddle: http://jsfiddle.net/tuybk748/1/

<div class='label gray'>+
</div><!-- must be connected to prevent gap --><div class='contents-wrapper'>
    <div class="gray contents">These are the contents of this div</div>
</div>
.gray {
    background: #ddd;
}
.contents-wrapper, .label, .contents {
    display: inline-block;
}
.label, .contents {
    overflow: hidden; /* must be on both divs to prevent dropdown behavior */
    height: 20px;
}
.label {
    padding: 10px 10px 15px;
}
.contents {
    padding: 10px 0px 15px; /* no left-right padding at beginning */
    white-space: nowrap; /* keeps text all on same line */
    width: 0%;
    -webkit-transition: width 1s ease-in-out, padding-left 1s ease-in-out, 
        padding-right 1s ease-in-out;
    -moz-transition: width 1s ease-in-out, padding-left 1s ease-in-out, 
        padding-right 1s ease-in-out;
    -o-transition: width 1s ease-in-out, padding-left 1s ease-in-out, 
        padding-right 1s ease-in-out;
    transition: width 1s ease-in-out, padding-left 1s ease-in-out, 
        padding-right 1s ease-in-out;
}
.label:hover + .contents-wrapper .contents {
    width: 100%;
    padding-left: 10px;
    padding-right: 10px;
}

'adb' is not recognized as an internal or external command, operable program or batch file

I recommand you using PowerShell

Set Android Studio Terminal to PowerShell:

Settings > Tools > Terminal > Shell path = pwsh.exe (instead of cmd.exe)

Open Terminal on Android Studio

PowerShell 7.0.1
Copyright (c) Microsoft Corporation. All rights reserved.

https://aka.ms/powershell
Type 'help' to get help.

PS >

Test the path for adb.exe

# `pikachu` should be replace your username
PS > test-path "C:\Users\pikachu\AppData\Local\Android\sdk\platform-tools"
True

Open your powershell profile file in your text editor

PS > notepad $profile

add below line, save and exit

# `pikachu` should be replaced with your username
$env:PATH+="C:\Users\pikachu\AppData\Local\Android\sdk\platform-tools"

re-open Terminal and try adb

PS > adb
Android Debug Bridge version 1.0.41
Version 30.0.1-6435776
Installed as C:\Users\hdformat\AppData\Local\Android\sdk\platform-tools\adb.exe

global options:
 -a         listen on all network interfaces, not just localhost
 -d         use USB device (error if multiple devices connected)
 -e         use TCP/IP device (error if multiple TCP/IP devices available)
 -s SERIAL  use device with given serial (overrides $ANDROID_SERIAL)
 -t ID      use device with given transport id
 -H         name of adb server host [default=localhost]
 -P         port of adb server [default=5037]

How to store arbitrary data for some HTML tags

As a jQuery user I would use the Metadata plugin. The HTML looks clean, it validates, and you can embed anything that can be described using JSON notation.

Convert blob to base64

async function blobToBase64(blob) {
  return new Promise((resolve, _) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result);
    reader.readAsDataURL(blob);
  });
}

let blob = null; // <= your blob object goes here

blobToBase64(blob)
  .then(base64String => console.log(base64String));

See also:

CSS - make div's inherit a height

You need to take out a float: left; property... because when you use float the parent div do not grub the height of it's children... If you want the parent dive to get the children height you need to give to the parent div a css property overflow:hidden; But to solve your problem you can use display: table-cell; instead of float... it will automatically scale the div height to its parent height...

AngularJS : The correct way of binding to a service properties

Late to the party, but for future Googlers - don't use the provided answer.

JavaScript has a mechanism of passing objects by reference, while it only passes a shallow copy for values "numbers, strings etc".

In above example, instead of binding attributes of a service, why don't we expose the service to the scope?

$scope.hello = HelloService;

This simple approach will make angular able to do two-way binding and all the magical things you need. Don't hack your controller with watchers or unneeded markup.

And if you are worried about your view accidentally overwriting your service attributes, use defineProperty to make it readable, enumerable, configurable, or define getters and setters. You can gain lots of control by making your service more solid.

Final tip: if you spend your time working on your controller more than your services then you are doing it wrong :(.

In that particular demo code you supplied I would recommend you do:

 function TimerCtrl1($scope, Timer) {
   $scope.timer = Timer;
 }
///Inside view
{{ timer.time_updated }}
{{ timer.other_property }}
etc...

Edit:

As I mentioned above, you can control the behaviour of your service attributes using defineProperty

Example:

// Lets expose a property named "propertyWithSetter" on our service
// and hook a setter function that automatically saves new value to db !
Object.defineProperty(self, 'propertyWithSetter', {
  get: function() { return self.data.variable; },
  set: function(newValue) { 
         self.data.variable = newValue; 
         // let's update the database too to reflect changes in data-model !
         self.updateDatabaseWithNewData(data);
       },
  enumerable: true,
  configurable: true
});

Now in our controller if we do

$scope.hello = HelloService;
$scope.hello.propertyWithSetter = 'NEW VALUE';

our service will change the value of propertyWithSetter and also post the new value to database somehow!

Or we can take any approach we want.

Refer to the MDN documentation for defineProperty.

How do I find which program is using port 80 in Windows?

Right click on "Command prompt" or "PowerShell", in menu click "Run as Administrator" (on Windows XP you can just run it as usual).

As Rick Vanover mentions in See what process is using a TCP port in Windows Server 2008

The following command will show what network traffic is in use at the port level:

Netstat -a -n -o

or

Netstat -a -n -o >%USERPROFILE%\ports.txt

(to open the port and process list in a text editor, where you can search for information you want)

Then,

with the PIDs listed in the netstat output, you can follow up with the Windows Task Manager (taskmgr.exe) or run a script with a specific PID that is using a port from the previous step. You can then use the "tasklist" command with the specific PID that corresponds to a port in question.

Example:

tasklist /svc /FI "PID eq 1348"

How do I link to a library with Code::Blocks?

At a guess, you used Code::Blocks to create a Console Application project. Such a project does not link in the GDI stuff, because console applications are generally not intended to do graphics, and TextOut is a graphics function. If you want to use the features of the GDI, you should create a Win32 Gui Project, which will be set up to link in the GDI for you.

Is it safe to shallow clone with --depth 1, create commits, and pull updates again?

Note that Git 1.9/2.0 (Q1 2014) has removed that limitation.
See commit 82fba2b, from Nguy?n Thái Ng?c Duy (pclouds):

Now that git supports data transfer from or to a shallow clone, these limitations are not true anymore.

The documentation now reads:

--depth <depth>::

Create a 'shallow' clone with a history truncated to the specified number of revisions.

That stems from commits like 0d7d285, f2c681c, and c29a7b8 which support clone, send-pack /receive-pack with/from shallow clones.
smart-http now supports shallow fetch/clone too.

All the details are in "shallow.c: the 8 steps to select new commits for .git/shallow".

Update June 2015: Git 2.5 will even allow for fetching a single commit!
(Ultimate shallow case)


Update January 2016: Git 2.8 (Mach 2016) now documents officially the practice of getting a minimal history.
See commit 99487cf, commit 9cfde9e (30 Dec 2015), commit 9cfde9e (30 Dec 2015), commit bac5874 (29 Dec 2015), and commit 1de2e44 (28 Dec 2015) by Stephen P. Smith (``).
(Merged by Junio C Hamano -- gitster -- in commit 7e3e80a, 20 Jan 2016)

This is "Documentation/user-manual.txt"

A <<def_shallow_clone,shallow clone>> is created by specifying the git-clone --depth switch.
The depth can later be changed with the git-fetch --depth switch, or full history restored with --unshallow.

Merging inside a <<def_shallow_clone,shallow clone>> will work as long as a merge base is in the recent history.
Otherwise, it will be like merging unrelated histories and may have to result in huge conflicts.
This limitation may make such a repository unsuitable to be used in merge based workflows.

Update 2020:

  • git 2.11.1 introduced option git fetch --shallow-exclude= to prevent fetching all history
  • git 2.11.1 introduced option git fetch --shallow-since= to prevent fetching old commits.

For more on the shallow clone update process, see "How to update a git shallow clone?".


As commented by Richard Michael:

to backfill history: git pull --unshallow

And Olle Härstedt adds in the comments:

To backfill part of the history: git fetch --depth=100.

How do I fix a Git detached head?

git pull origin master

worked for me. It was just about giving remote and branch name explicitly.

Using number_format method in Laravel

If you are using Eloquent, in your model put:

public function getPriceAttribute($price)
{
    return $this->attributes['price'] = sprintf('U$ %s', number_format($price, 2));
}

Where getPriceAttribute is your field on database. getSomethingAttribute.

What is the id( ) function used for?

If you're using python 3.4.1 then you get a different answer to your question.

list = [1,2,3]
id(list[0])
id(list[1])
id(list[2])

returns:

1705950792   
1705950808  # increased by 16   
1705950824  # increased by 16

The integers -5 to 256 have a constant id, and on finding it multiple times its id does not change, unlike all other numbers before or after it that have different id's every time you find it. The numbers from -5 to 256 have id's in increasing order and differ by 16.

The number returned by id() function is a unique id given to each item stored in memory and it is analogy wise the same as the memory location in C.

How to get index of object by its property in JavaScript?

Only way known for me is to looping through all array:

var index=-1;
for(var i=0;i<Data.length;i++)
  if(Data[i].name==="John"){index=i;break;}

or case insensitive:

var index=-1;
for(var i=0;i<Data.length;i++)
  if(Data[i].name.toLowerCase()==="john"){index=i;break;}

On result variable index contain index of object or -1 if not found.

how to convert 2d list to 2d numpy array?

Just pass the list to np.array:

a = np.array(a)

You can also take this opportunity to set the dtype if the default is not what you desire.

a = np.array(a, dtype=...)

Regular expression to match a word or its prefix

I test examples in js. Simplest solution - just add word u need inside / /:

var reg = /cat/;
reg.test('some cat here');//1 test
true // result
reg.test('acatb');//2 test
true // result

Now if u need this specific word with boundaries, not inside any other signs-letters. We use b marker:

var reg = /\bcat\b/
reg.test('acatb');//1 test 
false // result
reg.test('have cat here');//2 test
true // result

We have also exec() method in js, whichone returns object-result. It helps f.g. to get info about place/index of our word.

var matchResult = /\bcat\b/.exec("good cat good");
console.log(matchResult.index); // 5

If we need get all matched words in string/sentence/text, we can use g modifier (global match):

"cat good cat good cat".match(/\bcat\b/g).length
// 3 

Now the last one - i need not 1 specific word, but some of them. We use | sign, it means choice/or.

"bad dog bad".match(/\bcat|dog\b/g).length
// 1

Ant is using wrong java version

This is rather an old question, but I will add my notes for future references.

I had a similar issue and fixed it by changing the order of the exports in the PATH variable.

For example I was using a method of concatenating strings to my PATH by doing (this is just an example):

$> export PATH='$PATH:'$JAVA_HOME

If my variable PATH already had a java in it, the last value would be meaningless, thus the order would matter. To solve this I started inverting it by adding my variable first, then adding the PATH.

Following this idea I inverted the order that ANT_HOME was being exported. Adding JAVA_HOME before ANT_HOME.

This could be just a coincidence, but it worked for me.

Extract the maximum value within each group in a dataframe

df$Gene <- as.factor(df$Gene)
do.call(rbind, lapply(split(df,df$Gene), function(x) {return(x[which.max(x$Value),])}))

Just using base R

Jquery array.push() not working

Your code alerts the current value of the dropdown for me, showing that it has properly pushed into the array.

Are you wanting to keep old values and append? You're recreating the array each time, meaning that the old value gets clobbered.

Here's some updated code:

var myarray = [];
$("#test").click(function() {
    myarray.push($("#drop").val());
    alert(myarray);
});

jsFiddle

Grouped bar plot in ggplot

First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:

raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)

raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it

freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level

Then you need to create a data frame out of it, melt it and plot it:

Names=c("Food","Music","People")     # create list of names
data=data.frame(cbind(freq),Names)   # combine them into a data frame
data=data[,c(5,3,1,2,4)]             # sort columns

# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')

# plot everything
ggplot(data.m, aes(Names, value)) +   
  geom_bar(aes(fill = variable), position = "dodge", stat="identity")

Is this what you're after?

enter image description here

To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:

> head(df)
  ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
1  1    A  1980   450   338   154    36    13     9
2  2    A  2000   288   407   212    54    16    23
3  3    A  2020   196   434   246    68    19    36
4  4    B  1980   111   326   441    90    21    11
5  5    B  2000    63   298   443   133    42    21
6  6    B  2020    36   257   462   162    55    30

Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape and plotted.

For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw)) to get this:

> data
   Names Very.Bad Bad Good Very.Good
1   Food        7   6    5         2
2  Music        5   5    7         3
3 People        6   3    7         4

Just imagine you have Very.Bad, Bad, Good and so on instead of X1PCE, X2PCE, X3PCE. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw)).

Download history stock prices automatically from yahoo finance in python

There is already a library in Python called yahoo_finance so you'll need to download the library first using the following command line:

sudo pip install yahoo_finance

Then once you've installed the yahoo_finance library, here's a sample code that will download the data you need from Yahoo Finance:

#!/usr/bin/python
import yahoo_finance
import pandas as pd

symbol = yahoo_finance.Share("GOOG")
google_data = symbol.get_historical("1999-01-01", "2016-06-30")
google_df = pd.DataFrame(google_data)

# Output data into CSV
google_df.to_csv("/home/username/google_stock_data.csv")

This should do it. Let me know if it works.

UPDATE: The yahoo_finance library is no longer supported.

Conditional logic in AngularJS template

You could use the ngSwitch directive:

  <div ng-switch on="selection" >
    <div ng-switch-when="settings">Settings Div</div>
    <span ng-switch-when="home">Home Span</span>
    <span ng-switch-default>default</span>
  </div>

If you don't want the DOM to be loaded with empty divs, you need to create your custom directive using $http to load the (sub)templates and $compile to inject it in the DOM when a certain condition has reached.

This is just an (untested) example. It can and should be optimized:

HTML:

<conditional-template ng-model="element" template-url1="path/to/partial1" template-url2="path/to/partial2"></div>

Directive:

app.directive('conditionalTemplate', function($http, $compile) {
   return {
      restrict: 'E',
      require: '^ngModel',
      link: function(sope, element, attrs, ctrl) {
        // get template with $http
        // check model via ctrl.$viewValue
        // compile with $compile
        // replace element with element.replaceWith()
      }
   };
});

Using Mysql WHERE IN clause in codeigniter

try this:

return $this->db->query("
     SELECT * FROM myTable 
     WHERE trans_id IN ( SELECT trans_id FROM myTable WHERE code='B') 
     AND code!='B'
     ")->result_array();

Is not active record but is codeigniter's way http://codeigniter.com/user_guide/database/examples.html see Standard Query With Multiple Results (Array Version) section

Brew doctor says: "Warning: /usr/local/include isn't writable."

I have had this happen in my organization after all our users were bound to active directory (effectively changing the UID from 50x to ######).

Now it is simply a case of changing the ownership of all files where were owned by x to y.

Where 501 is my old numeric user id which is still associated with all the homebrew files.

The old user id can be found using ll /usr/local/Cellar

Now update the ownership sudo find /usr/local -user 501 -exec chown -h $USER {} \;

This way we avoid changing the ownership on files which are not controlled by homebrew or belong to some other system user.

Why std::cout instead of simply cout?

In the C++ standard, cout is defined in the std namespace, so you need to either say std::cout or put

using namespace std;

in your code in order to get at it.

However, this was not always the case, and in the past cout was just in the global namespace (or, later on, in both global and std). I would therefore conclude that your classes used an older C++ compiler.

How can I set size of a button?

This is how I did it.

            JFrame.setDefaultLookAndFeelDecorated(true);
            JDialog.setDefaultLookAndFeelDecorated(true);
            JFrame frame = new JFrame("SAP Multiple Entries");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel panel = new JPanel(new GridLayout(10,10,10,10));
            frame.setLayout(new FlowLayout());
            frame.setSize(512, 512);
            JButton button = new JButton("Select File");
            button.setPreferredSize(new Dimension(256, 256));
            panel.add(button);

            button.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent ae) {
                    JFileChooser fileChooser = new JFileChooser();
                    int returnValue = fileChooser.showOpenDialog(null);
                    if (returnValue == JFileChooser.APPROVE_OPTION) {
                        File selectedFile = fileChooser.getSelectedFile();

                        keep = selectedFile.getAbsolutePath();


                       // System.out.println(keep);
                        //out.println(file.flag); 
                       if(file.flag==true) {
                           JOptionPane.showMessageDialog(null, "It is done! \nLocation: " + file.path , "Success Message", JOptionPane.INFORMATION_MESSAGE);
                       }
                       else{
                           JOptionPane.showMessageDialog(null, "failure", "not okay", JOptionPane.INFORMATION_MESSAGE);
                       }
                    }
                }
            });
            frame.add(button);
            frame.pack();
            frame.setVisible(true);

Gradients on UIView and UILabels On iPhone

This is what I got working- set UIButton in xCode's IB to transparent/clear, and no bg image.

UIColor *pinkDarkOp = [UIColor colorWithRed:0.9f green:0.53f blue:0.69f alpha:1.0];
UIColor *pinkLightOp = [UIColor colorWithRed:0.79f green:0.45f blue:0.57f alpha:1.0];

CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = [[shareWordButton layer] bounds];
gradient.cornerRadius = 7;
gradient.colors = [NSArray arrayWithObjects:
                   (id)pinkDarkOp.CGColor,
                   (id)pinkLightOp.CGColor,
                   nil];
gradient.locations = [NSArray arrayWithObjects:
                      [NSNumber numberWithFloat:0.0f],
                      [NSNumber numberWithFloat:0.7],
                      nil];

[[recordButton layer] insertSublayer:gradient atIndex:0];

How to use RecyclerView inside NestedScrollView?

do not use recyclerView inside NestedScrollView. it may cause cascading problems! I suggest using ItemViewTypes in RecyclerView for handling multiple kinds of views. just add a RecyclerView with match_parent width and height. then in your recyclerViewAdapter override getItemViewType and use position for handling what layout to be inflated. after that you can handle your view holder by using onBindViewHolder method.

Failed to load ApplicationContext (with annotation)

In my case, I had to do the following while running with Junit5

@SpringBootTest(classes = {abc.class}) @ExtendWith(SpringExtension.class

Here abc.class was the class that was being tested

SQLite - getting number of rows in a database

You can query the actual number of rows with

SELECT Count(*) FROM tblName
see https://www.w3schools.com/sql/sql_count_avg_sum.asp

encapsulation vs abstraction real world example

If you have seen important TV machine, TV connections and TV color tube is hidden inside the TV case which is not been exposed for viewers like us and exposed only neccessary things of a TV like TV Channel keys, TV volume keys, ON/OFF switch, Cable Switch and TV remote control for viewers to use it.This means TV machine, TV connections and TV color tube is an unwanted data and not needed for viewers to see is been hidden from outside the world

So encapsulation means hiding the important features of a class which is not been needed to be exposed outside of a class and exposing only necessary things of a class. Here hidden part of a class acts like Encapsulation and exposed part of a class acts like Abstraction.

How to implement a Boolean search with multiple columns in pandas

Easiest way to do this

if this helpful hit up arrow! Tahnks!!

students = [ ('jack1', 'Apples1' , 341) ,
             ('Riti1', 'Mangos1'  , 311) ,
             ('Aadi1', 'Grapes1' , 301) ,
             ('Sonia1', 'Apples1', 321) ,
             ('Lucy1', 'Mangos1'  , 331) ,
             ('Mike1', 'Apples1' , 351),
              ('Mik', 'Apples1' , np.nan)
              ]
#Create a DataFrame object
df = pd.DataFrame(students, columns = ['Name1' , 'Product1', 'Sale1']) 
print(df)


    Name1 Product1  Sale1
0   jack1  Apples1    341
1   Riti1  Mangos1    311
2   Aadi1  Grapes1    301
3  Sonia1  Apples1    321
4   Lucy1  Mangos1    331
5   Mike1  Apples1    351
6     Mik  Apples1    NaN

# Select rows in above DataFrame for which ‘Product’ column contains the value ‘Apples’,
subset = df[df['Product1'] == 'Apples1']
print(subset)

 Name1 Product1  Sale1
0   jack1  Apples1    341
3  Sonia1  Apples1    321
5   Mike1  Apples1    351
6     Mik  Apples1    NA

# Select rows in above DataFrame for which ‘Product’ column contains the value ‘Apples’, AND notnull value in Sale

subsetx= df[(df['Product1'] == "Apples1")  & (df['Sale1'].notnull())]
print(subsetx)
    Name1   Product1    Sale1
0   jack1   Apples1      341
3   Sonia1  Apples1      321
5   Mike1   Apples1      351

# Select rows in above DataFrame for which ‘Product’ column contains the value ‘Apples’, AND Sale = 351

subsetx= df[(df['Product1'] == "Apples1")  & (df['Sale1'] == 351)]
print(subsetx)

   Name1 Product1  Sale1
5  Mike1  Apples1    351

# Another example
subsetData = df[df['Product1'].isin(['Mangos1', 'Grapes1']) ]
print(subsetData)

Name1 Product1  Sale1
1  Riti1  Mangos1    311
2  Aadi1  Grapes1    301
4  Lucy1  Mangos1    331

Here is the Original link I found this. I edit it a little bit -- https://thispointer.com/python-pandas-select-rows-in-dataframe-by-conditions-on-multiple-columns/

How I add Headers to http.get or http.post in Typescript and angular 2?

This way I was able to call MyService

private REST_API_SERVER = 'http://localhost:4040/abc';
public sendGetRequest() {
   var myFormData = { email: '[email protected]', password: '123' };
   const headers = new HttpHeaders();
   headers.append('Content-Type', 'application/json');
   //HTTP POST REQUEST
   this.httpClient
  .post(this.REST_API_SERVER, myFormData, {
    headers: headers,
   })
  .subscribe((data) => {
    console.log("i'm from service............", data, myFormData, headers);
    return data;
  });
}

Resolving MSB3247 - Found conflicts between different versions of the same dependent assembly

Sometime @AMissico answer is not enough. In my case, I couldn't find the error in the Output windows so I decided to create a log file and analyze it, by doing the following steps:

  1. Saving the build log to a file... https://msdn.microsoft.com/en-us/library/ms171470.aspx

    msbuild MyProject.proj /fl /flp:logfile=MyProjectOutput.log;verbosity=detailed

  2. Find the text: warning MS... or the specific warning info: (e.g. line 9293) Found conflicts between different versions... and the full detail of the conflict error will be above of this message (e.g. line 9277) There was a conflicts between... Find the error message

Visual Studio 2013

Selecting multiple classes with jQuery

Have you tried this?

$('.myClass, .myOtherClass').removeClass('theclass');

Check if string begins with something?

Use stringObject.substring

if (pathname.substring(0, 6) == "/sub/1") {
    // ...
}

CSS selector - element with a given child

Update 2019

The :has() pseudo-selector is propsed in the CSS Selectors 4 spec, and will address this use case once implemented.

To use it, we will write something like:

.foo > .bar:has(> .baz) { /* style here */ }

In a structure like:

<div class="foo">
  <div class="bar">
    <div class="baz">Baz!</div>
  </div>
</div>

This CSS will target the .bar div - because it both has a parent .foo and from its position in the DOM, > .baz resolves to a valid element target.


Original Answer (left for historical purposes) - this portion is no longer accurate

For completeness, I wanted to point out that in the Selectors 4 specification (currently in proposal), this will become possible. Specifically, we will gain Subject Selectors, which will be used in the following format:

!div > span { /* style here */

The ! before the div selector indicates that it is the element to be styled, rather than the span. Unfortunately, no modern browsers (as of the time of this posting) have implemented this as part of their CSS support. There is, however, support via a JavaScript library called Sel, if you want to go down the path of exploration further.

How to select rows from a DataFrame based on column values

To select rows whose column value equals a scalar, some_value, use ==:

df.loc[df['column_name'] == some_value]

To select rows whose column value is in an iterable, some_values, use isin:

df.loc[df['column_name'].isin(some_values)]

Combine multiple conditions with &:

df.loc[(df['column_name'] >= A) & (df['column_name'] <= B)]

Note the parentheses. Due to Python's operator precedence rules, & binds more tightly than <= and >=. Thus, the parentheses in the last example are necessary. Without the parentheses

df['column_name'] >= A & df['column_name'] <= B

is parsed as

df['column_name'] >= (A & df['column_name']) <= B

which results in a Truth value of a Series is ambiguous error.


To select rows whose column value does not equal some_value, use !=:

df.loc[df['column_name'] != some_value]

isin returns a boolean Series, so to select rows whose value is not in some_values, negate the boolean Series using ~:

df.loc[~df['column_name'].isin(some_values)]

For example,

import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
                   'B': 'one one two three two two one three'.split(),
                   'C': np.arange(8), 'D': np.arange(8) * 2})
print(df)
#      A      B  C   D
# 0  foo    one  0   0
# 1  bar    one  1   2
# 2  foo    two  2   4
# 3  bar  three  3   6
# 4  foo    two  4   8
# 5  bar    two  5  10
# 6  foo    one  6  12
# 7  foo  three  7  14

print(df.loc[df['A'] == 'foo'])

yields

     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

If you have multiple values you want to include, put them in a list (or more generally, any iterable) and use isin:

print(df.loc[df['B'].isin(['one','three'])])

yields

     A      B  C   D
0  foo    one  0   0
1  bar    one  1   2
3  bar  three  3   6
6  foo    one  6  12
7  foo  three  7  14

Note, however, that if you wish to do this many times, it is more efficient to make an index first, and then use df.loc:

df = df.set_index(['B'])
print(df.loc['one'])

yields

       A  C   D
B              
one  foo  0   0
one  bar  1   2
one  foo  6  12

or, to include multiple values from the index use df.index.isin:

df.loc[df.index.isin(['one','two'])]

yields

       A  C   D
B              
one  foo  0   0
one  bar  1   2
two  foo  2   4
two  foo  4   8
two  bar  5  10
one  foo  6  12

How can I get the ID of an element using jQuery?

it does not answer the OP, but may be interesting to others: you can access the .id field in this case:

$('#drop-insert').map((i, o) => o.id)

Multiple "order by" in LINQ

use the following line on your DataContext to log the SQL activity on the DataContext to the console - then you can see exactly what your linq statements are requesting from the database:

_db.Log = Console.Out

The following LINQ statements:

var movies = from row in _db.Movies 
             orderby row.CategoryID, row.Name
             select row;

AND

var movies = _db.Movies.OrderBy(m => m.CategoryID).ThenBy(m => m.Name);

produce the following SQL:

SELECT [t0].ID, [t0].[Name], [t0].CategoryID
FROM [dbo].[Movies] as [t0]
ORDER BY [t0].CategoryID, [t0].[Name]

Whereas, repeating an OrderBy in Linq, appears to reverse the resulting SQL output:

var movies = from row in _db.Movies 
             orderby row.CategoryID
             orderby row.Name
             select row;

AND

var movies = _db.Movies.OrderBy(m => m.CategoryID).OrderBy(m => m.Name);

produce the following SQL (Name and CategoryId are switched):

SELECT [t0].ID, [t0].[Name], [t0].CategoryID
FROM [dbo].[Movies] as [t0]
ORDER BY [t0].[Name], [t0].CategoryID

Only detect click event on pseudo-element

This is edited answer by Fasoeu with latest CSS3 and JS ES6

Edited demo without using JQuery.

Shortest example of code:

<p><span>Some text</span></p>
p {
    position: relative;
    pointer-events: none;
}
p::before {
    content: "";
    position: absolute;
    pointer-events: auto;
}
p span {
    display: contents;
    pointer-events: auto;
}
const all_p = Array.from(document.querySelectorAll('p'));

for (let p of all_p) {
    p.addEventListener("click", listener, false);
};

Explanation:

pointer-events control detection of events, removing receiving events from target, but keep receiving from pseudo-elements make possible to click on ::before and ::after and you will always know what you are clicking on pseudo-element, however if you still need to click, you put all content in nested element (span in example), but because we don't want to apply any additional styles, display: contents; become very handy solution and it supported by most browsers. pointer-events: none; as already mentioned in original post also widely supported.

The JavaScript part also used widely supported Array.from and for...of, however they are not necessary to use in code.

ImportError: No module named win32com.client

I realize this post is old but I wanted to add that I had to take an extra step to get this to work.

Instead of just doing:

pip install pywin32

I had use use the -m flag to get this to work properly. Without it I was running into an issue where I was still getting the error ImportError: No module named win32com.

So to fix this you can give this a try:

python -m pip install pywin32

This worked for me and has worked on several version of python where just doing pip install pywin32 did not work.

Versions tested on:

3.6.2, 3.7.6, 3.8.0, 3.9.0a1.

\n or \n in php echo not print

\n must be in double quotes!

 echo '<p>' . $unit1 . "</p>\n";

Difference between final and effectively final

final is a variable declare with key word final , example:

final double pi = 3.14 ;

it remains final through out the program.

effectively final : any local variable or parameter that is assigned a value only once right now(or updated only once). It may not remain effectively final through out the program. so this means that effectively final variable might loose its effectively final property after immediately the time it gets assigned/updated at least one more assignment. example:

class EffectivelyFinal {

    public static void main(String[] args) {
        calculate(124,53);
    }

    public static void calculate( int operand1, int operand2){   
     int rem = 0;  //   operand1, operand2 and rem are effectively final here
     rem = operand1%2  // rem lost its effectively final property here because it gets its second assignment 
                       // operand1, operand2 are still effectively final here 
        class operators{

            void setNum(){
                operand1 =   operand2%2;  // operand1 lost its effectively final property here because it gets its second assignment
            }

            int add(){
                return rem + operand2;  // does not compile because rem is not effectively final
            }
            int multiply(){
                return rem * operand1;  // does not compile because both rem and operand1 are not effectively final
            }
        }   
   }    
}

Vertical align middle with Bootstrap responsive grid

.row {
    letter-spacing: -.31em;
    word-spacing: -.43em;
}
.col-md-4 {
    float: none;
    display: inline-block;
    vertical-align: middle;
}

Note: .col-md-4 could be any grid column, its just an example here.

How and when to use SLEEP() correctly in MySQL?

SELECT ...
SELECT SLEEP(5);
SELECT ...

But what are you using this for? Are you trying to circumvent/reinvent mutexes or transactions?

How to get the selected value from drop down list in jsp?

I've got one more additional option to get value by id:

var idElement = document.getElementById("idName");
var selectedValue = idElement.options[idElement.selectedIndex].value;

It's a simple JavaScript solution.

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

When you share for Facebook, you have to add in your html into the head section next meta tags:

<meta property="og:title" content="title" />
<meta property="og:description" content="description" />
<meta property="og:image" content="thumbnail_image" />

And that's it!

Add the button as you should according to what FB tells you.

All the info you need is in www.facebook.com/share/

Convert JSON string to dict using Python

use simplejson or cjson for speedups

import simplejson as json

json.loads(obj)

or 

cjson.decode(obj)

Ineligible Devices section appeared in Xcode 6.x.x

I changed my deployment target to 7.1 the same as my iphone, and now I can run swift programs on it. It was on 8.0 and showed up as ineligible.

Safest way to run BAT file from Powershell script

To run the .bat, and have access to the last exit code, run it as:

 & .\my-app\my-fle.bat

Connecting to remote URL which requires authentication using Java

Was able to set the auth using the HttpsURLConnection

           URL myUrl = new URL(httpsURL);
            HttpsURLConnection conn = (HttpsURLConnection)myUrl.openConnection();
            String userpass = username + ":" + password;
            String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
            //httpsurlconnection
            conn.setRequestProperty("Authorization", basicAuth);

few of the changes fetched from this post. and Base64 is from java.util package.

How to subtract days from a plain Date?

This will give you last 10 days result 110% working you will not get any type of issue

var date = new Date();
var day=date.getDate();
var month=date.getMonth() + 1;
var year=date.getFullYear();
var startDate=day+"/"+month+"/"+year;
var dayBeforeNineDays=moment().subtract(10, 'days').format('DD/MM/YYYY');
startDate=dayBeforeNineDays;
var endDate=day+"/"+month+"/"+year;

you can change the subtract days according to your requirements

Insert results of a stored procedure into a temporary table

EXEC sp_serveroption 'YOURSERVERNAME', 'DATA ACCESS', TRUE

SELECT  *
INTO    #tmpTable
FROM    OPENQUERY(YOURSERVERNAME, 'EXEC db.schema.sproc 1')

How to split long commands over multiple lines in PowerShell

Another method for cleaner argument passing would be splatting.

Define your parameters and values as a hashtable like this:

$params = @{ 'class' = 'Win32_BIOS';
             'computername'='SERVER-R2';
             'filter'='drivetype=3';
             'credential'='Administrator' }

And then call your commandlet like this:

Get-WmiObject @params

Microsoft Docs: About Splatting

TechNet Magazine 2011: Windows PowerShell: Splatting

Looks like it works with Powershell 2.0 and up

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

I have build such kind of application using approximatively the same approach except :

  • I cache the generated image on the disk and always generate two to three images in advance in a separate thread.
  • I don't overlay with a UIImage but instead draw the image in the layer when zooming is 1. Those tiles will be released automatically when memory warnings are issued.

Whenever the user start zooming, I acquire the CGPDFPage and render it using the appropriate CTM. The code in - (void)drawLayer: (CALayer*)layer inContext: (CGContextRef) context is like :

CGAffineTransform currentCTM = CGContextGetCTM(context);    
if (currentCTM.a == 1.0 && baseImage) {
    //Calculate ideal scale
    CGFloat scaleForWidth = baseImage.size.width/self.bounds.size.width;
    CGFloat scaleForHeight = baseImage.size.height/self.bounds.size.height; 
    CGFloat imageScaleFactor = MAX(scaleForWidth, scaleForHeight);

    CGSize imageSize = CGSizeMake(baseImage.size.width/imageScaleFactor, baseImage.size.height/imageScaleFactor);
    CGRect imageRect = CGRectMake((self.bounds.size.width-imageSize.width)/2, (self.bounds.size.height-imageSize.height)/2, imageSize.width, imageSize.height);
    CGContextDrawImage(context, imageRect, [baseImage CGImage]);
} else {
    @synchronized(issue) { 
        CGPDFPageRef pdfPage = CGPDFDocumentGetPage(issue.pdfDoc, pageIndex+1);
        pdfToPageTransform = CGPDFPageGetDrawingTransform(pdfPage, kCGPDFMediaBox, layer.bounds, 0, true);
        CGContextConcatCTM(context, pdfToPageTransform);    
        CGContextDrawPDFPage(context, pdfPage);
    }
}

issue is the object containg the CGPDFDocumentRef. I synchronize the part where I access the pdfDoc property because I release it and recreate it when receiving memoryWarnings. It seems that the CGPDFDocumentRef object do some internal caching that I did not find how to get rid of.

Using grep to search for a string that has a dot in it

You can also search with -- option which basically ignores all the special characters and it won't be interpreted by grep.

$ cat foo |grep -- "0\.49"

How to stop VBA code running?

~ For those using custom input box

Private Sub CommandButton1_Click()

DoCmd.Close acForm, Me.Name
End

End Sub

Remove leading or trailing spaces in an entire column of data

Quite often the issue is a non-breaking space - CHAR(160) - especially from Web text sources -that CLEAN can't remove, so I would go a step further than this and try a formula like this which replaces any non-breaking spaces with a standard one

=TRIM(CLEAN(SUBSTITUTE(A1,CHAR(160)," ")))

Ron de Bruin has an excellent post on tips for cleaning data here

You can also remove the CHAR(160) directly without a workaround formula by

  • Edit .... Replace your selected data,
  • in Find What hold ALT and type 0160 using the numeric keypad
  • Leave Replace With as blank and select Replace All

How to create separate AngularJS controller files?

For brevity, here's an ES2015 sample that doesn't rely on global variables

// controllers/example-controller.js

export const ExampleControllerName = "ExampleController"
export const ExampleController = ($scope) => {
  // something... 
}

// controllers/another-controller.js

export const AnotherControllerName = "AnotherController"
export const AnotherController = ($scope) => {
  // functionality... 
}

// app.js

import angular from "angular";

import {
  ExampleControllerName,
  ExampleController
} = "./controllers/example-controller";

import {
  AnotherControllerName,
  AnotherController
} = "./controllers/another-controller";

angular.module("myApp", [/* deps */])
  .controller(ExampleControllerName, ExampleController)
  .controller(AnotherControllerName, AnotherController)

SUM of grouped COUNT in SQL Query

You can try group by on name and count the ids in that group.

SELECT name, count(id) as COUNT FROM table group by name

Setting up and using Meld as your git difftool and mergetool

How do I set up and use Meld as my git difftool?

git difftool displays the diff using a GUI diff program (i.e. Meld) instead of displaying the diff output in your terminal.

Although you can set the GUI program on the command line using -t <tool> / --tool=<tool> it makes more sense to configure it in your .gitconfig file. [Note: See the sections about escaping quotes and Windows paths at the bottom.]

# Add the following to your .gitconfig file.
[diff]
    tool = meld
[difftool]
    prompt = false
[difftool "meld"]
    cmd = meld "$LOCAL" "$REMOTE"

[Note: These settings will not alter the behaviour of git diff which will continue to function as usual.]

You use git difftool in exactly the same way as you use git diff. e.g.

git difftool <COMMIT_HASH> file_name
git difftool <BRANCH_NAME> file_name
git difftool <COMMIT_HASH_1> <COMMIT_HASH_2> file_name

If properly configured a Meld window will open displaying the diff using a GUI interface.

The order of the Meld GUI window panes can be controlled by the order of $LOCAL and $REMOTE in cmd, that is to say which file is shown in the left pane and which in the right pane. If you want them the other way around simply swap them around like this:

    cmd = meld "$REMOTE" "$LOCAL"

Finally the prompt = false line simply stops git from prompting you as to whether you want to launch Meld or not, by default git will issue a prompt.


How do I set up and use Meld as my git mergetool?

git mergetool allows you to use a GUI merge program (i.e. Meld) to resolve the merge conflicts that have occurred during a merge.

Like difftool you can set the GUI program on the command line using -t <tool> / --tool=<tool> but, as before, it makes more sense to configure it in your .gitconfig file. [Note: See the sections about escaping quotes and Windows paths at the bottom.]

# Add the following to your .gitconfig file.
[merge]
    tool = meld
[mergetool "meld"]
    # Choose one of these 2 lines (not both!) explained below.
    cmd = meld "$LOCAL" "$MERGED" "$REMOTE" --output "$MERGED"
    cmd = meld "$LOCAL" "$BASE" "$REMOTE" --output "$MERGED"

You do NOT use git mergetool to perform an actual merge. Before using git mergetool you perform a merge in the usual way with git. e.g.

git checkout master
git merge branch_name

If there is a merge conflict git will display something like this:

$ git merge branch_name
Auto-merging file_name
CONFLICT (content): Merge conflict in file_name
Automatic merge failed; fix conflicts and then commit the result.

At this point file_name will contain the partially merged file with the merge conflict information (that's the file with all the >>>>>>> and <<<<<<< entries in it).

Mergetool can now be used to resolve the merge conflicts. You start it very easily with:

git mergetool

If properly configured a Meld window will open displaying 3 files. Each file will be contained in a separate pane of its GUI interface.

In the example .gitconfig entry above, 2 lines are suggested as the [mergetool "meld"] cmd line. In fact there are all kinds of ways for advanced users to configure the cmd line, but that is beyond the scope of this answer.

This answer has 2 alternative cmd lines which, between them, will cater for most users, and will be a good starting point for advanced users who wish to take the tool to the next level of complexity.

Firstly here is what the parameters mean:

  • $LOCAL is the file in the current branch (e.g. master).
  • $REMOTE is the file in the branch being merged (e.g. branch_name).
  • $MERGED is the partially merged file with the merge conflict information in it.
  • $BASE is the shared commit ancestor of $LOCAL and $REMOTE, this is to say the file as it was when the branch containing $REMOTE was originally created.

I suggest you use either:

[mergetool "meld"]
    cmd = meld "$LOCAL" "$MERGED" "$REMOTE" --output "$MERGED"

or:

[mergetool "meld"]
    cmd = meld "$LOCAL" "$BASE" "$REMOTE" --output "$MERGED"
    # See 'Note On Output File' which explains --output "$MERGED".

The choice is whether to use $MERGED or $BASE in between $LOCAL and $REMOTE.

Either way Meld will display 3 panes with $LOCAL and $REMOTE in the left and right panes and either $MERGED or $BASE in the middle pane.

In BOTH cases the middle pane is the file that you should edit to resolve the merge conflicts. The difference is just in which starting edit position you'd prefer; $MERGED for the file which contains the partially merged file with the merge conflict information or $BASE for the shared commit ancestor of $LOCAL and $REMOTE. [Since both cmd lines can be useful I keep them both in my .gitconfig file. Most of the time I use the $MERGED line and the $BASE line is commented out, but the commenting out can be swapped over if I want to use the $BASE line instead.]

Note On Output File: Do not worry that --output "$MERGED" is used in cmd regardless of whether $MERGED or $BASE was used earlier in the cmd line. The --output option simply tells Meld what filename git wants the conflict resolution file to be saved in. Meld will save your conflict edits in that file regardless of whether you use $MERGED or $BASE as your starting edit point.

After editing the middle pane to resolve the merge conflicts, just save the file and close the Meld window. Git will do the update automatically and the file in the current branch (e.g. master) will now contain whatever you ended up with in the middle pane.

git will have made a backup of the partially merged file with the merge conflict information in it by appending .orig to the original filename. e.g. file_name.orig. After checking that you are happy with the merge and running any tests you may wish to do, the .orig file can be deleted.

At this point you can now do a commit to commit the changes.

If, while you are editing the merge conflicts in Meld, you wish to abandon the use of Meld, then quit Meld without saving the merge resolution file in the middle pane. git will respond with the message file_name seems unchanged and then ask Was the merge successful? [y/n], if you answer n then the merge conflict resolution will be aborted and the file will remain unchanged. Note that if you have saved the file in Meld at any point then you will not receive the warning and prompt from git. [Of course you can just delete the file and replace it with the backup .orig file that git made for you.]

If you have more than 1 file with merge conflicts then git will open a new Meld window for each, one after another until they are all done. They won't all be opened at the same time, but when you finish editing the conflicts in one, and close Meld, git will then open the next one, and so on until all the merge conflicts have been resolved.

It would be sensible to create a dummy project to test the use of git mergetool before using it on a live project. Be sure to use a filename containing a space in your test, in case your OS requires you to escape the quotes in the cmd line, see below.


Escaping quote characters

Some operating systems may need to have the quotes in cmd escaped. Less experienced users should remember that config command lines should be tested with filenames that include spaces, and if the cmd lines don't work with the filenames that include spaces then try escaping the quotes. e.g.

cmd = meld \"$LOCAL\" \"$REMOTE\"

In some cases more complex quote escaping may be needed. The 1st of the Windows path links below contains an example of triple-escaping each quote. It's a bore but sometimes necessary. e.g.

cmd = meld \\\"$LOCAL\\\" \\\"$REMOTE\\\"

Windows paths

Windows users will probably need extra configuration added to the Meld cmd lines. They may need to use the full path to meldc, which is designed to be called on Windows from the command line, or they may need or want to use a wrapper. They should read the StackOverflow pages linked below which are about setting the correct Meld cmd line for Windows. Since I am a Linux user I am unable to test the various Windows cmd lines and have no further information on the subject other than to recommend using my examples with the addition of a full path to Meld or meldc, or adding the Meld program folder to your path.

Ignoring trailing whitespace with Meld

Meld has a number of preferences that can be configured in the GUI.

In the preferences Text Filters tab there are several useful filters to ignore things like comments when performing a diff. Although there are filters to ignore All whitespace and Leading whitespace, there is no ignore Trailing whitespace filter (this has been suggested as an addition in the Meld mailing list but is not available in my version).

Ignoring trailing whitespace is often very useful, especially when collaborating, and can be manually added easily with a simple regular expression in the Meld preferences Text Filters tab.

# Use either of these regexes depending on how comprehensive you want it to be.
[ \t]*$
[ \t\r\f\v]*$

I hope this helps everyone.

Node.js EACCES error when listening on most ports

Running on your workstation

As a general rule, processes running without root privileges cannot bind to ports below 1024.

So try a higher port, or run with elevated privileges via sudo. You can downgrade privileges after you have bound to the low port using process.setgid and process.setuid.

Running on heroku

When running your apps on heroku you have to use the port as specified in the PORT environment variable.

See http://devcenter.heroku.com/articles/node-js

const server = require('http').createServer();
const port = process.env.PORT || 3000;

server.listen(port, () => console.log(`Listening on ${port}`));

Aggregate multiple columns at once

You could try:

agg <- aggregate(list(x$val1, x$val2, x$val3, x$val4), by = list(x$id1, x$id2), mean)

Found conflicts between different versions of the same dependent assembly that could not be resolved

I just ran into this and the problem after switching a package from nuget to locally referenced dlls. The issue was old runtime binding stuff in app.config.

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

As a fallback solution, you could wrap your classes in a parent element like this:

<div>
    <div>This text should appear as normal</div>
    <p>This text should be blue.</p>
    <div>
        <!-- first-child / first-of-type starts from here -->
        <p class="myclass1">This text should appear red.</p>
        <p class="myclass2">This text should appear green.</p>
    </div>
</div>

How to make an ImageView with rounded corners?

Answer for the question that is redirected here: "How to create a circular ImageView in Android?"

public static Bitmap getRoundBitmap(Bitmap bitmap) {

    int min = Math.min(bitmap.getWidth(), bitmap.getHeight());

    Bitmap bitmapRounded = Bitmap.createBitmap(min, min, bitmap.getConfig());

    Canvas canvas = new Canvas(bitmapRounded);
    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setShader(new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
    canvas.drawRoundRect((new RectF(0.0f, 0.0f, min, min)), min/2, min/2, paint);

    return bitmapRounded;
}

What is an NP-complete in computer science?

NP-complete problems are a set of problems to each of which any other NP-problem can be reduced in polynomial time, and whose solution may still be verified in polynomial time. That is, any NP problem can be transformed into any of the NP-complete problems. – Informally, an NP-complete problem is an NP problem that is at least as "tough" as any other problem in NP.

Subversion ignoring "--password" and "--username" options

I had a similar problem, I wanted to use a different user name for a svn+ssh repository. In the end, I used svn relocate (as described in in this answer. In my case, I'm using svn 1.6.11 and did the following:

svn switch --relocate \
    svn+ssh://olduser@svnserver/path/to/repo \
    svn+ssh://newuser@svnserver/path/to/repo

where svn+ssh://olduser@svnserver/path/to/repo can be found in the URL: line output of svn info command. This command asked me for the password of newuser.

Note that this change is persistent, i.e. if you want only temporarily switch to the new username with this method, you'll have to issue a similar command again after svn update etc.

UIView Infinite 360 degree rotation animation?

Swift 5 UIView Extension using Keyframe Animations

This approach allows us to directly use the UIView.AnimationOptions.repeat

public extension UIView {

    func animateRotation(duration: TimeInterval, repeat: Bool, completion: ((Bool) -> ())?) {

        var options = UIView.KeyframeAnimationOptions(rawValue: UIView.AnimationOptions.curveLinear.rawValue)

        if `repeat` {
            options.insert(.repeat)
        }

        UIView.animateKeyframes(withDuration: duration, delay: 0, options: options, animations: {

            UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.25, animations: {
                self.transform = CGAffineTransform(rotationAngle: CGFloat.pi/2)
            })

            UIView.addKeyframe(withRelativeStartTime: 0.25, relativeDuration: 0.25, animations: {
                self.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
            })

            UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.25, animations: {
                self.transform = CGAffineTransform(rotationAngle: 3*CGFloat.pi/2)
            })

            UIView.addKeyframe(withRelativeStartTime: 0.75, relativeDuration: 0.25, animations: {
                self.transform = CGAffineTransform(rotationAngle: 2*CGFloat.pi)
            })

        }, completion: completion)

    }

}

Copy data from another Workbook through VBA

Are you looking for the syntax to open them:

Dim wkbk As Workbook

Set wkbk = Workbooks.Open("C:\MyDirectory\mysheet.xlsx")

Then, you can use wkbk.Sheets(1).Range("3:3") (or whatever you need)

Phone validation regex

^+?\d{3}-?\d{2}-?\d{2}-?\d{3}$

You may try this....

How about this one....Hope this helps...

^(\\+?)\d{3,3}-?\d{2,2}-?\d{2,2}-?\d{3,3}$

How to prevent Google Colab from disconnecting?

Try this:

function ClickConnect(){
  console.log("Working"); 
  document
    .querySelector("#top-toolbar > colab-connect-button")
    .shadowRoot
    .querySelector("#connect")
    .click()
}

setInterval(ClickConnect,60000)

Non-resolvable parent POM using Maven 3.0.3 and relativePath notation

Please check in logs if you have http.HttpWagon$__sisu1:Cannot find 'basicAuthScope' this error or warning also, if so you need to use maven 3.2.5 version, which will resolve error.

'App not Installed' Error on Android

In my case, it's because Android Studio 3.0 sets android:testOnly="true" on APKs that build from the release Build Variant.

https://commonsware.com/blog/2017/10/31/android-studio-3p0-flag-test-only.html

So run ./gradlew assembleRelease solve my issue

CSS: How to remove pseudo elements (after, before,...)?

had a same problem few minutes ago and just content:none; did not do work but adding content:none !important; and display:none !important; worked for me

difference between $query>num_rows() and $this->db->count_all_results() in CodeIgniter & which one is recommended

Simply as bellow;

$this->db->get('table_name')->num_rows();

This will get number of rows/records. however you can use search parameters as well;

$this->db->select('col1','col2')->where('col'=>'crieterion')->get('table_name')->num_rows();

However, it should be noted that you will see bad bad errors if applying as below;

$this->db->get('table_name')->result()->num_rows();

Facebook database design?

You're looking for foreign keys. Basically you can't have an array in a database unless it has it's own table.


Example schema:

    Users Table
        userID PK
        other data
    Friends Table
        userID   -- FK to users's table representing the user that has a friend.
        friendID -- FK to Users' table representing the user id of the friend

Unexpected token ILLEGAL in webkit

I got the same error when the script file I was including container some special characters and when I was running in local moode (directly from local disk). I my case the solution was to explicitly tell the encoding:

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

Understanding Fragment's setRetainInstance(boolean)

setRetaininstance is only useful when your activity is destroyed and recreated due to a configuration change because the instances are saved during a call to onRetainNonConfigurationInstance. That is, if you rotate the device, the retained fragments will remain there(they're not destroyed and recreated.) but when the runtime kills the activity to reclaim resources, nothing is left. When you press back button and exit the activity, everything is destroyed.

Usually I use this function to saved orientation changing Time.Say I have download a bunch of Bitmaps from server and each one is 1MB, when the user accidentally rotate his device, I certainly don't want to do all the download work again.So I create a Fragment holding my bitmaps and add it to the manager and call setRetainInstance,all the Bitmaps are still there even if the screen orientation changes.

jquery: how to get the value of id attribute?

You need to do:

alert($(this).attr('value'));

How to replace four spaces with a tab in Sublime Text 2?

create a keybinding for quickest way

{ "keys": ["super+alt+t"], "command": "unexpand_tabs", "args": { "set_translate_tabs": true } }

add this to Preferences > Key Bindings (user) when you press super+alt+t it will convert spaces to tabs

Accessing an array out of bounds gives no error, why?

Undefined behavior working in your favor. Whatever memory you're clobbering apparently isn't holding anything important. Note that C and C++ do not do bounds checking on arrays, so stuff like that isn't going to be caught at compile or run time.

How to check if a double value has no decimal part

You could simply do

d % 1 == 0

to check if double d is a whole.

How to create a simple checkbox in iOS?

Yeah, no checkbox for you in iOS (-:

Here, this is what I did to create a checkbox:

UIButton *checkbox;
BOOL checkBoxSelected;
checkbox = [[UIButton alloc] initWithFrame:CGRectMake(x,y,20,20)];
// 20x20 is the size of the checkbox that you want
// create 2 images sizes 20x20 , one empty square and
// another of the same square with the checkmark in it
// Create 2 UIImages with these new images, then:

[checkbox setBackgroundImage:[UIImage imageNamed:@"notselectedcheckbox.png"]
                    forState:UIControlStateNormal];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
                    forState:UIControlStateSelected];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
                    forState:UIControlStateHighlighted];
checkbox.adjustsImageWhenHighlighted=YES;
[checkbox addTarget:(nullable id) action:(nonnull SEL) forControlEvents:(UIControlEvents)];
[self.view addSubview:checkbox];

Now in the target method do the following:

-(void)checkboxSelected:(id)sender
{
    checkBoxSelected = !checkBoxSelected; /* Toggle */
    [checkbox setSelected:checkBoxSelected];
}

That's it!

How do I drop a foreign key in SQL Server?

Try

alter table company drop constraint Company_CountryID_FK


alter table company drop column CountryID

How to query for Xml values and attributes from table in SQL Server?

Actually you're close to your goal, you just need to use nodes() method to split your rows and then get values:

select
    s.SqmId,
    m.c.value('@id', 'varchar(max)') as id,
    m.c.value('@type', 'varchar(max)') as type,
    m.c.value('@unit', 'varchar(max)') as unit,
    m.c.value('@sum', 'varchar(max)') as [sum],
    m.c.value('@count', 'varchar(max)') as [count],
    m.c.value('@minValue', 'varchar(max)') as minValue,
    m.c.value('@maxValue', 'varchar(max)') as maxValue,
    m.c.value('.', 'nvarchar(max)') as Value,
    m.c.value('(text())[1]', 'nvarchar(max)') as Value2
from sqm as s
    outer apply s.data.nodes('Sqm/Metrics/Metric') as m(c)

sql fiddle demo

Init function in javascript and how it works

Its is called immediatly invoking function expression (IIFE). Mainly associated with the JavaScript closure concept. Main use is to run the function before the global variable changed, so that the expected behaviour of code can be retained.

What does 'stale file handle' in Linux mean?

When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).

Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle message because you asked for some nonexistent data.

When you perform a cd operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.

How do I connect to my existing Git repository using Visual Studio Code?

  1. Open Visual Studio Code terminal (Ctrl + `)
  2. Write the Git clone command. For example,

    git clone https://github.com/angular/angular-phonecat.git
    
  3. Open the folder you have just cloned (menu FileOpen Folder)

    Enter image description here

535-5.7.8 Username and Password not accepted

First, You need to use a valid Gmail account with your credentials.

Second, In my app I don't use TLS auto, try without this line:

config.action_mailer.smtp_settings = {
  address:              'smtp.gmail.com',
  port:                 587,
  domain:               'gmail.com',
  user_name:            '[email protected]',
  password:             'YOUR_PASSWORD',
  authentication:       'plain'
  # enable_starttls_auto: true
  # ^ ^ remove this option ^ ^
}

UPDATE: (See answer below for details) now you need to enable "less secure apps" on your Google Account

https://myaccount.google.com/lesssecureapps?pli=1

Simulate low network connectivity for Android

for and mac OS user you can use Network Link Conditioner which could be downloaded from apple. set it as a AP on mac and any divices could connected it.

you can either use facebook open source tools ATC http://facebook.github.io/augmented-traffic-control/

Oracle SQL Where clause to find date records older than 30 days

Use:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= TRUNC(SYSDATE) - 30

SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date that is 30 days previous including the current time.

Depending on your needs, you could also look at using ADD_MONTHS:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)

Difference between a virtual function and a pure virtual function

You can actually provide implementations of pure virtual functions in C++. The only difference is all pure virtual functions must be implemented by derived classes before the class can be instantiated.

Some dates recognized as dates, some dates not recognized. Why?

Here is what worked for me. I highlighted the column with all my dates. Under the Data tab, I selected 'text to columns' and selected the 'Delimited' box, I hit next and finish. Although it didn't seem like anything changed, Excel now read the column as dates and I was able to sort by dates.

how to fix java.lang.IndexOutOfBoundsException

This error happens because your list lstpp is empty (Nothing at index 0). So either there is a bug in your getResult() function, or the empty list is normal and you need to handle this case (By checking the size of the list before, or catching the exception).

How to copy a selection to the OS X clipboard

Use Homebrew's vim: brew install vim

Mac (as of 10.10.3 Yosemite) comes pre-installed with a system vim that does not have the clipboard flag enabled.

You can either compile vim for yourself and enable that flag, or simply use Homebrew's vim which is setup properly.

To see this for yourself, check out the stock system vim with /usr/bin/vim --version

You'll see something like:

$ /usr/bin/vim --version

VIM - Vi IMproved 7.3 (2010 Aug 15, compiled Nov  5 2014 21:00:28)
Compiled by [email protected]
Normal version without GUI.  Features included (+) or not (-):
... -clientserver -clipboard +cmdline_compl ...

Note the -clipboard

With homebrew's vim you instead get

$ /usr/local/bin/vim --version

VIM - Vi IMproved 7.4 (2013 Aug 10, compiled May 10 2015 14:04:42)
MacOS X (unix) version
Included patches: 1-712
Compiled by Homebrew
Huge version without GUI.  Features included (+) or not (-):
... +clipboard ...

Note the +clipboard

How to cast an object in Objective-C

Remember, Objective-C is a superset of C, so typecasting works as it does in C:

myEditController = [[SelectionListViewController alloc] init];
((SelectionListViewController *)myEditController).list = listOfItems;

What are .tpl files? PHP, web design

Other possibilities for .tpl: HTML::SimpleTemplate, example:

Hello $name

, and Template Toolkit, example:

Hello [% world %]!

ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

In my case, the problem was I didn't had a Tomcat server separately installed in my eclipse. I assumed my Springboot will start the server automatically within itself.

Since my main class extends SpringBootServletInitializer and override configure method, I definitely need a Tomcat server installed in my IDE.

To install, first download Apachce Tomcat (version 9 in my case) and create server using Servers tab.

After installation, run the main class on server.

Run As -> Run on Server

ggplot2 legend to bottom and horizontal

If you want to move the position of the legend please use the following code:

library(reshape2) # for melt
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
    theme(legend.position="bottom")

This should give you the desired result. Legend at bottom

CSS: Truncate table cells, but fit as much as possible

I've been recently working on it. Check out this jsFiddle test, try it yourself changing the width of the base table to check the behavior).

The solution is to embedded a table into another:

<table style="width: 200px;border:0;border-collapse:collapse">
    <tbody>
        <tr>
            <td style="width: 100%;">
                <table style="width: 100%;border:0;border-collapse:collapse">
                    <tbody>
                        <tr>
                            <td>
                                <div style="position: relative;overflow:hidden">
                                    <p>&nbsp;</p>
                                    <p style="overflow:hidden;text-overflow: ellipsis;position: absolute; top: 0pt; left: 0pt;width:100%">This cells has more content</p>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </td>
            <td style="white-space:nowrap">Less content here</td>
        </tr>
    </tbody>
</table>

Is Fred now happy with Celldito's expansion?

Send Message in C#

Some other options:

Common Assembly

Create another assembly that has some common interfaces that can be implemented by the assemblies.

Reflection

This has all sorts of warnings and drawbacks, but you could use reflection to instantiate / communicate with the forms. This is both slow and runtime dynamic (no static checking of this code at compile time).

How do I fill arrays in Java?

Check out the Arrays.fill methods.

int[] array = new int[4];
Arrays.fill(array, 0);

Connection attempt failed with "ECONNREFUSED - Connection refused by server"

I solved this error

A connection attempt failed with "ECONNREFUSED - Connection refused by server"

by changing my port to 22 that was successful

How to embed PDF file with responsive width

Seen from a non-PHP guru perspective, this should do exactly what us desired to:

<style>
    [name$='pdf'] { width:100%; height: auto;}
</style>

How do I generate a random int number?

I've tried all of these solutions excluding the COBOL answer... lol

None of these solutions were good enough. I needed randoms in a fast for int loop and I was getting tons of duplicate values even in very wide ranges. After settling for kind of random results far too long I decided to finally tackle this problem once and for all.

It's all about the seed.

I create a random integer by parsing out the non-digits from Guid, then I use that to instantiate my Random class.

public int GenerateRandom(int min, int max)
{
    var seed = Convert.ToInt32(Regex.Match(Guid.NewGuid().ToString(), @"\d+").Value);
    return new Random(seed).Next(min, max);
}

Update: Seeding isn't necessary if you instantiate the Random class once. So it'd be best to create a static class and call a method off that.

public static class IntUtil
{
   private static Random random;

   private static void Init()
   {
      if (random == null) random = new Random();
   }

   public static int Random(int min, int max)
   {
      Init();
      return random.Next(min, max);
   }
}

Then you can use the static class like so..

for(var i = 0; i < 1000; i++)
{
   int randomNumber = IntUtil.Random(1,100);
   Console.WriteLine(randomNumber); 
}

I admit I like this approach better.

Filter LogCat to get only the messages from My Application in Android?

Using Windows command prompt: adb logcat -d | findstr <package>.

*This was first mentioned by jj_, but it took me ages to find it in the comments...

How to show an empty view with a RecyclerView?

Use AdapterDataObserver in custom RecyclerView

Kotlin:

RecyclerViewEnum.kt

enum class RecyclerViewEnum {
    LOADING,
    NORMAL,
    EMPTY_STATE
}

RecyclerViewEmptyLoadingSupport.kt

class RecyclerViewEmptyLoadingSupport : RecyclerView {

    var stateView: RecyclerViewEnum? = RecyclerViewEnum.LOADING
        set(value) {
            field = value
            setState()
        }
    var emptyStateView: View? = null
    var loadingStateView: View? = null


    constructor(context: Context) : super(context) {}

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {}

    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {}


    private val dataObserver = object : AdapterDataObserver() {
        override fun onChanged() {
            onChangeState()
        }

        override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
            super.onItemRangeRemoved(positionStart, itemCount)
            onChangeState()
        }

        override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
            super.onItemRangeInserted(positionStart, itemCount)
            onChangeState()
        }
    }


    override fun setAdapter(adapter: RecyclerView.Adapter<*>?) {
        super.setAdapter(adapter)
        adapter?.registerAdapterDataObserver(dataObserver)
        dataObserver.onChanged()
    }


    fun onChangeState() {
        if (adapter?.itemCount == 0) {
            emptyStateView?.visibility = View.VISIBLE
            loadingStateView?.visibility = View.GONE
            [email protected] = View.GONE
        } else {
            emptyStateView?.visibility = View.GONE
            loadingStateView?.visibility = View.GONE
            [email protected] = View.VISIBLE
        }
    }

    private fun setState() {

        when (this.stateView) {
            RecyclerViewEnum.LOADING -> {
                loadingStateView?.visibility = View.VISIBLE
                [email protected] = View.GONE
                emptyStateView?.visibility = View.GONE
            }

            RecyclerViewEnum.NORMAL -> {
                loadingStateView?.visibility = View.GONE
                [email protected] = View.VISIBLE
                emptyStateView?.visibility = View.GONE
            }
            RecyclerViewEnum.EMPTY_STATE -> {
                loadingStateView?.visibility = View.GONE
                [email protected] = View.GONE
                emptyStateView?.visibility = View.VISIBLE
            }
        }
    }
}

layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/emptyView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white"
        android:gravity="center"
        android:orientation="vertical">

        <TextView
            android:id="@+id/emptyLabelTv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="empty" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/loadingView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white"
        android:gravity="center"
        android:orientation="vertical">

        <ProgressBar
            android:id="@+id/progressBar"
            android:layout_width="45dp"
            android:layout_height="45dp"
            android:layout_gravity="center"
            android:indeterminate="true"
            android:theme="@style/progressBarBlue" />
    </LinearLayout>

    <com.peeyade.components.recyclerView.RecyclerViewEmptyLoadingSupport
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

in activity use this way:

recyclerView?.apply {
        layoutManager = GridLayoutManager(context, 2)
        emptyStateView = emptyView
        loadingStateView = loadingView
        adapter = adapterGrid
    }

    // you can set LoadingView or emptyView manual
    recyclerView.stateView = RecyclerViewEnum.EMPTY_STATE
    recyclerView.stateView = RecyclerViewEnum.LOADING

How are iloc and loc different?

iloc works based on integer positioning. So no matter what your row labels are, you can always, e.g., get the first row by doing

df.iloc[0]

or the last five rows by doing

df.iloc[-5:]

You can also use it on the columns. This retrieves the 3rd column:

df.iloc[:, 2]    # the : in the first position indicates all rows

You can combine them to get intersections of rows and columns:

df.iloc[:3, :3] # The upper-left 3 X 3 entries (assuming df has 3+ rows and columns)

On the other hand, .loc use named indices. Let's set up a data frame with strings as row and column labels:

df = pd.DataFrame(index=['a', 'b', 'c'], columns=['time', 'date', 'name'])

Then we can get the first row by

df.loc['a']     # equivalent to df.iloc[0]

and the second two rows of the 'date' column by

df.loc['b':, 'date']   # equivalent to df.iloc[1:, 1]

and so on. Now, it's probably worth pointing out that the default row and column indices for a DataFrame are integers from 0 and in this case iloc and loc would work in the same way. This is why your three examples are equivalent. If you had a non-numeric index such as strings or datetimes, df.loc[:5] would raise an error.

Also, you can do column retrieval just by using the data frame's __getitem__:

df['time']    # equivalent to df.loc[:, 'time']

Now suppose you want to mix position and named indexing, that is, indexing using names on rows and positions on columns (to clarify, I mean select from our data frame, rather than creating a data frame with strings in the row index and integers in the column index). This is where .ix comes in:

df.ix[:2, 'time']    # the first two rows of the 'time' column

I think it's also worth mentioning that you can pass boolean vectors to the loc method as well. For example:

 b = [True, False, True]
 df.loc[b] 

Will return the 1st and 3rd rows of df. This is equivalent to df[b] for selection, but it can also be used for assigning via boolean vectors:

df.loc[b, 'name'] = 'Mary', 'John'

How to refer environment variable in POM.xml?

You can use <properties> tag to define a custom variable and ${variable} pattern to use it

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <!-- define -->
    <properties>
        <property.name>1.0</property.name>
    </properties>

    <!-- using -->
    <version>${property.name}</version>

</project>

sys.argv[1] meaning in script

sys.argv is a list containing the script path and command line arguments; i.e. sys.argv[0] is the path of the script you're running and all following members are arguments.

MySQL CREATE TABLE IF NOT EXISTS in PHPmyadmin import

If you really want to insert this record, remove the `abuse_id` field and the corresponding value from the INSERTstatement :

INSERT INTO  `abuses` (  `user_id` ,  `abuser_username` ,  `comment` ,  `reg_date` , `auction_id` ) 
VALUES ( 100020,  'artictundra', 'I placed a bid for it more than an hour ago. It is still active. I thought I was supposed to get an email after 15 minutes.', 1338052850, 108625 ) ;

Select folder dialog WPF

Microsoft.Win32.OpenFileDialog is the standard dialog that any application on Windows uses. Your user won't be surprised by its appearance when you use WPF in .NET 4.0

The dialog was altered in Vista. WPF in .NET 3.0 and 3.5 still used the legacy dialog but that was fixed in .NET 4.0. I can only guess that you started this thread because you are seeing that old dialog. Which probably means you're actually running a program that is targeting 3.5. Yes, the Winforms wrapper did get the upgrade and shows the Vista version. System.Windows.Forms.OpenFileDialog class, you'll need to add a reference to System.Windows.Forms.

How to write log base(2) in c/c++

#define M_LOG2E 1.44269504088896340736 // log2(e)

inline long double log2(const long double x){
    return log(x) * M_LOG2E;
}

(multiplication may be faster than division)

Build android release apk on Phonegap 3.x CLI

In cordova 6.2.0

cd cordova/ #change to root cordova folder
platforms/android/cordova/clean #clean if you want
cordova build android --release -- --keystore="/path/to/keystore" --storePassword=password --alias=alias_name #password will be prompted if you have any

Previous answer:

According to cordova 5.0.0

{
     "android": {
         "release": {
             "keystore": "app-release-key.keystore",
             "alias": "alias_name"
         }
     }
 }

and run ./build --release --buildConfig build.json from directory platforms/android/cordova/

keystore file location is relative to platforms/android/cordova/, so in above configuration .keystore file and build.json are in same directory.

keytool -genkey -v -keystore app-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000

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

Perl 5.10+ contains the 'smart-match' operator ~~, which returns true if a certain element is contained in an array or hash, and false if it doesn't (see perlfaq4):

The nice thing is that it also supports regexes, meaning that your case-insensitive requirement can easily be taken care of:

use strict;
use warnings;
use 5.010;

my @array  = qw/aaa bbb/;
my $wanted = 'aAa';

say "'$wanted' matches!" if /$wanted/i ~~ @array;   # Prints "'aAa' matches!"

Coarse-grained vs fine-grained

In simple terms

  • Coarse-grained - larger components than fine-grained, large subcomponents. Simply wraps one or more fine-grained services together into a more coarse­-grained operation.
  • Fine-grained - smaller components of which the larger ones are composed, lower­level service

It is better to have more coarse-grained service operations, which are composed by fine-grained operations

enter image description here

Loop through all the resources in a .resx file

With the nuget package System.Resources.ResourceManager (v4.3.0) the ResourceSet and ResourceManager.GetResourceSet are not available.

Using the ResourceReader, as this post suggest: "C# - Cannot getting a string from ResourceManager (from satellite assembly)"

It's still possible to read the key/values of the resource file.

System.Reflection.Assembly resourceAssembly = System.Reflection.Assembly.Load(new System.Reflection.AssemblyName("YourAssemblyName"));
String[] manifests = resourceAssembly.GetManifestResourceNames(); 
using (ResourceReader reader = new ResourceReader(resourceAssembly.GetManifestResourceStream(manifests[0])))
{
   System.Collections.IDictionaryEnumerator dict = reader.GetEnumerator();
   while (dict.MoveNext())
   {
      String key = dict.Key as String;
      String value = dict.Value as String;
   }
}

Git: Remove committed file after push

  1. Get the hash code of last commit.

    • git log
  2. Revert the commit
    • git revert <hash_code_from_git_log>
  3. Push the changes
    • git push

check out in the GHR. you might get what ever you need, hope you this is useful

Get the system date and split day, month and year

You can do like follow:

 String date = DateTime.Now.Date.ToString();
    String Month = DateTime.Now.Month.ToString();
    String Year = DateTime.Now.Year.ToString();

On the place of datetime you can use your column..

Move_uploaded_file() function is not working

This answer is late but it might help someone like it helped me

Just ensure you have given the user permission for the destination file

sudo chown -R www-data:www-data /Users/George/Desktop/uploads/

Angular Directive refresh on parameter change

I hope this will help reloading/refreshing directive on value from parent scope

<html>

        <head>
            <!-- version 1.4.5 -->
            <script src="angular.js"></script>
        </head>

        <body ng-app="app" ng-controller="Ctrl">

            <my-test reload-on="update"></my-test><br>
            <button ng-click="update = update+1;">update {{update}}</button>
        </body>
        <script>
            var app = angular.module('app', [])
            app.controller('Ctrl', function($scope) {

                $scope.update = 0;
            });
            app.directive('myTest', function() {
                return {
                    restrict: 'AE',
                    scope: {
                        reloadOn: '='
                    },
                    controller: function($scope) {
                        $scope.$watch('reloadOn', function(newVal, oldVal) {
                            //  all directive code here
                            console.log("Reloaded successfully......" + $scope.reloadOn);
                        });
                    },
                    template: '<span>  {{reloadOn}} </span>'
                }
            });
        </script>


   </html>

Write a file in UTF-8 using FileWriter (Java)?

Ditch FileWriter and FileReader, which are useless exactly because they do not allow you to specify the encoding. Instead, use

new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)

and

new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);

Read data from a text file using Java

The reason your code skipped the last line was because you put fis.available() > 0 instead of fis.available() >= 0

eslint: error Parsing error: The keyword 'const' is reserved

ESLint defaults to ES5 syntax-checking. You'll want to override to the latest well-supported version of JavaScript.

Try adding a .eslintrc file to your project. Inside it:

{
    "parserOptions": {
        "ecmaVersion": 2017
    },

    "env": {
        "es6": true
    }
}

Hopefully this helps.

EDIT: I also found this example .eslintrc which might help.

Add leading zeroes to number in Java?

String.format (https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax)

In your case it will be:

String formatted = String.format("%03d", num);
  • 0 - to pad with zeros
  • 3 - to set width to 3

Execute script after specific delay using JavaScript

You can also use window.setInterval() to run some code repeatedly at a regular interval.

How to draw a graph in PHP?

You can use google's chart api to generate charts.

How to read from stdin with fgets()?

Assuming that you only want to read a single line, then use LINE_MAX, which is defined in <limits.h>:

#include <stdio.h>
#include <limits.h>
...
char line[LINE_MAX];
...
if (fgets(line, LINE_MAX, stdin) != NULL) {
...
}
...

How to remove close button on the jQuery UI dialog?

You can use CSS to hide the close button instead of JavaScript:

.ui-dialog-titlebar-close{
    display: none;
}

If you don't want to affect all the modals, you could use a rule like

.hide-close-btn .ui-dialog-titlebar-close{
    display: none;
}

And apply .hide-close-btn to the top node of the dialog

global variable for all controller and views

At first, a config file is appropriate for this kind of things but you may also use another approach, which is as given below (Laravel - 4):

// You can keep this in your filters.php file
App::before(function($request) {
    App::singleton('site_settings', function(){
        return Setting::all();
    });

    // If you use this line of code then it'll be available in any view
    // as $site_settings but you may also use app('site_settings') as well
    View::share('site_settings', app('site_settings'));
});

To get the same data in any controller you may use:

$site_settings = app('site_settings');

There are many ways, just use one or another, which one you prefer but I'm using the Container.

Type datetime for input parameter in procedure

In this part of your SP:

IF @DateFirst <> '' and @DateLast <> ''
   set @FinalSQL  = @FinalSQL
       + '  or convert (Date,DateLog) >=     ''' + @DateFirst
       + ' and convert (Date,DateLog) <=''' + @DateLast  

you are trying to concatenate strings and datetimes.

As the datetime type has higher priority than varchar/nvarchar, the + operator, when it happens between a string and a datetime, is interpreted as addition, not as concatenation, and the engine then tries to convert your string parts (' or convert (Date,DateLog) >= ''' and others) to datetime or numeric values. And fails.

That doesn't happen if you omit the last two parameters when invoking the procedure, because the condition evaluates to false and the offending statement isn't executed.

To amend the situation, you need to add explicit casting of your datetime variables to strings:

set @FinalSQL  = @FinalSQL
    + '  or convert (Date,DateLog) >=     ''' + convert(date, @DateFirst)
    + ' and convert (Date,DateLog) <=''' + convert(date, @DateLast)

You'll also need to add closing single quotes:

set @FinalSQL  = @FinalSQL
    + '  or convert (Date,DateLog) >=     ''' + convert(date, @DateFirst) + ''''
    + ' and convert (Date,DateLog) <=''' + convert(date, @DateLast) + ''''

Create table using Javascript

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Insert title here</title>
    </head>
    <body>
        <table id="myTable" cellpadding="2" cellspacing="2" border="1" onclick="tester()"></table>
        <script>
            var student;
            for (var j = 0; j < 10; j++) {
                student = {
                    name: "Name" + j,
                    rank: "Rank" + j,
                    stuclass: "Class" + j,
                };
                var table = document.getElementById("myTable");
                var row = table.insertRow(j);
                var cell1 = row.insertCell(0);
                var cell2 = row.insertCell(1);
                var cell3 = row.insertCell(2);

                cell1.innerHTML = student.name,
                cell2.innerHTML = student.rank,
                cell3.innerHTML = student.stuclass;
            }
        </script>
    </body>
</html>

handle textview link click in my android app

Here is a more generic solution based on @Arun answer

public abstract class TextViewLinkHandler extends LinkMovementMethod {

    public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
        if (event.getAction() != MotionEvent.ACTION_UP)
            return super.onTouchEvent(widget, buffer, event);

        int x = (int) event.getX();
        int y = (int) event.getY();

        x -= widget.getTotalPaddingLeft();
        y -= widget.getTotalPaddingTop();

        x += widget.getScrollX();
        y += widget.getScrollY();

        Layout layout = widget.getLayout();
        int line = layout.getLineForVertical(y);
        int off = layout.getOffsetForHorizontal(line, x);

        URLSpan[] link = buffer.getSpans(off, off, URLSpan.class);
        if (link.length != 0) {
            onLinkClick(link[0].getURL());
        }
        return true;
    }

    abstract public void onLinkClick(String url);
}

To use it just implement onLinkClick of TextViewLinkHandler class. For instance:

    textView.setMovementMethod(new TextViewLinkHandler() {
        @Override
        public void onLinkClick(String url) {
            Toast.makeText(textView.getContext(), url, Toast.LENGTH_SHORT).show();
        }
    });

Bash script error [: !=: unary operator expected

Or for what seems like rampant overkill, but is actually simplistic ... Pretty much covers all of your cases, and no empty string or unary concerns.

In the case the first arg is '-v', then do your conditional ps -ef, else in all other cases throw the usage.

#!/bin/sh
case $1 in
  '-v') if [ "$1" = -v ]; then
         echo "`ps -ef | grep -v '\['`"
        else
         echo "`ps -ef | grep '\[' | grep root`"
        fi;;
     *) echo "usage: $0 [-v]"
        exit 1;; #It is good practice to throw a code, hence allowing $? check
esac

If one cares not where the '-v' arg is, then simply drop the case inside a loop. The would allow walking all the args and finding '-v' anywhere (provided it exists). This means command line argument order is not important. Be forewarned, as presented, the variable arg_match is set, thus it is merely a flag. It allows for multiple occurrences of the '-v' arg. One could ignore all other occurrences of '-v' easy enough.

#!/bin/sh

usage ()
 {
  echo "usage: $0 [-v]"
  exit 1
 }

unset arg_match

for arg in $*
 do
  case $arg in
    '-v') if [ "$arg" = -v ]; then
           echo "`ps -ef | grep -v '\['`"
          else
           echo "`ps -ef | grep '\[' | grep root`"
          fi
          arg_match=1;; # this is set, but could increment.
       *) ;;
  esac
done

if [ ! $arg_match ]
 then
  usage
fi

But, allow multiple occurrences of an argument is convenient to use in situations such as:

$ adduser -u:sam -s -f -u:bob -trace -verbose

We care not about the order of the arguments, and even allow multiple -u arguments. Yes, it is a simple matter to also allow:

$ adduser -u sam -s -f -u bob -trace -verbose

presentViewController and displaying navigation bar

One solution

DetailViewController *controller = [[DetailViewController alloc] initWithNibName:nil                                                                                 
                                        bundle:[NSBundle mainBundle]];  

UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:controller];
navController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
navController.modalPresentationStyle = UIModalPresentationCurrentContext;



[self.navigationController presentViewController:navController 
                                        animated:YES 
                                        completion:nil];

Cannot find module '@angular/compiler'

This command is working fine for me ubuntu 16.04 LTS:

npm install --save-dev @angular/cli@latest

Does an HTTP Status code of 0 have any meaning?

Short Answer

It's not a HTTP response code, but it is documented by WhatWG as a valid value for the status attribute of an XMLHttpRequest or a Fetch response.

Broadly speaking, it is a default value used when there is no real HTTP status code to report and/or an error occurred sending the request or receiving the response. Possible scenarios where this is the case include, but are not limited to:

  • The request hasn't yet been sent, or was aborted.
  • The browser is still waiting to receive the response status and headers.
  • The connection dropped during the request.
  • The request timed out.
  • The request encountered an infinite redirect loop.
  • The browser knows the response status, but you're not allowed to access it due to security restrictions related to the Same-origin Policy.

Long Answer

First, to reiterate: 0 is not a HTTP status code. There's a complete list of them in RFC 7231 Section 6.1, that doesn't include 0, and the intro to section 6 states clearly that

The status-code element is a three-digit integer code

which 0 is not.

However, 0 as a value of the .status attribute of an XMLHttpRequest object is documented, although it's a little tricky to track down all the relevant details. We begin at https://xhr.spec.whatwg.org/#the-status-attribute, documenting the .status attribute, which simply states:

The status attribute must return the response’s status.

That may sound vacuous and tautological, but in reality there is information here! Remember that this documentation is talking here about the .response attribute of an XMLHttpRequest, not a response, so this tells us that the definition of the status on an XHR object is deferred to the definition of a response's status in the Fetch spec.

But what response object? What if we haven't actually received a response yet? The inline link on the word "response" takes us to https://xhr.spec.whatwg.org/#response, which explains:

An XMLHttpRequest has an associated response. Unless stated otherwise it is a network error.

So the response whose status we're getting is by default a network error. And by searching for everywhere the phrase "set response to" is used in the XHR spec, we can see that it's set in five places:

Looking in the Fetch standard, we can see that:

A network error is a response whose status is always 0

so we can immediately tell that we'll see a status of 0 on an XHR object in any of the cases where the XHR spec says the response should be set to a network error. (Interestingly, this includes the case where the body's stream gets "errored", which the Fetch spec tells us can happen during parsing the body after having received the status - so in theory I suppose it is possible for an XHR object to have its status set to 200, then encounter an out-of-memory error or something while receiving the body and so change its status back to 0.)

We also note in the Fetch standard that a couple of other response types exist whose status is defined to be 0, whose existence relates to cross-origin requests and the same-origin policy:

An opaque filtered response is a filtered response whose ... status is 0...

An opaque-redirect filtered response is a filtered response whose ... status is 0...

(various other details about these two response types omitted).

But beyond these, there are also many cases where the Fetch algorithm (rather than the XHR spec, which we've already looked at) calls for the browser to return a network error! Indeed, the phrase "return a network error" appears 40 times in the Fetch standard. I will not try to list all 40 here, but I note that they include:

  • The case where the request's scheme is unrecognised (e.g. trying to send a request to madeupscheme://foobar.com)
  • The wonderfully vague instruction "When in doubt, return a network error." in the algorithms for handling ftp:// and file:// URLs
  • Infinite redirects: "If request’s redirect count is twenty, return a network error."
  • A bunch of CORS-related issues, such as "If httpRequest’s response tainting is not "cors" and the cross-origin resource policy check with request and response returns blocked, then return a network error."
  • Connection failures: "If connection is failure, return a network error."

In other words: whenever something goes wrong other than getting a real HTTP error status code like a 500 or 400 from the server, you end up with a status attribute of 0 on your XHR object or Fetch response object in the browser. The number of possible specific causes enumerated in spec is vast.

Finally: if you're interested in the history of the spec for some reason, note that this answer was completely rewritten in 2020, and that you may be interested in the previous revision of this answer, which parsed essentially the same conclusions out of the older (and much simpler) W3 spec for XHR, before these were replaced by the more modern and more complicated WhatWG specs this answers refers to.

Problems with local variable scope. How to solve it?

You have a scope problem indeed, because statement is a local method variable defined here:

protected void createContents() {
    ...
    Statement statement = null; // local variable
    ...
     btnInsert.addMouseListener(new MouseAdapter() { // anonymous inner class
        @Override
        public void mouseDown(MouseEvent e) {
            ...
            try {
                statement.executeUpdate(query); // local variable out of scope here
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            ...
    });
}

When you try to access this variable inside mouseDown() method you are trying to access a local variable from within an anonymous inner class and the scope is not enough. So it definitely must be final (which given your code is not possible) or declared as a class member so the inner class can access this statement variable.

Sources:


How to solve it?

You could...

Make statement a class member instead of a local variable:

public class A1 { // Note Java Code Convention, also class name should be meaningful   
    private Statement statement;
    ...
}

You could...

Define another final variable and use this one instead, as suggested by @HotLicks:

protected void createContents() {
    ...
    Statement statement = null;
    try {
        statement = connect.createStatement();
        final Statement innerStatement = statement;
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    ...
}

But you should...

Reconsider your approach. If statement variable won't be used until btnInsert button is pressed then it doesn't make sense to create a connection before this actually happens. You could use all local variables like this:

btnInsert.addMouseListener(new MouseAdapter() {
   @Override
   public void mouseDown(MouseEvent e) {
       try {
           Class.forName("com.mysql.jdbc.Driver");
           try (Connection connect = DriverManager.getConnection(...);
                Statement statement = connect.createStatement()) {

                // execute the statement here

           } catch (SQLException ex) {
               ex.printStackTrace();
           }

       } catch (ClassNotFoundException ex) {
           e.printStackTrace();
       }
});

Render partial from different folder (not shared)

For a user control named myPartial.ascx located at Views/Account folder write like this:

<%Html.RenderPartial("~/Views/Account/myPartial.ascx");%>

SSIS Text was truncated with status value 4

I suspect the or one or more characters had no match in the target code page part of the error.

If you remove the rows with values in that column, does it load? Can you identify, in other words, the rows which cause the package to fail? It could be the data is too long, or it could be that there's some funky character in there SQL Server doesn't like.

Best practices when running Node.js with port 80 (Ubuntu / Linode)

Drop root privileges after you bind to port 80 (or 443).

This allows port 80/443 to remain protected, while still preventing you from serving requests as root:

function drop_root() {
    process.setgid('nobody');
    process.setuid('nobody');
}

A full working example using the above function:

var process = require('process');
var http = require('http');
var server = http.createServer(function(req, res) {
    res.write("Success!");
    res.end();
});

server.listen(80, null, null, function() {
    console.log('User ID:',process.getuid()+', Group ID:',process.getgid());
    drop_root();
    console.log('User ID:',process.getuid()+', Group ID:',process.getgid());
});

See more details at this full reference.

Java ArrayList - how can I tell if two lists are equal, order not mattering?

This is based on @cHao solution. I included several fixes and performance improvements. This runs roughly twice as fast the equals-ordered-copy solution. Works for any collection type. Empty collections and null are regarded as equal. Use to your advantage ;)

/**
 * Returns if both {@link Collection Collections} contains the same elements, in the same quantities, regardless of order and collection type.
 * <p>
 * Empty collections and {@code null} are regarded as equal.
 */
public static <T> boolean haveSameElements(Collection<T> col1, Collection<T> col2) {
    if (col1 == col2)
        return true;

    // If either list is null, return whether the other is empty
    if (col1 == null)
        return col2.isEmpty();
    if (col2 == null)
        return col1.isEmpty();

    // If lengths are not equal, they can't possibly match
    if (col1.size() != col2.size())
        return false;

    // Helper class, so we don't have to do a whole lot of autoboxing
    class Count
    {
        // Initialize as 1, as we would increment it anyway
        public int count = 1;
    }

    final Map<T, Count> counts = new HashMap<>();

    // Count the items in col1
    for (final T item : col1) {
        final Count count = counts.get(item);
        if (count != null)
            count.count++;
        else
            // If the map doesn't contain the item, put a new count
            counts.put(item, new Count());
    }

    // Subtract the count of items in col2
    for (final T item : col2) {
        final Count count = counts.get(item);
        // If the map doesn't contain the item, or the count is already reduced to 0, the lists are unequal 
        if (count == null || count.count == 0)
            return false;
        count.count--;
    }

    // At this point, both collections are equal.
    // Both have the same length, and for any counter to be unequal to zero, there would have to be an element in col2 which is not in col1, but this is checked in the second loop, as @holger pointed out.
    return true;
}

Can I display the value of an enum with printf()?

As a string, no. As an integer, %d.

Unless you count:

static char* enumStrings[] = { /* filler 0's to get to the first value, */
                               "enum0", "enum1", 
                               /* filler for hole in the middle: ,0 */
                               "enum2", "enum3", .... };

...

printf("The value is %s\n", enumStrings[thevalue]);

This won't work for something like an enum of bit masks. At that point, you need a hash table or some other more elaborate data structure.

msvcr110.dll is missing from computer error while installing PHP

To identify which x86/x64 version of VC is needed:

Go to IIS Manager > Handler Mappings > right click then Edit *.php path. In the "Executable (optional)" field note in which version of Program Files is the php-cgi.exe installed.

How to hide the title bar for an Activity in XML with existing custom theme

Or if you want to hide/show the title bar at any point:

private void toggleFullscreen(boolean fullscreen)
{
    WindowManager.LayoutParams attrs = getWindow().getAttributes();
    if (fullscreen)
    {
        attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
    }
    else
    {
        attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
    }
    getWindow().setAttributes(attrs);
}

Serializing class instance to JSON

The basic problem is that the JSON encoder json.dumps() only knows how to serialize a limited set of object types by default, all built-in types. List here: https://docs.python.org/3.3/library/json.html#encoders-and-decoders

One good solution would be to make your class inherit from JSONEncoder and then implement the JSONEncoder.default() function, and make that function emit the correct JSON for your class.

A simple solution would be to call json.dumps() on the .__dict__ member of that instance. That is a standard Python dict and if your class is simple it will be JSON serializable.

class Foo(object):
    def __init__(self):
        self.x = 1
        self.y = 2

foo = Foo()
s = json.dumps(foo) # raises TypeError with "is not JSON serializable"

s = json.dumps(foo.__dict__) # s set to: {"x":1, "y":2}

The above approach is discussed in this blog posting:

    Serializing arbitrary Python objects to JSON using __dict__

ASP.NET MVC Html.DropDownList SelectedValue

The code in the previous MVC 3 post does not work but it is a good start. I will fix it. I have tested this code and it works in MVC 3 Razor C# This code uses the ViewModel pattern to populate a property that returns a List<SelectListItem>.

The Model class

public class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }
}

The ViewModel class

using System.Web.Mvc;

public class ProductListviewModel
{
    public List<SelectListItem> Products { get; set; }
}

The Controller Method

public ViewResult List()
{
    var productList = new List<SelectListItem>();

    foreach (Product p in Products)
    {
        productList.Add(new SelectListItem
        {
            Value = p.ProductId.ToString(),
            Text = "Product: " + p.Name + " " + p.Price.ToString(),
            // To set the selected item use the following code 
            // Note: you should not set every item to selected
            Selected = true
        });
    }

    ProductListViewModel productListVM = new ProductListViewModeld();

    productListVM.Products = productList;

    return View(productListVM);
}

The view

@model MvcApp.ViewModels.ProductListViewModel

@using (Html.BeginForm())
{
    @Html.DropDownList("Products", Model.Products)
}

The HTML output will be something like

<select id="Products" name="Products">
    <option value="3">Product: Widget 10.00</option>
    <option value="4">Product: Gadget 5.95</option>
</select>

depending on how you format the output. I hope this helps. The code does work.

Run PHP function on html button click

If you want to make a server request you should use AJAX, so you can send your desired parameters to the server and it can run whatever php you want with these parameters.

Example with pure javascript:

<input type="text" id="name" value="..."/>
<input type="text" id="location" value="..."/>
<input type="button" onclick="ajaxFunction();" value="Submit" />
<div id="ajaxDiv"></div>
<script type="text/javascript">    
    function ajaxFunction(){
        var ajaxRequest;  // The variable that makes Ajax possible!

        try{
            // Opera 8.0+, Firefox, Safari
            ajaxRequest = new XMLHttpRequest();
        } catch (e){
            // Internet Explorer Browsers
            try{
                ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try{
                    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e){
                    // Something went wrong
                    alert("Your browser broke!");
                    return false;
                }
            }
        }
        // Create a function that will receive data sent from the server
        ajaxRequest.onreadystatechange = function(){
            if(ajaxRequest.readyState == 4){
                var ajaxDisplay = document.getElementById('ajaxDiv');
                ajaxDisplay.innerHTML = ajaxRequest.responseText;
            }
        }
        var name = document.getElementById('name').value;
        var location = document.getElementById('location').value;
        var queryString = "?name=" + name + "&location=" + location;
        ajaxRequest.open("POST", "some.php" + queryString, true);
        ajaxRequest.send(null); 
    }
</script>

Example with jQuery Ajax: http://api.jquery.com/jQuery.ajax/

$.ajax({
  type: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" }
}).done(function( msg ) {
  alert( "Data Saved: " + msg );
});

You can have one file with functions called for example functions.php

functions.php

<?php
  myFunction($Name, $Location) {
      // etc...
  }
  myFunction2() {
  }
  // ... many functions
?>

some.php

<?php include("functions.php");    
$Name = $_POST['name'];
$Location = $_POST['location'];

myFunction($Name, $Location);

// make what you want with these variables...?>

How to create Password Field in Model Django

I thinks it is vary helpful way.

models.py

from django.db import models
class User(models.Model):
    user_name = models.CharField(max_length=100)
    password = models.CharField(max_length=32)

forms.py

from django import forms
from Admin.models import *
class User_forms(forms.ModelForm):
    class Meta:
        model= User
        fields=[
           'user_name',
           'password'
            ]
       widgets = {
      'password': forms.PasswordInput()
         }

Detect browser or tab closing

I have tried all above solutions, none of them really worked for me, specially because there are some Telerik components in my project which have 'Close' button for popup windows, and it calls 'beforeunload' event. Also, button selector does not work properly when you have Telerik grid in your page (I mean buttons inside the grid) So, I couldn't use any of above suggestions. Finally this is the solution worked for me. I have added an onUnload event on the body tag of _Layout.cshtml. Something like this:

<body onUnload="LogOff()">

and then add the LogOff function to redirect to Account/LogOff which is a built-in method in Asp.Net MVC. Now, when I close the browser or tab, it redirect to LogOff method and user have to login when returns. I have tested it in both Chrome & Firefox. And it works!

  function LogOff() {
        $.ajax({
            url: "/Account/LogOff",
            success: function (result) {

                                        }
               });
       }

How do I kill an Activity when the Back button is pressed?

public boolean onKeyDown(int keycode, KeyEvent event) {
    if (keycode == KeyEvent.KEYCODE_BACK) {
        moveTaskToBack(true);
    }
    return super.onKeyDown(keycode, event);
}

My app closed with above code.

How can I pass a member function where a free function is expected?

Not sure why this incredibly simple solution has been passed up:

#include <stdio.h>

class aClass
{
public:
    void aTest(int a, int b)
    {
        printf("%d + %d = %d\n", a, b, a + b);
    }
};

template<class C>
void function1(void (C::*function)(int, int), C& c)
{
    (c.*function)(1, 1);
}
void function1(void (*function)(int, int)) {
  function(1, 1);
}

void test(int a,int b)
{
    printf("%d - %d = %d\n", a , b , a - b);
}

int main (int argc, const char* argv[])
{
    aClass a;

    function1(&test);
    function1<aClass>(&aClass::aTest, a);
    return 0;
}

Output:

1 - 1 = 0
1 + 1 = 2

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

jQuery - select all text from a textarea

Slightly shorter jQuery version:

$('your-element').focus(function(e) {
  e.target.select();
  jQuery(e.target).one('mouseup', function(e) {
    e.preventDefault();
  });
});

It handles the Chrome corner case correctly. See http://jsfiddle.net/Ztyx/XMkwm/ for an example.

How Do I Make Glyphicons Bigger? (Change Size?)

For ex .. add class:

btn-lg - LARGE

btn-sm - SMALL

btn-xs - Very small

<button type=button class="btn btn-default btn-lg">
<span class="glyphicon glyphicon-star" aria-hidden=true></span> Star
</button> 

<button type=button class="btn btn-default">
<span class="glyphicon glyphicon-star" aria-hidden=true></span>Star
</button>

 <button type=button class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-star" aria-hidden=true></span> Star
</button> 

<button type=button class="btn btn-default btn-xs">
<span class="glyphicon glyphicon-star" aria-hidden=true></span> Star
</button> 

Ref link Bootstrap : Glyphicons Bootstrap

Cloning an array in Javascript/Typescript

It looks like you may have made a mistake as to where you are doing the copy of an Array. Have a look at my explanation below and a slight modification to the code which should work in helping you reset the data to its previous state.

In your example i can see the following taking place:

  • you are doing a request to get generic items
  • after you get the data you set the results to the this.genericItems
  • directly after that you set the backupData as the result

Am i right in thinking you don't want the 3rd point to happen in that order?

Would this be better:

  • you do the data request
  • make a backup copy of what is current in this.genericItems
  • then set genericItems as the result of your request

Try this:

getGenericItems(selected: Item) {
  this.itemService.getGenericItems(selected).subscribe(
    result => {
       // make a backup before you change the genericItems
       this.backupData = this.genericItems.slice();

       // now update genericItems with the results from your request
       this.genericItems = result;
    });
  }

Redirect stderr and stdout in Bash

For tcsh, I have to use the following command :

command >& file

If use command &> file , it will give "Invalid null command" error.

How do I get the base URL with PHP?

   $base_url="http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["REQUEST_URI"].'?').'/';

Usage:

print "<script src='{$base_url}js/jquery.min.js'/>";

onclick event pass <li> id or value

Try this:

<li onclick="getPaging(this.id)" id="1">1</li>
<li onclick="getPaging(this.id)" id="2">2</li>


function getPaging(str)
{
    $("#loading-content").load("dataSearch.php?"+str, hideLoader);
}

Confirmation dialog on ng-click - AngularJS

In today's date this solution works for me:

/**
 * A generic confirmation for risky actions.
 * Usage: Add attributes: ng-really-message="Are you sure"? ng-really-click="takeAction()" function
 */
angular.module('app').directive('ngReallyClick', [function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('click', function() {
                var message = attrs.ngReallyMessage;
                if (message && confirm(message)) {
                    scope.$apply(attrs.ngReallyClick);
                }
            });
        }
    }
}]);

Credits:https://gist.github.com/asafge/7430497#file-ng-really-js

SELECT with LIMIT in Codeigniter

For further visitors:

// Executes: SELECT * FROM mytable LIMIT 10 OFFSET 20
// get([$table = ''[, $limit = NULL[, $offset = NULL]]])
$query = $this->db->get('mytable', 10, 20);

// get_where sample, 
$query = $this->db->get_where('mytable', array('id' => $id), 10, 20);

// Produces: LIMIT 10
$this->db->limit(10);  

// Produces: LIMIT 10 OFFSET 20
// limit($value[, $offset = 0])
$this->db->limit(10, 20);

How do Python functions handle the types of the parameters that you pass in?

You never specify the type; Python has the concept of duck typing; basically the code that processes the parameters will make certain assumptions about them - perhaps by calling certain methods that a parameter is expected to implement. If the parameter is of the wrong type, then an exception will be thrown.

In general it is up to your code to ensure that you are passing around objects of the proper type - there is no compiler to enforce this ahead of time.

Reset C int array to zero : the fastest way?

This question, although rather old, needs some benchmarks, as it asks for not the most idiomatic way, or the way that can be written in the fewest number of lines, but the fastest way. And it is silly to answer that question without some actual testing. So I compared four solutions, memset vs. std::fill vs. ZERO of AnT's answer vs a solution I made using AVX intrinsics.

Note that this solution is not generic, it only works on data of 32 or 64 bits. Please comment if this code is doing something incorrect.

#include<immintrin.h>
#define intrin_ZERO(a,n){\
size_t x = 0;\
const size_t inc = 32 / sizeof(*(a));/*size of 256 bit register over size of variable*/\
for (;x < n-inc;x+=inc)\
    _mm256_storeu_ps((float *)((a)+x),_mm256_setzero_ps());\
if(4 == sizeof(*(a))){\
    switch(n-x){\
    case 3:\
        (a)[x] = 0;x++;\
    case 2:\
        _mm_storeu_ps((float *)((a)+x),_mm_setzero_ps());break;\
    case 1:\
        (a)[x] = 0;\
        break;\
    case 0:\
        break;\
    };\
}\
else if(8 == sizeof(*(a))){\
switch(n-x){\
    case 7:\
        (a)[x] = 0;x++;\
    case 6:\
        (a)[x] = 0;x++;\
    case 5:\
        (a)[x] = 0;x++;\
    case 4:\
        _mm_storeu_ps((float *)((a)+x),_mm_setzero_ps());break;\
    case 3:\
        (a)[x] = 0;x++;\
    case 2:\
        ((long long *)(a))[x] = 0;break;\
    case 1:\
        (a)[x] = 0;\
        break;\
    case 0:\
        break;\
};\
}\
}

I will not claim that this is the fastest method, since I am not a low level optimization expert. Rather it is an example of a correct architecture dependent implementation that is faster than memset.

Now, onto the results. I calculated performance for size 100 int and long long arrays, both statically and dynamically allocated, but with the exception of msvc, which did a dead code elimination on static arrays, the results were extremely comparable, so I will show only dynamic array performance. Time markings are ms for 1 million iterations, using time.h's low precision clock function.

clang 3.8 (Using the clang-cl frontend, optimization flags= /OX /arch:AVX /Oi /Ot)

int:
memset:      99
fill:        97
ZERO:        98
intrin_ZERO: 90

long long:
memset:      285
fill:        286
ZERO:        285
intrin_ZERO: 188

gcc 5.1.0 (optimization flags: -O3 -march=native -mtune=native -mavx):

int:
memset:      268
fill:        268
ZERO:        268
intrin_ZERO: 91
long long:
memset:      402
fill:        399
ZERO:        400
intrin_ZERO: 185

msvc 2015 (optimization flags: /OX /arch:AVX /Oi /Ot):

int
memset:      196
fill:        613
ZERO:        221
intrin_ZERO: 95
long long:
memset:      273
fill:        559
ZERO:        376
intrin_ZERO: 188

There is a lot interesting going on here: llvm killing gcc, MSVC's typical spotty optimizations (it does an impressive dead code elimination on static arrays and then has awful performance for fill). Although my implementation is significantly faster, this may only be because it recognizes that bit clearing has much less overhead than any other setting operation.

Clang's implementation merits more looking at, as it is significantly faster. Some additional testing shows that its memset is in fact specialized for zero--non zero memsets for 400 byte array are much slower (~220ms) and are comparable to gcc's. However, the nonzero memsetting with an 800 byte array makes no speed difference, which is probably why in that case, their memset has worse performance than my implementation--the specialization is only for small arrays, and the cuttoff is right around 800 bytes. Also note that gcc 'fill' and 'ZERO' are not optimizing to memset (looking at generated code), gcc is simply generating code with identical performance characteristics.

Conclusion: memset is not really optimized for this task as well as people would pretend it is (otherwise gcc and msvc and llvm's memset would have the same performance). If performance matters then memset should not be a final solution, especially for these awkward medium sized arrays, because it is not specialized for bit clearing, and it is not hand optimized any better than the compiler can do on its own.

How to use the CancellationToken property?

@BrainSlugs83

You shouldn't blindly trust everything posted on stackoverflow. The comment in Jens code is incorrect, the parameter doesn't control whether exceptions are thrown or not.

MSDN is very clear what that parameter controls, have you read it? http://msdn.microsoft.com/en-us/library/dd321703(v=vs.110).aspx

If throwOnFirstException is true, an exception will immediately propagate out of the call to Cancel, preventing the remaining callbacks and cancelable operations from being processed. If throwOnFirstException is false, this overload will aggregate any exceptions thrown into an AggregateException, such that one callback throwing an exception will not prevent other registered callbacks from being executed.

The variable name is also wrong because Cancel is called on CancellationTokenSource not the token itself and the source changes state of each token it manages.

Display tooltip on Label's hover?

If you also have jQuery UI, you can add this:

$(document).ready(function () {
  $(document).tooltip();
});

You then need a title instead of a hidden input. RGraham already posted an answer doing this for you :P

What are these ^M's that keep showing up in my files in emacs?

In git-config, set core.autocrlf to true to make git automatically convert line endings correctly for your platform, e.g. run this command for a global setting:

git config --global core.autocrlf true

Optimum way to compare strings in JavaScript?

You can use the localeCompare() method.

string_a.localeCompare(string_b);

/* Expected Returns:

 0:  exact match

-1:  string_a < string_b

 1:  string_a > string_b

 */

Further Reading:

How do I convert a string to a number in PHP?

You don't typically need to do this, since PHP will coerce the type for you in most circumstances. For situations where you do want to explicitly convert the type, cast it:

$num = "3.14";
$int = (int)$num;
$float = (float)$num;

How to convert index of a pandas dataframe into a column?

If you want to use the reset_index method and also preserve your existing index you should use:

df.reset_index().set_index('index', drop=False)

or to change it in place:

df.reset_index(inplace=True)
df.set_index('index', drop=False, inplace=True)

For example:

print(df)
          gi  ptt_loc
0  384444683      593
4  384444684      594
9  384444686      596

print(df.reset_index())
   index         gi  ptt_loc
0      0  384444683      593
1      4  384444684      594
2      9  384444686      596

print(df.reset_index().set_index('index', drop=False))
       index         gi  ptt_loc
index
0          0  384444683      593
4          4  384444684      594
9          9  384444686      596

And if you want to get rid of the index label you can do:

df2 = df.reset_index().set_index('index', drop=False)
df2.index.name = None
print(df2)
   index         gi  ptt_loc
0      0  384444683      593
4      4  384444684      594
9      9  384444686      596

Could not find tools.jar. Please check that C:\Program Files\Java\jre1.8.0_151 contains a valid JDK installation

What I did was I uninstalled Java from my PC, and then downloaded and installed JDK again from Oracle. After this it worked perfectly. I think the problem was because the JRE and JDK update version were different from each other.

Is there a limit on how much JSON can hold?

There is no fixed limit on how large a JSON data block is or any of the fields.

There are limits to how much JSON the JavaScript implementation of various browsers can handle (e.g. around 40MB in my experience). See this question for example.

A simple jQuery form validation script

you can use jquery validator for that but you need to add jquery.validate.js and jquery.form.js file for that. after including validator file define your validation something like this.

<script type="text/javascript">
$(document).ready(function(){
    $("#formID").validate({
    rules :{
        "data[User][name]" : {
            required : true
        }
    },
    messages :{
        "data[User][name]" : {
            required : 'Enter username'
        }
    }
    });
});
</script>

You can see required : true same there is many more property like for email you can define email : true for number number : true

Get all unique values in a JavaScript array (remove duplicates)

You can also use sugar.js:

[1,2,2,3,1].unique() // => [1,2,3]

[{id:5, name:"Jay"}, {id:6, name:"Jay"}, {id: 5, name:"Jay"}].unique('id') 
  // => [{id:5, name:"Jay"}, {id:6, name:"Jay"}]

Python: list of lists

The list variable (which I would recommend to rename to something more sensible) is a reference to a list object, which can be changed.

On the line

listoflists.append((list, list[0]))

You actually are only adding a reference to the object reference by the list variable. You've got multiple possibilities to create a copy of the list, so listoflists contains the values as you seem to expect:

Use the copy library

import copy
listoflists.append((copy.copy(list), list[0]))

use the slice notation

listoflists.append((list[:], list[0]))

How to set a parameter in a HttpServletRequest?

As mentioned in the previous posts, using an HttpServletReqiestWrapper is the way to go, however the missed part in those posts was that apart from overriding the method getParameter(), you should also override other parameter related methods to produce a consistent response. e.g. the value of a param added by the custom request wrapper should also be included in the parameters map returned by the method getParameterMap(). Here is an example:

   public class AddableHttpRequest extends HttpServletRequestWrapper {

    /** A map containing additional request params this wrapper adds to the wrapped request */
    private final Map<String, String> params = new HashMap<>();

    /**
     * Constructs a request object wrapping the given request.
     * @throws java.lang.IllegalArgumentException if the request is null
     */
    AddableHttpRequest(final HttpServletRequest request) {
        super(request)
    }

    @Override
    public String getParameter(final String name) {
        // if we added one with the given name, return that one
        if ( params.get( name ) != null ) {
            return params.get( name );
        } else {
            // otherwise return what's in the original request
            return super.getParameter(name);
        }
    }


    /**
     * *** OVERRIDE THE METHODS BELOW TO REFLECT PARAMETERS ADDED BY THIS WRAPPER ****
     */

    @Override
    public Map<String, String> getParameterMap() {
        // defaulf impl, should be overridden for an approprivate map of request params
        return super.getParameterMap();
    }

    @Override
    public Enumeration<String> getParameterNames() {
        // defaulf impl, should be overridden for an approprivate map of request params names
        return super.getParameterNames();
    }

    @Override
    public String[] getParameterValues(final String name) {
        // defaulf impl, should be overridden for an approprivate map of request params values
        return super.getParameterValues(name);
    }
}

how to find host name from IP with out login to the host

  • For Windows, try:

    NBTSTAT -A 10.100.3.104
    

    or

    ping -a 10.100.3.104
    
  • For Linux, try:

    nmblookup -A 10.100.3.104
    

They are almost same.

How to generate UML diagrams (especially sequence diagrams) from Java code?

I would recommend EclipseUML from Omondo for general usage, although I did experience some problems a few months back, with my web projects. They had a free edition at one point in time, but that is supposedly no longer promoted.

If you are really keen on reverse engineering sequence diagrams from source code, I would recommend jTracert.

As far as Eclipse projects themselves are concerned, the Eclipse UML2 Tools project might support reverse engineering, although I've have never seen its use in practice.

The MoDisco (Model Discovery) project Eclipse GMT project seems to be clearer in achieving your objective. The list of technology specific tools would be a good place to start with.

Ignore Typescript Errors "property does not exist on value of type"

A quick fix where nothing else works:

const a.b = 5 // error

const a['b'] = 5 // error if ts-lint rule no-string-literal is enabled

const B = 'b'
const a[B] = 5 // always works

Not good practice but provides a solution without needing to turn off no-string-literal

How to count days between two dates in PHP?

You can use date_diff to calculate the difference between two dates:

$date1 = date_create("2013-03-15");
$date2 = date_create("2013-12-12");
$diff =  date_diff($date1 , $date2);
echo  $diff->format("%R%a days");

MVC DateTime binding with incorrect date format

public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    var str = controllerContext.HttpContext.Request.QueryString[bindingContext.ModelName];
    if (string.IsNullOrEmpty(str)) return null;
    var date = DateTime.ParseExact(str, "dd.MM.yyyy", null);
    return date;
}

How do I remove a submodule?

With git 2.17 and above it's just:

git submodule deinit -f {module_name}
git add {module_name}
git commit

Angularjs Template Default Value if Binding Null / Undefined (With Filter)

Turns out all I needed to do was wrap the left-hand side of the expression in soft brackets:

<span class="gallery-date">{{(gallery.date | date:'mediumDate') || "Various"}}</span>

Current Subversion revision command

  1. First of all svn status has the revision number, you can read it from there.

  2. Also, each file that you store in SVN can store the revision number in itself -- add the $Rev$ keyword to your file and run propset: svn propset svn:keywords "Revision" file

  3. Finally, the revision number is also in .svn/entries file, fourth line

Now each time you checkout that file, it will have the revision in itself.

Scrolling to an Anchor using Transition/CSS3

While some of the answers were very useful and informative, I thought I would write down the answer I came up with. The answer from Alex was very good, it is however limited in the sense that the height of the div needs to be hard coded in the CSS.

So the solution I came up with uses JS (no jQuery) and is actually a stripped down version (almost to the minimum) of over solutions to solve similar problems I found on Statckoverflow:

HTML

<div class="header">
    <p class="menu"><a href="#S1" onclick="test('S1'); return false;">S1</a></p>
    <p class="menu"><a href="#S2" onclick="test('S2'); return false;">S2</a></p>
    <p class="menu"><a href="#S3" onclick="test('S3'); return false;">S3</a></p>
    <p class="menu"><a href="#S4" onclick="test('S4'); return false;">S3</a></p>
</div>
<div style="width: 100%;">
    <div id="S1" class="curtain">
    blabla
    </div>
    <div id="S2" class="curtain">
    blabla
    </div>
    <div id="S3" class="curtain">
    blabla
    </div>
    <div id="S4" class="curtain">
    blabla
    </div>
 </div>

NOTE THE "RETURN FALSE;" in the on click call. This is important if you want to avoid having your browser jumping to the link itself (and let the effect being managed by your JS).

JS code:

<script>
function scrollTo(to, duration) {
    if (document.body.scrollTop == to) return;
    var diff = to - document.body.scrollTop;
    var scrollStep = Math.PI / (duration / 10);
    var count = 0, currPos;
    start = element.scrollTop;
    scrollInterval = setInterval(function(){
        if (document.body.scrollTop != to) {
            count = count + 1;
            currPos = start + diff * (0.5 - 0.5 * Math.cos(count * scrollStep));
            document.body.scrollTop = currPos;
        }
        else { clearInterval(scrollInterval); }
    },10);
}

function test(elID)
{
    var dest = document.getElementById(elID);
    scrollTo(dest.offsetTop, 500);
}
</script>

It's incredibly simple. It finds the vertical position of the div in the document using its unique ID (in the function test). Then it calls the scrollTo function passing the starting position (document.body.scrollTop) and the destination position (dest.offsetTop). It performs the transition using some sort of ease-inout curve.

Thanks everyone for your help.

Knowing a bit of coding can help you avoiding (sometimes heavy) libraries, and giving you (the programmer) more control.

Getting specified Node values from XML document

Just like you do for getting something from the CNode you also need to do for the ANode

XmlNodeList xnList = xml.SelectNodes("/Element[@*]");
foreach (XmlNode xn in xnList)
{
  XmlNode anode = xn.SelectSingleNode("ANode");
    if (anode!= null)
    {
        string id = anode["ID"].InnerText;
        string date = anode["Date"].InnerText;
        XmlNodeList CNodes = xn.SelectNodes("ANode/BNode/CNode");
        foreach (XmlNode node in CNodes)
        {
         XmlNode example = node.SelectSingleNode("Example");
         if (example != null)
         {
            string na = example["Name"].InnerText;
            string no = example["NO"].InnerText;
         }
        }
    }
}

Can we open pdf file using UIWebView on iOS?

UIWebviews can also load the .pdf using loadData method, if you acquire it as NSData:

[self.webView loadData:self.pdfData 
              MIMEType:@"application/pdf" 
      textEncodingName:@"UTF-8" 
               baseURL:nil];

PL/SQL block problem: No data found error

This data not found causes because of some datatype we are using .

like select empid into v_test

above empid and v_test has to be number type , then only the data will be stored .

So keep track of the data type , when getting this error , may be this will help

JWT (JSON Web Token) library for Java

This page keeps references to implementations in various languages, including Java, and compares features: http://kjur.github.io/jsjws/index_mat.html

How to serialize an Object into a list of URL query parameters?

_x000D_
_x000D_
const obj = { id: 1, name: 'Neel' };_x000D_
let str = '';_x000D_
str = Object.entries(obj).map(([key, val]) => `${key}=${val}`).join('&');_x000D_
console.log(str);
_x000D_
_x000D_
_x000D_

SQL query to find Nth highest salary from a salary table

if wanna specified nth highest,could use rank method.

To get the third highest, use

SELECT * FROM
(SELECT @rank := @rank + 1 AS rank, salary
FROM   tbl,(SELECT @rank := 0) r 
order by salary desc ) m
WHERE rank=3

Why is my method undefined for the type object?

Try this.

public static void main(String[] args) {
    EchoServer0 myServer;
    myServer = new EchoServer0();
    myServer.listen();
}

What you were trying to do was declaring a variable of type Object, not creating anything for that variable to reference, then trying to call a method that didn't exist (in the class Object) on an object that hadn't been created. It was never going to work.

What is the difference between a string and a byte string?

From What is Unicode:

Fundamentally, computers just deal with numbers. They store letters and other characters by assigning a number for each one.

......

Unicode provides a unique number for every character, no matter what the platform, no matter what the program, no matter what the language.

So when a computer represents a string, it finds characters stored in the computer of the string through their unique Unicode number and these figures are stored in memory. But you can't directly write the string to disk or transmit the string on network through their unique Unicode number because these figures are just simple decimal number. You should encode the string to byte string, such as UTF-8. UTF-8 is a character encoding capable of encoding all possible characters and it stores characters as bytes (it looks like this). So the encoded string can be used everywhere because UTF-8 is nearly supported everywhere. When you open a text file encoded in UTF-8 from other systems, your computer will decode it and display characters in it through their unique Unicode number. When a browser receive string data encoded UTF-8 from network, it will decode the data to string (assume the browser in UTF-8 encoding) and display the string.

In python3, you can transform string and byte string to each other:

>>> print('??'.encode('utf-8'))
b'\xe4\xb8\xad\xe6\x96\x87'
>>> print(b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8'))
?? 

In a word, string is for displaying to humans to read on a computer and byte string is for storing to disk and data transmission.

UIView's frame, bounds, center, origin, when to use what?

They are related values, and kept consistent by the property setter/getter methods (and using the fact that frame is a purely synthesized value, not backed by an actual instance variable).

The main equations are:

frame.origin = center - bounds.size / 2

(which is the same as)

center = frame.origin + bounds.size / 2

(and there’s also)

frame.size = bounds.size

That's not code, just equations to express the invariant between the three properties. These equations also assume your view's transform is the identity, which it is by default. If it's not, then bounds and center keep the same meaning, but frame can change. Unless you're doing non-right-angle rotations, the frame will always be the transformed view in terms of the superview's coordinates.

This stuff is all explained in more detail with a useful mini-library here:

http://bynomial.com/blog/?p=24

What is the difference between _tmain() and main() in C++?

With a little effort of templatizing this, it wold work with any list of objects.

#include <iostream>
#include <string>
#include <vector>

char non_repeating_char(std::string str){
    while(str.size() >= 2){
        std::vector<size_t> rmlist; 
        for(size_t  i = 1;  i < str.size(); i++){        
            if(str[0] == str[i]) {
                rmlist.push_back(i);
            }      
        }          

        if(rmlist.size()){            
            size_t s = 0;  // Need for terator position adjustment   
            str.erase(str.begin() + 0);
            ++s;
            for (size_t j : rmlist){   
                str.erase(str.begin() + (j-s));                
                ++s;
            }
         continue;
        }
        return str[0];
   }
    if(str.size() == 1) return str[0];
    else return -1;
}

int main(int argc, char ** args)
{
    std::string test = "FabaccdbefafFG";
    test = args[1];
    char non_repeating = non_repeating_char(test);
    Std::cout << non_repeating << '\n';
}

Excel doesn't update value unless I hit Enter

It sounds like your workbook got set to Manual Calculation. You can change this to Automatic by going to Formulas > Calculation > Calculation Options > Automatic.

Location in Ribbon

Manual calculation can be useful to reduce computational load and improve responsiveness in workbooks with large amounts of formulas. The idea is that you can look at data and make changes, then choose when you want to make your computer go through the effort of calculation.