# Programs & Examples On #Census

### Error:attempt to apply non-function

You're missing *s in the last two terms of your expression, so R is interpreting (e.g.) 0.207 (log(DIAM93))^2 as an attempt to call a function named 0.207 ...

For example:

> 1 + 2*(3)
[1] 7
> 1 + 2 (3)


Error: attempt to apply non-function

Your (unreproducible) expression should read:

censusdata_20$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) + 0.207* (log(DIAM93))^2 - 0.0281*(log(DIAM93))^3)  Mathematica is the only computer system I know of that allows juxtaposition to be used for multiplication ... ### Java best way for string find and replace? Another option: "My name is Milan, people know me as Milan Vasic" .replaceAll("Milan Vasic|Milan", "Milan Vasic"))  ### Count textarea characters $(document).ready(function(){
$('#characterLeft').text('140 characters left');$('#message').keydown(function () {
var max = 140;
var len = $(this).val().length; if (len >= max) {$('#characterLeft').text('You have reached the limit');
$('#characterLeft').addClass('red');$('#btnSubmit').addClass('disabled');
}
else {
var ch = max - len;
$('#characterLeft').text(ch + ' characters left');$('#btnSubmit').removeClass('disabled');
$('#characterLeft').removeClass('red'); } }); });  ### How to extract text from the PDF document? Download the class.pdf2text.php @ https://pastebin.com/dvwySU1a or http://www.phpclasses.org/browse/file/31030.html (Registration required) Code: include('class.pdf2text.php');$a = new PDF2Text();
$a->setFilename('filename.pdf');$a->decodePDF();
echo $a->output();  • class.pdf2text.php Project Home • pdf2textclass doesn't work with all the PDF's I've tested, If it doesn't work for you, try PDF Parser ### Can you force Vue.js to reload/re-render? I had this issue with an image gallery that I wanted to rerender due to changes made on a different tab. So tab1 = imageGallery, tab2 = favoriteImages tab @change="updateGallery()" -> this forces my v-for directive to process the filteredImages function every time I switch tabs. <script> export default { data() { return { currentTab: 0, tab: null, colorFilter: "", colors: ["None", "Beige", "Black"], items: ["Image Gallery", "Favorite Images"] }; }, methods: { filteredImages: function() { return this.$store.getters.getImageDatabase.filter(img => {
if (img.color.match(this.colorFilter)) return true;
});
},
updateGallery: async function() {
// instance is responsive to changes
// change is made and forces filteredImages to do its thing
// async await forces the browser to slow down and allows changes to take effect
await this.$nextTick(function() { this.colorFilter = "Black"; }); await this.$nextTick(function() {
// Doesnt hurt to zero out filters on change
this.colorFilter = "";
});
}
}
};
</script>


### How Do I Upload Eclipse Projects to GitHub?

While the EGit plugin for Eclipse is a good option, an even better one would be to learn to use git bash -- i.e., git from the command line. It isn't terribly difficult to learn the very basics of git, and it is often very beneficial to understand some basic operations before relying on a GUI to do it for you. But to answer your question:

First things first, download git from http://git-scm.com/. Then go to http://github.com/ and create an account and repository.

On your machine, first you will need to navigate to the project folder using git bash. When you get there you do:

git init


which initiates a new git repository in that directory.

When you've done that, you need to register that new repo with a remote (where you'll upload -- push -- your files to), which in this case will be github. This assumes you have already created a github repository. You'll get the correct URL from your repo in GitHub.

git remote add origin https://github.com/[username]/[reponame].git


You need to add you existing files to your local commit:

git add .   # this adds all the files


Then you need to make an initial commit, so you do:

git commit -a -m "Initial commit" # this stages your files locally for commit.
# they haven't actually been pushed yet


Now you've created a commit in your local repo, but not in the remote one. To put it on the remote, you do the second line you posted:

git push -u origin --all


### jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

Remove servlet.jar from source web-inf/lib folder as it is available in tomcat lib folder then it works fine

### Angular 4 setting selected option in Dropdown

To preselect an option when the form is initialized, the value of the select element must be set to an element attribute of the array you are iterating over and setting the value of option to. Which is the key attribute in this case.

From your example.

<select [id]="question.key" [formControlName]="question.key">
<option *ngFor="let opt of question.options" [value]="opt.key"</option>
</select>


You are iterating over 'options' to create the select options. So the value of select must be set to the key attribute of an item in options(the one you want to display on initialization). This will display the default of select as the option whose value matches the value you set for select.

You can achieve this by setting the value of the select element in the onInit method like so.

ngOnInit(): void{
myForm : new FormGroup({
...
question.key : new FormControl(null)
})
// Get desired initial value to display on <select>
desiredValue = question.options.find(opt => opt === initialValue)
this.myForm.get(question.key).setValue(desiredValue.key)
}


### Removing trailing newline character from fgets() input

Below is a fast approach to remove a potential '\n' from a string saved by fgets().
It uses strlen(), with 2 tests.

char buffer[100];
if (fgets(buffer, sizeof buffer, stdin) != NULL) {

size_t len = strlen(buffer);
if (len > 0 && buffer[len-1] == '\n') {
buffer[--len] = '\0';
}


Now use buffer and len as needed.

This method has the side benefit of a len value for subsequent code. It can be easily faster than strchr(Name, '\n'). Ref YMMV, but both methods work.

buffer, from the original fgets() will not contain in "\n" under some circumstances:
A) The line was too long for buffer so only char preceding the '\n' is saved in buffer. The unread characters remain in the stream.
B) The last line in the file did not end with a '\n'.

If input has embedded null characters '\0' in it somewhere, the length reported by strlen() will not include the '\n' location.

Some other answers' issues:

1. strtok(buffer, "\n"); fails to remove the '\n' when buffer is "\n". From this answer - amended after this answer to warn of this limitation.

2. The following fails on rare occasions when the first char read by fgets() is '\0'. This happens when input begins with an embedded '\0'. Then buffer[len -1] becomes buffer[SIZE_MAX] accessing memory certainly outside the legitimate range of buffer. Something a hacker may try or found in foolishly reading UTF16 text files. This was the state of an answer when this answer was written. Later a non-OP edited it to include code like this answer's check for "".

size_t len = strlen(buffer);
if (buffer[len - 1] == '\n') {  // FAILS when len == 0
buffer[len -1] = '\0';
}

3. sprintf(buffer,"%s",buffer); is undefined behavior: Ref. Further, it does not save any leading, separating or trailing whitespace. Now deleted.

4. [Edit due to good later answer] There are no problems with the 1 liner buffer[strcspn(buffer, "\n")] = 0; other than performance as compared to the strlen() approach. Performance in trimming is usually not an issue given code is doing I/O - a black hole of CPU time. Should following code need the string's length or is highly performance conscious, use this strlen() approach. Else the strcspn() is a fine alternative.

### HTML&CSS + Twitter Bootstrap: full page layout or height 100% - Npx

I've found a post here on Stackoverflow and implemented your design:

http://jsfiddle.net/bKsad/25/

Here's the original post: https://stackoverflow.com/a/5768262/1368423

Is that what you're looking for?

HTML:

<div class="container-fluid wrapper">

<div class="row-fluid columns content">

<div class="span2 article-tree">
navigation column
</div>

<div class="span10 content-area">
content column
</div>
</div>

<div class="footer">
footer content
</div>
</div>


CSS:

html, body {
height: 100%;
}
.container-fluid {
margin: 0 auto;
height: 100%;
padding: 20px 0;

-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}

.columns {
background-color: #C9E6FF;
height: 100%;
}

.content-area, .article-tree{
background: #bada55;
overflow:auto;
height: 100%;
}

.footer {
background: red;
height: 20px;
}


### How do I use a char as the case in a switch-case?

Using a char when the variable is a string won't work. Using

switch (hello.charAt(0))


you will extract the first character of the hello variable instead of trying to use the variable as it is, in string form. You also need to get rid of your space inside

case 'a '


### OnClick Send To Ajax

Tried and working. you are using,

<textarea name='Status'> </textarea>
<input type='button' onclick='UpdateStatus()' value='Status Update'>


I am using javascript , (don't know about php), use id ="status" in textarea like

<textarea name='Status' id="status"> </textarea>
<input type='button' onclick='UpdateStatus()' value='Status Update'>


then make a call to servlet sending the status to backend for updating using whatever strutucre(like MVC in java or anyother) you like, like this in your UI in script tag

<srcipt>
function UpdateStatus(){

//make an ajax call and get status value using the same 'id'
var var1= document.getElementById("status").value;
$.ajax({ type:"GET",//or POST url:'http://localhost:7080/ajaxforjson/Testajax', // (or whatever your url is) data:{data1:var1}, //can send multipledata like {data1:var1,data2:var2,data3:var3 //can use dataType:'text/html' or 'json' if response type expected success:function(responsedata){ // process on data alert("got response as "+"'"+responsedata+"'"); } }) } </script>  and jsp is like the servlet will look like: //webservlet("/zcvdzv") is just for url annotation @WebServlet("/Testajax") public class Testajax extends HttpServlet { private static final long serialVersionUID = 1L; public Testajax() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String data1=request.getParameter("data1"); //do processing on datas pass in other java class to add to DB // i am adding or concatenate String data="i Got : "+"'"+data1+"' "; System.out.println(" data1 : "+data1+"\n data "+data); response.getWriter().write(data); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); }  } ### Very Long If Statement in Python According to PEP8, long lines should be placed in parentheses. When using parentheses, the lines can be broken up without using backslashes. You should also try to put the line break after boolean operators. Further to this, if you're using a code style check such as pycodestyle, the next logical line needs to have different indentation to your code block. For example: if (abcdefghijklmnopqrstuvwxyz > some_other_long_identifier and here_is_another_long_identifier != and_finally_another_long_name): # ... your code here ... pass  ### Stack array using pop() and push() Here is an example of implementing stack in java (Array Based implementation): public class MyStack extends Throwable{ /** * */ private static final long serialVersionUID = -4433344892390700337L; protected static int top = -1; protected static int capacity; protected static int size; public int stackDatas[] = null; public MyStack(){ stackDatas = new int[10]; capacity = stackDatas.length; } public static int size(){ if(top < 0){ size = top + 1; return size; } size = top+1; return size; } public void push(int data){ if(capacity == size()){ System.out.println("no memory"); }else{ stackDatas[++top] = data; } } public boolean topData(){ if(top < 0){ return true; }else{ System.out.println(stackDatas[top]); return false; } } public void pop(){ if(top < 0){ System.out.println("stack is empty"); }else{ int temp = stackDatas[top]; stackDatas = ArrayUtils.remove(stackDatas, top--); System.out.println("poped data---> "+temp); } } public String toString(){ String result = "["; if(top<0){ return "[]"; }else{ for(int i = 0; i< size(); i++){ result = result + stackDatas[i] +","; } } return result.substring(0, result.lastIndexOf(",")) +"]"; } }  calling MyStack:  public class CallingMyStack { public static MyStack ms; public static void main(String[] args) { ms = new MyStack(); ms.push(1); ms.push(2); ms.push(3); ms.push(4); ms.push(5); ms.push(6); ms.push(7); ms.push(8); ms.push(9); ms.push(10); System.out.println("size: "+MyStack.size()); System.out.println("List---> "+ms); System.out.println("----------"); ms.pop(); ms.pop(); ms.pop(); ms.pop(); System.out.println("List---> "+ms); System.out.println("size: "+MyStack.size()); } }  output: size: 10 List---> [1,2,3,4,5,6,7,8,9,10] ---------- poped data---> 10 poped data---> 9 poped data---> 8 poped data---> 7 List---> [1,2,3,4,5,6] size: 6  ### Use a loop to plot n charts Python Ok, so the easiest method to create several plots is this: import matplotlib.pyplot as plt x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]] y=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]] for i in range(len(x)): plt.figure() plt.plot(x[i],y[i]) # Show/save figure as desired. plt.show() # Can show all four figures at once by calling plt.show() here, outside the loop. #plt.show()  Note that you need to create a figure every time or pyplot will plot in the first one created. If you want to create several data series all you need to do is: import matplotlib.pyplot as plt plt.figure() x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]] y=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]] plt.plot(x[0],y[0],'r',x[1],y[1],'g',x[2],y[2],'b',x[3],y[3],'k')  You could automate it by having a list of colours like ['r','g','b','k'] and then just calling both entries in this list and corresponding data to be plotted in a loop if you wanted to. If you just want to programmatically add data series to one plot something like this will do it (no new figure is created each time so everything is plotted in the same figure): import matplotlib.pyplot as plt x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]] y=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]] colours=['r','g','b','k'] plt.figure() # In this example, all the plots will be in one figure. for i in range(len(x)): plt.plot(x[i],y[i],colours[i]) plt.show()  Hope this helps. If anything matplotlib has a very good documentation page with plenty of examples. 17 Dec 2019: added plt.show() and plt.figure() calls to clarify this part of the story. ### How do I pass a variable by reference? I used the following method to quickly convert a couple of Fortran codes to Python. True, it's not pass by reference as the original question was posed, but is a simple work around in some cases. a=0 b=0 c=0 def myfunc(a,b,c): a=1 b=2 c=3 return a,b,c a,b,c = myfunc(a,b,c) print a,b,c  ### What is the easiest way to remove the first character from a string? I find a nice solution to be str.delete(str[0]) for its readability, though I cannot attest to it's performance. ### Unable to execute dex: method ID not in [0, 0xffff]: 65536 Remove some jar file from Libs folder and copy to some other folder, And Go to _Project Properties > Select Java Build Path, Select Libraries, Select Add External Jar, Select the Removed jar to your project, Click save, this will be added under Referenced Library instead of Libs folder. Now clean and Run your project. You dont need to add Any code for MultDex. Its simply worked for me. ### how to make a html iframe 100% width and height? Answering this just in case if someone else like me stumbles upon this post among many that advise use of JavaScripts for changing iframe height to 100%. I strongly recommend that you see and try this option specified at How do you give iframe 100% height before resorting to a JavaScript based option. The referenced solution works perfectly for me in all of the testing I have done so far. Hope this helps someone. ### Using CMake to generate Visual Studio C++ project files I've started my own project, called syncProj. Documentation / download links from here: If you're planning to use Visual studio for development, and currently only C++ is supported. Main advantage compared to other make systems is that you can actually debug your script, as it's C# based. If you're not familiar with syncProj, you can just convert your solution / project to .cs script, and continue further development from that point on. In cmake you will need to write everything from scratch. ### Greater than and less than in one statement Please just write a static method somewhere and write: if( isSizeBetween(orderBean.getFiles(), 0, 5) ){ // do your stuff }  ### How do you specifically order ggplot2 x axis instead of alphabetical order? It is a little difficult to answer your specific question without a full, reproducible example. However something like this should work: #Turn your 'treatment' column into a character vector data$Treatment <- as.character(data$Treatment) #Then turn it back into a factor with the levels in the correct order data$Treatment <- factor(data$Treatment, levels=unique(data$Treatment))


In this example, the order of the factor will be the same as in the data.csv file.

If you prefer a different order, you can order them by hand:

data$Treatment <- factor(data$Treatment, levels=c("Y", "X", "Z"))


However this is dangerous if you have a lot of levels: if you get any of them wrong, that will cause problems.

### Regular Expression with wildcards to match any character

The following should work:

ABC: *$$[a-zA-Z]+$$ *(.+)


Explanation:

ABC:            # match literal characters 'ABC:'
*              # zero or more spaces
$$[a-zA-Z]+$$   # one or more letters inside of parentheses
*              # zero or more spaces
(.+)            # capture one or more of any character (except newlines)


To get your desired grouping based on the comments below, you can use the following:

(ABC:) *($$[a-zA-Z]+$$.+)


### How do I work with a git repository within another repository?

If I understand your problem well you want the following things:

1. Have your media files stored in one single git repository, which is used by many projects
2. If you modify a media file in any of the projects in your local machine, it should immediately appear in every other project (so you don't want to commit+push+pull all the time)

Unfortunately there is no ultimate solution for what you want, but there are some things by which you can make your life easier.

First you should decide one important thing: do you want to store for every version in your project repository a reference to the version of the media files? So for example if you have a project called example.com, do you need know which style.css it used 2 weeks ago, or the latest is always (or mostly) the best?

If you don't need to know that, the solution is easy:

1. create a repository for the media files and one for each project
2. create a symbolic link in your projects which point to the locally cloned media repository. You can either create a relative symbolic link (e.g. ../media) and assume that everybody will checkout the project so that the media directory is in the same place, or write the name of the symbolic link into .gitignore, and everybody can decide where he/she puts the media files.

In most of the cases, however, you want to know this versioning information. In this case you have two choices:

1. Store every project in one big repository. The advantage of this solution is that you will have only 1 copy of the media repository. The big disadvantage is that it is much harder to switch between project versions (if you checkout to a different version you will always modify ALL projects)

2. Use submodules (as explained in answer 1). This way you will store the media files in one repository, and the projects will contain only a reference to a specific media repo version. But this way you will normally have many local copies of the media repository, and you cannot easily modify a media file in all projects.

If I were you I would probably choose the first or third solution (symbolic links or submodules). If you choose to use submodules you can still do a lot of things to make your life easier:

1. Before committing you can rename the submodule directory and put a symlink to a common media directory. When you're ready to commit, you can remove the symlink and remove the submodule back, and then commit.

2. You can add one of your copy of the media repository as a remote repository to all of your projects.

You can add local directories as a remote this way:

cd /my/project2/media
git remote add project1 /my/project1/media


If you modify a file in /my/project1/media, you can commit it and pull it from /my/project2/media without pushing it to a remote server:

cd /my/project1/media
git commit -a -m "message"
cd /my/project2/media
git pull project1 master


You are free to remove these commits later (with git reset) because you haven't shared them with other users.

### PIL image to array (numpy array to array) - Python

I highly recommend you use the tobytes function of the Image object. After some timing checks this is much more efficient.

def jpg_image_to_array(image_path):
"""
Loads JPEG image into 3D Numpy array of shape
(width, height, channels)
"""
with Image.open(image_path) as image:
im_arr = np.fromstring(image.tobytes(), dtype=np.uint8)
im_arr = im_arr.reshape((image.size[1], image.size[0], 3))
return im_arr


The timings I ran on my laptop show

In [76]: %timeit np.fromstring(im.tobytes(), dtype=np.uint8)
1000 loops, best of 3: 230 µs per loop

In [77]: %timeit np.array(im.getdata(), dtype=np.uint8)
10 loops, best of 3: 114 ms per loop




### Reading Email using Pop3 in C#

I've successfully used OpenPop.NET to access emails via POP3.

### Best way to repeat a character in C#

And yet another method

new System.Text.StringBuilder().Append('\t', 100).ToString()


### htaccess "order" Deny, Allow, Deny

Update : for the new apache 2.4 jump directly to the end.

The Order keyword and its relation with Deny and Allow Directives is a real nightmare. It would be quite interesting to understand how we ended up with such solution, a non-intuitive one to say the least.

• The first important point is that the Order keyword will have a big impact on how Allow and Deny directives are used.
• Secondly, Deny and Allow directives are not applied in the order they are written, they must be seen as two distinct blocks (one the for Deny directives, one for Allow).
• Thirdly, they are drastically not like firewall rules: all rules are applied, the process is not stopping at the first match.

You have two main modes:

#### The Order-Deny-Allow-mode, or Allow-anyone-except-this-list-or-maybe-not

Order Deny,Allow

• This is an allow by default mode. You optionally specify Deny rules.
• Firstly, the Deny rules reject some requests.
• If someone gets rejected you can get them back with an Allow.

I would rephrase it as:

Rule Deny
list of Deny rules
Except
list of Allow rules
Policy Allow (when no rule fired)


#### The Order-Allow-Deny-mode, or Reject-everyone-except-this-list-or-maybe-not

Order Allow,Deny

• This is a deny by default mode. So you usually specify Allow rules.
• Firstly, someone's request must match at least one Allow rule.
• If someone matched an Allow, you can still reject them with a Deny.

In the simplified form:

Rule Allow
list of Allow rules
Except
list of Deny rules
Policy Deny (when no rule fired)


#### Back to your case

You need to allow a list of networks which are the country networks. And in this country you want to exclude some proxies' IP addresses.

You have taken the allow-anyone-except-this-list-or-maybe-not mode, so by default anyone can access your server, except proxies' IPs listed in the Deny list, but if they get rejected you still allow the country networks. That's too broad. Not good.

By inverting to order allow,deny you will be in the reject-everyone-except-this-list-or-maybe-not mode. So you will reject access to everyone but allow the country networks and then you will reject the proxies. And of course you must remove the Deny from all as stated by @Gerben and @Michael Slade (this answer only explains what they wrote).

The Deny from all is usually seen with order deny,allow to remove the allow by default access and make a simple, readable configuration. For example, specify a list of allowed IPs after that. You don't need that rule and your question is a perfect case of a 3-way access mode (default policy, exceptions, exceptions to exceptions).

But the guys who designed these settings are certainly insane.

#### All this is deprecated with Apache 2.4

The whole authorization scheme has been refactored in Apache 2.4 with RequireAll, RequireAny and RequireNone directives. See for example this complex logic example.

So the old strange Order logic becomes a relic, and to quote the new documentation:

Controling how and in what order authorization will be applied has been a bit of a mystery in the past

### jQuery Validation using the class instead of the name value

Here's my solution (requires no jQuery... just JavaScript):

function argsToArray(args) {
var r = []; for (var i = 0; i < args.length; i++)
r.push(args[i]);
return r;
}
function bind() {
var initArgs = argsToArray(arguments);
var fx =        initArgs.shift();
var tObj =      initArgs.shift();
var args =      initArgs;
return function() {
return fx.apply(tObj, args.concat(argsToArray(arguments)));
};
}
var salutation = argsToArray(document.getElementsByClassName('salutation'));
salutation.forEach(function(checkbox) {
checkbox.addEventListener('change', bind(function(checkbox, salutation) {
var numChecked = salutation.filter(function(checkbox) { return checkbox.checked; }).length;
if (numChecked >= 4)
checkbox.checked = false;
}, null, checkbox, salutation), false);
});


Put this in a script block at the end of <body> and the snippet will do its magic, limiting the number of checkboxes checked in maximum to three (or whatever number you specify).

Here, I'll even give you a test page (paste it into a file and try it):

<!DOCTYPE html><html><body>
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<script>
function argsToArray(args) {
var r = []; for (var i = 0; i < args.length; i++)
r.push(args[i]);
return r;
}
function bind() {
var initArgs = argsToArray(arguments);
var fx =        initArgs.shift();
var tObj =      initArgs.shift();
var args =      initArgs;
return function() {
return fx.apply(tObj, args.concat(argsToArray(arguments)));
};
}
var salutation = argsToArray(document.getElementsByClassName('salutation'));
salutation.forEach(function(checkbox) {
checkbox.addEventListener('change', bind(function(checkbox, salutation) {
var numChecked = salutation.filter(function(checkbox) { return checkbox.checked; }).length;
if (numChecked >= 3)
checkbox.checked = false;
}, null, checkbox, salutation), false);
});
</script></body></html>


### How to create a directory if it doesn't exist using Node.js?

Here is a little function to recursivlely create directories:

const createDir = (dir) => {
// This will create a dir given a path such as './folder/subfolder'
const splitPath = dir.split('/');
splitPath.reduce((path, subPath) => {
let currentPath;
if(subPath != '.'){
currentPath = path + '/' + subPath;
if (!fs.existsSync(currentPath)){
fs.mkdirSync(currentPath);
}
}
else{
currentPath = subPath;
}
return currentPath
}, '')
}


### "Press Any Key to Continue" function in C

You can try more system indeppended method: system("pause");

### Is a Java hashmap search really O(1)?

You seem to mix up worst-case behaviour with average-case (expected) runtime. The former is indeed O(n) for hash tables in general (i.e. not using a perfect hashing) but this is rarely relevant in practice.

Any dependable hash table implementation, coupled with a half decent hash, has a retrieval performance of O(1) with a very small factor (2, in fact) in the expected case, within a very narrow margin of variance.

### How to change the color of the axis, ticks and labels for a plot in matplotlib

motivated by previous contributors, this is an example of three axes.

import matplotlib.pyplot as plt

x_values1=[1,2,3,4,5]
y_values1=[1,2,2,4,1]

x_values2=[-1000,-800,-600,-400,-200]
y_values2=[10,20,39,40,50]

x_values3=[150,200,250,300,350]
y_values3=[-10,-20,-30,-40,-50]

fig=plt.figure()
ax=fig.add_subplot(111, label="1")
ax2=fig.add_subplot(111, label="2", frame_on=False)
ax3=fig.add_subplot(111, label="3", frame_on=False)

ax.plot(x_values1, y_values1, color="C0")
ax.set_xlabel("x label 1", color="C0")
ax.set_ylabel("y label 1", color="C0")
ax.tick_params(axis='x', colors="C0")
ax.tick_params(axis='y', colors="C0")

ax2.scatter(x_values2, y_values2, color="C1")
ax2.set_xlabel('x label 2', color="C1")
ax2.xaxis.set_label_position('bottom') # set the position of the second x-axis to bottom
ax2.spines['bottom'].set_position(('outward', 36))
ax2.tick_params(axis='x', colors="C1")
ax2.set_ylabel('y label 2', color="C1")
ax2.yaxis.tick_right()
ax2.yaxis.set_label_position('right')
ax2.tick_params(axis='y', colors="C1")

ax3.plot(x_values3, y_values3, color="C2")
ax3.set_xlabel('x label 3', color='C2')
ax3.xaxis.set_label_position('bottom')
ax3.spines['bottom'].set_position(('outward', 72))
ax3.tick_params(axis='x', colors='C2')
ax3.set_ylabel('y label 3', color='C2')
ax3.yaxis.tick_right()
ax3.yaxis.set_label_position('right')
ax3.spines['right'].set_position(('outward', 36))
ax3.tick_params(axis='y', colors='C2')

plt.show()


### Similarity String Comparison in Java

Sounds like a plagiarism finder to me if your string turns into a document. Maybe searching with that term will turn up something good.

"Programming Collective Intelligence" has a chapter on determining whether two documents are similar. The code is in Python, but it's clean and easy to port.

### postgresql - add boolean column to table set default

If you are using postgresql then you have to use column type BOOLEAN in lower case as boolean.

ALTER TABLE users ADD "priv_user" boolean DEFAULT false;

### How to control font sizes in pgf/tikz graphics in latex?

I believe Mica's way deserves the rank of answer, since is not visible enough as a comment:

\begin{tikzpicture}[font=\small]


### how to set font size based on container size?

I used Fittext on some of my projects and it looks like a good solution to a problem like this.

FitText makes font-sizes flexible. Use this plugin on your fluid or responsive layout to achieve scalable headlines that fill the width of a parent element.

### Can't compare naive and aware datetime.now() <= challenge.datetime_end

datetime.datetime.now is not timezone aware.

Django comes with a helper for this, which requires pytz

from django.utils import timezone
now = timezone.now()


You should be able to compare now to challenge.datetime_start

### Jquery DatePicker Set default date

<script  type="text/javascript">
$(document).ready(function () {$("#txtDate").datepicker({ dateFormat: 'yy/mm/dd' }).datepicker("setDate", "0");
$("#txtDate2").datepicker({ dateFormat: 'yy/mm/dd', }).datepicker("setDate", new Date().getDay+15); }); </script>  ### Sourcetree - undo unpushed commits If you select the log entry to which you want to revert to then you can click on "Reset to this commit". Only use this option if you didn't push the reverse commit changes. If you're worried about losing the changes then you can use the soft mode which will leave a set of uncommitted changes (what you just changed). Using the mixed resets the working copy but keeps those changes, and a hard will just get rid of the changes entirely. Here's some screenshots: ### Specifying Style and Weight for Google Fonts Here's the issue: You can't specify font weights that don't exist in the font set from Google. Click on the SEE SPECIMEN link below the font, then scroll down to the STYLES section. There you'll see each of the "styles" available for that particular font. Sadly Google doesn't list the CSS font weights for each style. Here's how the names map to CSS font weight numbers: Thin 100 Extra Light 200 Light 300 Regular 400 Medium 500 Semi-Bold 600 Bold 700 Extra-Bold 800 Black 900  Note that very few fonts come in all 9 weights. ### Can I use tcpdump to get HTTP requests, response header and response body? There are tcpdump filters for HTTP GET & HTTP POST (or for both plus message body): • Run man tcpdump | less -Ip examples to see some examples • Here’s a tcpdump filter for HTTP GET (GET = 0x47, 0x45, 0x54, 0x20): sudo tcpdump -s 0 -A 'tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x47455420'  • Here’s a tcpdump filter for HTTP POST (POST = 0x50, 0x4f, 0x53, 0x54): sudo tcpdump -s 0 -A 'tcp dst port 80 and (tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x504f5354)'  • Monitor HTTP traffic including request and response headers and message body (source): tcpdump -A -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)' tcpdump -X -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'  For more information on the bit-twiddling in the TCP header see: String-Matching Capture Filter Generator (link to Sake Blok's explanation). ### How can I go back/route-back on vue-router? Another solution is using vue-router-back-mixin import BackMixin from vue-router-back-mixin export default { ... mixins: [BackMixin], methods() { goBack() { this.backMixin_handleBack() } } ... }  ### Best way to create enum of strings? Use its name() method: public class Main { public static void main(String[] args) throws Exception { System.out.println(Strings.ONE.name()); } } enum Strings { ONE, TWO, THREE }  yields ONE. ### What can cause a “Resource temporarily unavailable” on sock send() command That's because you're using a non-blocking socket and the output buffer is full. From the send() man page  When the message does not fit into the send buffer of the socket, send() normally blocks, unless the socket has been placed in non-block- ing I/O mode. In non-blocking mode it would return EAGAIN in this case.  EAGAIN is the error code tied to "Resource temporarily unavailable" Consider using select() to get a better control of this behaviours ### NULL value for int in Update statement If this is nullable int field then yes. update TableName set FiledName = null where Id = SomeId  ### CURRENT_DATE/CURDATE() not working as default DATE value According to this documentation, starting in MySQL 8.0.13, you will be able to specify: CREATE TABLE INVOICE( INVOICEDATE DATE DEFAULT (CURRENT_DATE) )  Unfortunately, as of today, that version is not yet released. You can check here for the latest updates. ### How can I pretty-print JSON in a shell script? With Python 2.6+ you can do: echo '{"foo": "lorem", "bar": "ipsum"}' | python -m json.tool  or, if the JSON is in a file, you can do: python -m json.tool my_json.json  if the JSON is from an internet source such as an API, you can use curl http://my_url/ | python -m json.tool  For convenience in all of these cases you can make an alias: alias prettyjson='python -m json.tool'  For even more convenience with a bit more typing to get it ready: prettyjson_s() { echo "$1" | python -m json.tool
}

prettyjson_f() {
python -m json.tool "$1" } prettyjson_w() { curl "$1" | python -m json.tool
}


for all the above cases. You can put this in .bashrc and it will be available every time in shell. Invoke it like prettyjson_s '{"foo": "lorem", "bar": "ipsum"}'.

Note that as @pnd pointed out in the comments below, in Python 3.5+ the JSON object is no longer sorted by default. To sort, add the --sort-keys flag to the end. I.e. ... | python -m json.tool --sort-keys.

### Jquery : Refresh/Reload the page on clicking a button

simple way can be -

just href="javascript:location.reload(true);

your answer is

location.reload(true);


Thanks

### How to align content of a div to the bottom

Relative+absolute positioning is your best bet:

_x000D_
_x000D_
#header {_x000D_
position: relative;_x000D_
min-height: 150px;_x000D_
}_x000D_
_x000D_
#header-content {_x000D_
position: absolute;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
}_x000D_
_x000D_
#header, #header * {_x000D_
background: rgba(40, 40, 100, 0.25);_x000D_
}
_x000D_
<div id="header">_x000D_
<h1>Title</h1>_x000D_
<div id="header-content">Some content</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

But you may run into issues with that. When I tried it I had problems with dropdown menus appearing below the content. It's just not pretty.

Honestly, for vertical centering issues and, well, any vertical alignment issues with the items aren't fixed height, it's easier just to use tables.

### perform an action on checkbox checked or unchecked event on html form

The currently accepted answer doesn't always work.

(To read about the problem and circumstances, read this: Defined function is "Not defined".)

So, you have 3 options:

1 (it has above-mentioned drawback)

<input type="checkbox" onchange="doAlert(this)">

<script>
function doAlert(checkboxElem) {
if (checkboxElem.checked) {
alert ('hi');
} else {
alert ('bye');
}
}
</script>


2 and 3

<input type="checkbox" id="foo">

<script>
function doAlert() {
var input = document.querySelector('#foo');

// input.addEventListener('change', function() { ... });
// or
// input.onchange = function() { ... };
input.addEventListener('change', function() {
if (input.checked) {
alert ('hi');
} else {
alert ('bye');
}
});
}

doAlert();
</script>


### Finding last index of a string in Oracle

Use -1 as the start position:

INSTR('JD-EQ-0001', '-', -1)


### Regex Until But Not Including

The explicit way of saying "search until X but not including X" is:

(?:(?!X).)*


where X can be any regular expression.

In your case, though, this might be overkill - here the easiest way would be

[^z]*


This will match anything except z and therefore stop right before the next z.

So .*?quick[^z]* will match The quick fox jumps over the la.

However, as soon as you have more than one simple letter to look out for, (?:(?!X).)* comes into play, for example

(?:(?!lazy).)* - match anything until the start of the word lazy.

This is using a lookahead assertion, more specifically a negative lookahead.

.*?quick(?:(?!lazy).)* will match The quick fox jumps over the.

Explanation:

(?:        # Match the following but do not capture it:
(?!lazy)  # (first assert that it's not possible to match "lazy" here
.         # then match any character
)*         # end of group, zero or more repetitions.


Furthermore, when searching for keywords, you might want to surround them with word boundary anchors: \bfox\b will only match the complete word fox but not the fox in foxy.

Note

If the text to be matched can also include linebreaks, you will need to set the "dot matches all" option of your regex engine. Usually, you can achieve that by prepending (?s) to the regex, but that doesn't work in all regex engines (notably JavaScript).

Alternative solution:

In many cases, you can also use a simpler, more readable solution that uses a lazy quantifier. By adding a ? to the * quantifier, it will try to match as few characters as possible from the current position:

.*?(?=(?:X)|$)  will match any number of characters, stopping right before X (which can be any regex) or the end of the string (if X doesn't match). You may also need to set the "dot matches all" option for this to work. (Note: I added a non-capturing group around X in order to reliably isolate it from the alternation) ### Cannot use special principal dbo: Error 15405 Fix: Cannot use the special principal ‘sa’. Microsoft SQL Server, Error: 15405 When importing a database in your SQL instance you would find yourself with Cannot use the special principal 'sa'. Microsoft SQL Server, Error: 15405 popping out when setting the sa user as the DBO of the database. To fix this, Open SQL Management Studio and Click New Query. Type: USE mydatabase exec sp_changedbowner 'sa', 'true'  Close the new query and after viewing the security of the sa, you will find that that sa is the DBO of the database. (14444) ### How do I register a DLL file on Windows 7 64-bit? If the DLL is 32 bit: 1. Copy the DLL to C:\Windows\SysWoW64\ 2. In elevated cmd: %windir%\SysWoW64\regsvr32.exe %windir%\SysWoW64\namedll.dll if the DLL is 64 bit: 1. Copy the DLL to C:\Windows\System32\ 2. In elevated cmd: %windir%\System32\regsvr32.exe %windir%\System32\namedll.dll ### How to get the selected date value while using Bootstrap Datepicker? Bootstrap datepicker (the first result from bootstrap datepickcer search) has a method to get the selected date. https://bootstrap-datepicker.readthedocs.io/en/latest/methods.html#getdate getDate: Returns a localized date object representing the internal date object of the first datepicker in the selection. For multidate pickers, returns the latest date selected. $('.datepicker').datepicker("getDate")


or

$('.datepicker').datepicker("getDate").valueOf()  ### How do I download a file using VBA (without Internet Explorer) I was struggling for hours on this until I figured out it can be done in one line of powershell: invoke-webrequest -Uri "http://myserver/Reports/Pages/ReportViewer.aspx?%2fClients%2ftest&rs:Format=PDF&rs:ClearSession=true&CaseCode=12345678" -OutFile "C:\Temp\test.pdf" -UseDefaultCredentials  I looked into doing it purely in VBA but it runs to several pages, so I just call my powershell script from VBA every time I want to download a file. Simple. ### Read file As String You can use org.apache.commons.io.IOUtils.toString(InputStream is, Charset chs) to do that. e.g. IOUtils.toString(context.getResources().openRawResource(<your_resource_id>), StandardCharsets.UTF_8)  For adding the correct library: Add the following to your app/build.gradle file: dependencies { compile 'org.apache.directory.studio:org.apache.commons.io:2.4' }  or for the Maven repo see -> this link For direct jar download see-> https://commons.apache.org/proper/commons-io/download_io.cgi ### Docker: Multiple Dockerfiles in project In Intellij, I simple changed the name of the docker files to *.Dockerfile, and associated the file type *.Dockerfile to docker syntax. ### How to use ESLint with Jest To complete Zachary's answer, here is a workaround for the "extend in overrides" limitation of eslint config : overrides: [ Object.assign( { files: [ '**/*.test.js' ], env: { jest: true }, plugins: [ 'jest' ], }, require('eslint-plugin-jest').configs.recommended ) ]  ### How to ignore a property in class if null, using json.net Here's an option that's similar, but provides another choice: public class DefaultJsonSerializer : JsonSerializerSettings { public DefaultJsonSerializer() { NullValueHandling = NullValueHandling.Ignore; } }  Then, I use it like this: JsonConvert.SerializeObject(postObj, new DefaultJsonSerializer());  The difference here is that: • Reduces repeated code by instantiating and configuring JsonSerializerSettings each place it's used. • Saves time in configuring every property of every object to be serialized. • Still gives other developers flexibility in serialization options, rather than having the property explicitly specified on a reusable object. • My use-case is that the code is a 3rd party library and I don't want to force serialization options on developers who would want to reuse my classes. • Potential drawbacks are that it's another object that other developers would need to know about, or if your application is small and this approach wouldn't matter for a single serialization. ### extract month from date in python import datetime a = '2010-01-31' datee = datetime.datetime.strptime(a, "%Y-%m-%d") datee.month Out[9]: 1 datee.year Out[10]: 2010 datee.day Out[11]: 31  ### Column count doesn't match value count at row 1 The error means that you are providing not as much data as the table wp_posts does contain columns. And now the DB engine does not know in which columns to put your data. To overcome this you must provide the names of the columns you want to fill. Example: insert into wp_posts (column_name1, column_name2) values (1, 3)  Look up the table definition and see which columns you want to fill. And insert means you are inserting a new record. You are not modifying an existing one. Use update for that. ### Change font-weight of FontAwesome icons? Just to help anyone coming to this page. This is an alternate if you are flexible with using some other icon library. James is correct that you cannot change the font weight however if you are looking for more modern look for icons then you might consider ionicons It has both ios and android versions for icons. ### Validate a username and password against Active Directory? very simple solution using DirectoryServices: using System.DirectoryServices; //srvr = ldap server, e.g. LDAP://domain.com //usr = user name //pwd = user password public bool IsAuthenticated(string srvr, string usr, string pwd) { bool authenticated = false; try { DirectoryEntry entry = new DirectoryEntry(srvr, usr, pwd); object nativeObject = entry.NativeObject; authenticated = true; } catch (DirectoryServicesCOMException cex) { //not authenticated; reason why is in cex } catch (Exception ex) { //not authenticated due to some other exception [this is optional] } return authenticated; }  the NativeObject access is required to detect a bad user/password ### Transparent background in JPEG image If you’re concerned about the file size of a PNG, you can use an SVG mask to create a transparent JPEG. Here is an example I put together. ### How do I print the type or class of a variable in Swift? I had luck with: let className = NSStringFromClass(obj.dynamicType)  ### How to mute an html5 video player using jQuery If you don't want to jQuery, here's the vanilla JavaScript: ///Mute var video = document.getElementById("your-video-id"); video.muted= true; //Unmute var video = document.getElementById("your-video-id"); video.muted= false;  It will work for audio too, just put the element's id and it will work (and change the var name if you want, to 'media' or something suited for both audio/video as you like). ### how to get rid of notification circle in right side of the screen? This stuff comes from ES file explorer Just go into this app > settings Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good ### Converting Pandas dataframe into Spark dataframe error I made this script, It worked for my 10 pandas Data frames from pyspark.sql.types import * # Auxiliar functions def equivalent_type(f): if f == 'datetime64[ns]': return TimestampType() elif f == 'int64': return LongType() elif f == 'int32': return IntegerType() elif f == 'float64': return FloatType() else: return StringType() def define_structure(string, format_type): try: typo = equivalent_type(format_type) except: typo = StringType() return StructField(string, typo) # Given pandas dataframe, it will return a spark's dataframe. def pandas_to_spark(pandas_df): columns = list(pandas_df.columns) types = list(pandas_df.dtypes) struct_list = [] for column, typo in zip(columns, types): struct_list.append(define_structure(column, typo)) p_schema = StructType(struct_list) return sqlContext.createDataFrame(pandas_df, p_schema)  You can see it also in this gist With this you just have to call spark_df = pandas_to_spark(pandas_df) ### How to add months to a date in JavaScript? Split your date into year, month, and day components then use Date: var d = new Date(year, month, day); d.setMonth(d.getMonth() + 8);  Date will take care of fixing the year. ### How to create dynamic href in react render function? Could you please try this ? Create another item in post such as post.link then assign the link to it before send post to the render function. post.link = '/posts/+ id.toString();  So, the above render function should be following instead. return <li key={post.id}><a href={post.link}>{post.title}</a></li>  ### Boolean checking in the 'if' condition If you look at the alternatives on this page, of course the first option looks better and the second one is just more verbose. But if you are looking through a large class that someone else wrote, that verbosity can make the difference between realizing right away what the conditional is testing or not. One of the reasons I moved away from Perl is because it relies so heavily on punctuation, which is much slower to interpret while reading. I know I'm outvoted here, but I will almost always side with more explicit code so others can read it more accurately. Then again, I would never use a boolean variable called "status" either. Maybe isSuccess or just success, but "status" being true or false does not mean anything to the casual reader intuitively. As you can tell, I'm very into code readability because I read so much code others have written. ### Why doesn't [01-12] range work as expected? The []s in a regex denote a character class. If no ranges are specified, it implicitly ors every character within it together. Thus, [abcde] is the same as (a|b|c|d|e), except that it doesn't capture anything; it will match any one of a, b, c, d, or e. All a range indicates is a set of characters; [ac-eg] says "match any one of: a; any character between c and e; or g". Thus, your match says "match any one of: 0; any character between 1 and 1 (i.e., just 1); or 2. Your goal is evidently to specify a number range: any number between 01 and 12 written with two digits. In this specific case, you can match it with 0[1-9]|1[0-2]: either a 0 followed by any digit between 1 and 9, or a 1 followed by any digit between 0 and 2. In general, you can transform any number range into a valid regex in a similar manner. There may be a better option than regular expressions, however, or an existing function or module which can construct the regex for you. It depends on your language. ### Temporary table in SQL server causing ' There is already an object named' error You are dropping it, then creating it, then trying to create it again by using SELECT INTO. Change to: DROP TABLE #TMPGUARDIAN CREATE TABLE #TMPGUARDIAN( LAST_NAME NVARCHAR(30), FRST_NAME NVARCHAR(30)) INSERT INTO #TMPGUARDIAN SELECT LAST_NAME,FRST_NAME FROM TBL_PEOPLE  In MS SQL Server you can create a table without a CREATE TABLE statement by using SELECT INTO ### Building executable jar with maven? If you don't want execute assembly goal on package, you can use next command: mvn package assembly:single  Here package is keyword. ### overlay two images in android to set an imageview ok just so you know there is a program out there that's called DroidDraw. It can help you draw objects and try them one on top of the other. I tried your solution but I had animation under the smaller image so that didn't work. But then I tried to place one image in a relative layout that's suppose to be under first and then on top of that I drew the other image that is suppose to overlay and everything worked great. So RelativeLayout, DroidDraw and you are good to go :) Simple, no any kind of jiggery pockery :) and here is a bit of code for ya: The logo is going to be on top of shazam background image. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout android:id="@+id/widget30" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" > <ImageView android:id="@+id/widget39" android:layout_width="219px" android:layout_height="225px" android:src="@drawable/shazam_bkgd" android:layout_centerVertical="true" android:layout_centerHorizontal="true" > </ImageView> <ImageView android:id="@+id/widget37" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/shazam_logo" android:layout_centerVertical="true" android:layout_centerHorizontal="true" > </ImageView> </RelativeLayout>  ### Solve Cross Origin Resource Sharing with Flask Note that setting the Access-Control-Allow-Origin header in the Flask response object is fine in many cases (such as this one), but it has no effect when serving static assets (in a production setup, at least). That's because static assets are served directly by the front-facing web server (usually Nginx or Apache). So, in that case, you have to set the response header at the web server level, not in Flask. For more details, see this article that I wrote a while back, explaining how to set the headers (in my case, I was trying to do cross-domain serving of Font Awesome assets). Also, as @Satu said, you may need to allow access only for a specific domain, in the case of JS AJAX requests. For requesting static assets (like font files), I think the rules are less strict, and allowing access for any domain is more accepted. ### How do you set up use HttpOnly cookies in PHP You can specify it in the set cookie function see the php manual setcookie('Foo','Bar',0,'/', 'www.sample.com' , FALSE, TRUE);  ### Is there a way to call a stored procedure with Dapper? Here is code for getting value return from Store procedure Stored procedure: alter proc [dbo].[UserlogincheckMVC] @username nvarchar(max), @password nvarchar(max) as begin if exists(select Username from Adminlogin where Username =@username and Password=@password) begin return 1 end else begin return 0 end end  Code: var parameters = new DynamicParameters(); string pass = EncrytDecry.Encrypt(objUL.Password); conx.Open(); parameters.Add("@username", objUL.Username); parameters.Add("@password", pass); parameters.Add("@RESULT", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue); var RS = conx.Execute("UserlogincheckMVC", parameters, null, null, commandType: CommandType.StoredProcedure); int result = parameters.Get<int>("@RESULT");  ### How to override the properties of a CSS class using another CSS class You should override by increasing Specificity of your styling. There are different ways of increasing the Specificity. Usage of !important which effects specificity, is a bad practice because it breaks natural cascading in your style sheet. Following diagram taken from css-tricks.com will help you produce right specificity for your element based on a points structure. Whichever specificity has higher points, will win. Sounds like a game - doesn't it? Checkout sample calculations here on css-tricks.com. This will help you understand the concept very well and it will only take 2 minutes. If you then like to produce and/or compare different specificities by yourself, try this Specificity Calculator: https://specificity.keegan.st/ or you can just use traditional paper/pencil. For further reading try MDN Web Docs. All the best for not using !important. ### nvm keeps "forgetting" node in new terminal session Doing nvm install 10.14, for example, will nvm use that version for the current shell session but it will not always set it as the default for future sessions as you would expect. The node version you get in a new shell session is determined by nvm alias default. Confusingly, nvm install will only set the default alias if it is not already set. To get the expected behaviour, do this: nvm alias default ''; nvm install 10.14  This will ensure that that version is downloaded, use it for the current session and set it as the default for future sessions. ### http://localhost:8080/ Access Error: 404 -- Not Found Cannot locate document: / A tip for others: if you have NI applications installed, the NI Application Web Server also uses the port 8080. ### orderBy multiple fields in Angular There are 2 ways of doing AngularJs filters, one in the HTML using {{}} and one in actual JS files... You can solve you problem by using : {{ Expression | orderBy : expression : reverse}}  if you use it in the HTML or use something like: $filter('orderBy')(yourArray, yourExpression, reverse)


The reverse is optional at the end, it accepts a boolean and if it's true, it will reverse the Array for you, very handy way to reverse your Array...

### Where to put Gradle configuration (i.e. credentials) that should not be committed?

First answer is still valid, but the API has changed in the past. Since my edit there wasn't accepted I post it as separate answer.

The method authentication() is only used to provide the authentication method (e.g. Basic) but not any credentials.

You also shouldn't use it since it's printing the credentials plain on failure!

This his how it should look like in your build.gradle

    maven {
credentials {
username "$mavenUser" password "$mavenPassword"
}
url 'https://maven.yourcorp.net/'
}


In gradle.properties in your userhome dir put:

mavenUser=admin
mavenPassword=admin123


Also ensure that the GRADLE_USER_HOME is set to ~/.gradle otherwise the properties file there won't be resolved.

See also:

https://docs.gradle.org/current/userguide/build_environment.html

and

### SQL Server SELECT into existing table

SELECT ... INTO ... only works if the table specified in the INTO clause does not exist - otherwise, you have to use:

INSERT INTO dbo.TABLETWO
SELECT col1, col2
FROM dbo.TABLEONE
WHERE col3 LIKE @search_key


This assumes there's only two columns in dbo.TABLETWO - you need to specify the columns otherwise:

INSERT INTO dbo.TABLETWO
(col1, col2)
SELECT col1, col2
FROM dbo.TABLEONE
WHERE col3 LIKE @search_key


### How to set CATALINA_HOME variable in windows 7?

Assuming Java (JDK + JRE) is installed in your system, do the following:

1. Install Tomcat7
2. Copy 'tools.jar' from 'C:\Program Files (x86)\Java\jdk1.6.0_27\lib' and pasted it under 'C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\lib'.
3. Setup paths in your Environment Variables as shown below:

C:/>javap javax.servlet.http.HttpServletRequest

It should show a bunch of classes

### Unzipping files

I'm using zip.js and it seems to be quite useful. It's worth a look!

Check the Unzip demo, for example.

### Can JavaScript connect with MySQL?

YES? Have a look a meteor. Links:

I don't understand how it is done. But Nettuts+ put this thing in the javascript-ajax section, maybe magic happens.

It also shows some way to connect and insert to MongoDB with JS, like this:

Products.insert({Name : "Hammer", Price : 4.50, InStock : true});
Products.insert({Name : "Wrench", Price : 2.70, InStock : true});
Products.insert({Name : "Screw Driver", Price : 3.00, InStock : false});
Products.insert({Name : "Drill", Price : 5.25, InStock : true});


### import an array in python

Have a look at SciPy cookbook. It should give you an idea of some basic methods to import /export data.

If you save/load the files from your own Python programs, you may also want to consider the Pickle module, or cPickle.

### Update Eclipse with Android development tools v. 23

I found these instructions in a comment.

Download the newest version of ADT and use your existing workspace. This is actually the least pain-full upgrade you'll ever do. It didn't mess with the .android folder so I still had my original debug key. Only things missing were a couple of add ons I hardly ever use and they are easily installed into the new version.

Note don't install into your existing adt folder create a new folder so you can still fall back if the new install doesn't work.

### Disabling Warnings generated via _CRT_SECURE_NO_DEPRECATE

For the warning by warning case, It's wise to restore it to default at some point, since you are doing it on a case by case basis.

#pragma warning(disable: 4996) /* Disable deprecation */
// Code that causes it goes here
#pragma warning(default: 4996) /* Restore default */


### How to run only one unit test class using Gradle

Please note that --tests option may not work if you have different build types/flavors (fails with Unknown command-line option '--tests'). In this case, it's necessary to specify the particular test task (e.g. testProdReleaseUnitTest instead of just test)

### Exit a while loop in VBS/VBA

While Loop is an obsolete structure, I would recommend you to replace "While loop" to "Do While..loop", and you will able to use Exit clause.

check = 0

Do while not rs.EOF
if rs("reg_code") = rcode then
check = 1
Response.Write ("Found")
Exit do
else
rs.MoveNext
end if
Loop

if check = 0 then
Response.Write "Not Found"
end if}


### How to obtain the chat_id of a private Telegram channel?

You Can Too Do This:

Step 1)Convert Your Private Channel To Public Channel

Step 2)Set The ChannelName For This Channel

Step 3)then you Can change this Channel to Private

Step 4)Now Sending Your Message Using @ChannelName That you Set In Step 3

note:For Step 1 You Can Change One of Your Public Channel To Private For a short time.

### What is the default access specifier in Java?

First of all let me say one thing there is no such term as "Access specifier" in java. We should call everything as "Modifiers". As we know that final, static, synchronised, volatile.... are called as modifiers, even Public, private, protected, default, abstract should also be called as modifiers . Default is such a modifiers where physical existence is not there but no modifiers is placed then it should be treated as default modifiers.

To justify this take one example:

public class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}


Output will be: Hello Java

Now change public to private and see what compiler error you get: It says "Modifier private is not allowed here" What conclusion is someone can be wrong or some tutorial can be wrong but compiler cannot be wrong. So we can say there is no term access specifier in java everything is modifiers.

### How to create a JSON object

$post_data = [ "item" => [ 'item_type_id' =>$item_type,
'string_key' => $string_key, 'string_value' =>$string_value,
'string_extra' => $string_extra, 'is_public' =>$public,
'is_public_for_contacts' => $public_contacts ] ];$post_data = json_encode(post_data);
$post_data = json_decode(post_data); return$post_data;


### Remove useless zero digits from decimals in PHP

$x = '100.10';$x = preg_replace("/\.?0*$/",'',$x);
echo x;  There is nothing that can't be fixed with a simple regex ;) http://xkcd.com/208/ ### Using lodash to compare jagged arrays (items existence without order) You can use lodashs xor for this doArraysContainSameElements = _.xor(arr1, arr2).length === 0  If you consider array [1, 1] to be different than array [1] then you may improve performance a bit like so: doArraysContainSameElements = arr1.length === arr2.length === 0 && _.xor(arr1, arr2).length === 0  ### What are the benefits of using C# vs F# or F# vs C#? General benefits of functional programming over imperative languages: You can formulate many problems much easier, closer to their definition and more concise in a functional programming language like F# and your code is less error-prone (immutability, more powerful type system, intuitive recurive algorithms). You can code what you mean instead of what the computer wants you to say ;-) You will find many discussions like this when you google it or even search for it at SO. Special F#-advantages: Take a look at this document The advantages of C# are that it's often more accurate to "imperative"-applications (User-interface, imperative algorithms) than a functional programming language, that the .NET-Framework it uses is designed imperatively and that it's more widespread. Furthermore you can have F# and C# together in one solution, so you can combine the benefits of both languages and use them where they're needed. ### sql query distinct with Row_Number Try this SELECT distinct id FROM (SELECT id, ROW_NUMBER() OVER (ORDER BY id) AS RowNum FROM table WHERE fid = 64) t  Or use RANK() instead of row number and select records DISTINCT rank SELECT id FROM (SELECT id, ROW_NUMBER() OVER (PARTITION BY id ORDER BY id) AS RowNum FROM table WHERE fid = 64) t WHERE t.RowNum=1  This also returns the distinct ids ### What is stdClass in PHP? Also worth noting, an stdClass object can be created from the use of json_decode() as well. ### How do I add an element to array in reducer of React native redux? I have a sample import * as types from '../../helpers/ActionTypes'; var initialState = { changedValues: {} }; const quickEdit = (state = initialState, action) => { switch (action.type) { case types.PRODUCT_QUICKEDIT: { const item = action.item; const changedValues = { ...state.changedValues, [item.id]: item, }; return { ...state, loading: true, changedValues: changedValues, }; } default: { return state; } } }; export default quickEdit;  ### How to load/reference a file as a File instance from the classpath Try getting hold of a URL for your classpath resource: URL url = this.getClass().getResource("/com/path/to/file.txt")  Then create a file using the constructor that accepts a URI: File file = new File(url.toURI());  ### What does HTTP/1.1 302 mean exactly? From Wikipedia: The HTTP response status code 302 Found is the most common way of performing a redirection. It is an example of industrial practice contradicting the standard. ### Image style height and width not taken in outlook mails I have same problem for image which is not showing correctly in outlook.and I am using px and % for applying height and width for image. but when i removed px and % and using only just whatever the value in html it is worked for me. For example i was using : width="800px" now I'm using widht="800" and problem is resolved for me. ### How to get out of while loop in java with Scanner method "hasNext" as condition? If you don't want to use an EOF character for this, you can use StringTokenizer : import java.util.*; public class Test{ public static void main(){ Scanner sc = new Scanner (System.in); System.out.print("Enter your sentence: "); String s=sc.nextLine(); StringTokenizer st=new StringTokenizer(s," ");//" " is the delimiter here. while (st.hasMoreTokens() ) { String s1 = st.nextToken(); System.out.println(s1); } System.out.println("The loop has been ended"); } }  ### Setting mime type for excel document For anyone who is still stumbling with this after using all of the possible MIME types listed in the question: I have found that iMacs tend to also throw a MIME type of "text/xls" for XLS Excel files, hope this helps. ### How does one parse XML files? You can use ExtendedXmlSerializer to serialize and deserialize. Instalation You can install ExtendedXmlSerializer from nuget or run the following command: Install-Package ExtendedXmlSerializer  Serialization: ExtendedXmlSerializer serializer = new ExtendedXmlSerializer(); var obj = new Message(); var xml = serializer.Serialize(obj);  Deserialization var obj2 = serializer.Deserialize<Message>(xml);  Standard XML Serializer in .NET is very limited. • Does not support serialization of class with circular reference or class with interface property, • Does not support Dictionaries, • There is no mechanism for reading the old version of XML, • If you want create custom serializer, your class must inherit from IXmlSerializable. This means that your class will not be a POCO class, • Does not support IoC. ExtendedXmlSerializer can do this and much more. ExtendedXmlSerializer support .NET 4.5 or higher and .NET Core. You can integrate it with WebApi and AspCore. ### Hibernate: flush() and commit() flush() will synchronize your database with the current state of object/objects held in the memory but it does not commit the transaction. So, if you get any exception after flush() is called, then the transaction will be rolled back. You can synchronize your database with small chunks of data using flush() instead of committing a large data at once using commit() and face the risk of getting an OutOfMemoryException. commit() will make data stored in the database permanent. There is no way you can rollback your transaction once the commit() succeeds. ### TypeScript: Creating an empty typed container array Please try this which it works for me. return [] as Criminal[];  ### Better way to represent array in java properties file Use YAML files for properties, this supports properties as an array. Quick glance about YAML: A superset of JSON, it can do everything JSON can + more 1. Simple to read 2. Long properties into multiline values 3. Supports comments 4. Properties as Array 5. YAML Validation ### Better/Faster to Loop through set or list? While a set may be what you want structure-wise, the question is what is faster. A list is faster. Your example code doesn't accurately compare set vs list because you're converting from a list to a set in set_loop, and then you're creating the list you'll be looping through in list_loop. The set and list you iterate through should be constructed and in memory ahead of time, and simply looped through to see which data structure is faster at iterating: ids_list = range(1000000) ids_set = set(ids) def f(x): for i in x: pass %timeit f(ids_set) #1 loops, best of 3: 214 ms per loop %timeit f(ids_list) #1 loops, best of 3: 176 ms per loop  ### How can you flush a write using a file descriptor? You have two choices: 1. Use fileno() to obtain the file descriptor associated with the stdio stream pointer 2. Don't use <stdio.h> at all, that way you don't need to worry about flush either - all writes will go to the device immediately, and for character devices the write() call won't even return until the lower-level IO has completed (in theory). For device-level IO I'd say it's pretty unusual to use stdio. I'd strongly recommend using the lower-level open(), read() and write() functions instead (based on your later reply): int fd = open("/dev/i2c", O_RDWR); ioctl(fd, IOCTL_COMMAND, args); write(fd, buf, length);  ### How to make input type= file Should accept only pdf and xls You can try following way <input type= "file" name="Upload" accept = "application/pdf,.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel">  OR (in asp.net mvc) @Html.TextBoxFor(x => x.FileName, new { @id = "doc", @type = "file", @accept = "application/pdf,.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" })  ### how does multiplication differ for NumPy Matrix vs Array classes? There is a situation where the dot operator will give different answers when dealing with arrays as with dealing with matrices. For example, suppose the following: >>> a=numpy.array([1, 2, 3]) >>> b=numpy.array([1, 2, 3])  Lets convert them into matrices: >>> am=numpy.mat(a) >>> bm=numpy.mat(b)  Now, we can see a different output for the two cases: >>> print numpy.dot(a.T, b) 14 >>> print am.T*bm [[1. 2. 3.] [2. 4. 6.] [3. 6. 9.]]  ### CSS: Responsive way to center a fluid div (without px width) while limiting the maximum width? From Chris Coyier's article on centering percentage width elements: Instead of using negative margins, you use negative translate() transforms. .center { position: absolute; left: 50%; top: 50%; /* Nope =( margin-left: -25%; margin-top: -25%; */ /* Yep! */ transform: translate(-50%, -50%); /* Not even necessary really. e.g. Height could be left out! */ width: 40%; height: 50%; }  Codepen ### Codesign wants to access key "access" in your keychain, I put in my login password but keeps asking me For me, the problem was caps lock. and it seems it may ask you a couple of times to input your password or you will have to enter a password once and press always allow. ### Switch with if, else if, else, and loops inside case Your problem..... I think is that your for loop is encompassing all of the if, else if stuff - which acts like one statement, like hoang nguyen pointed out. Change to this. Note the brackets that denote the code block on which the for loop operates and the change of the first else if to if. switch(value){ case 1: for(int i=0; i<something_in_the_array.length;i++) { if(whatever_value==(something_in_the_array[i])) { value=2; break; } } if(whatever_value==2) { value=3; break; } else if(whatever_value==3) { value=4; break; } break; case 2: code continues....  ### Enterprise app deployment doesn't work on iOS 7.1 Further the previous answers about Dropbox, I implemented the following files tree such as only the PLIST file has to be uploaded to Dropbox: 1. upload the ipa file to your server in http (no change here) 2. upload the provisioning (.mobileprovision) file to your server in http (no change here) 3. upload the plist file to your dropbox (no change to do inside the plist file as the URLs are in absolute) 4. use the option "Share the link with Dropbox" which copies the link to your clipboard. This link has to be copied into your html file into the itms-servivces URL's query after changing the part www.dropbox.com by dl.dropboxusercontent.com. Note I URL encoded the link as suggested by @Mike but I don't test without to do it. Now the itms-services URL's query should look like this: itms-services://?action=download-manifest&url=https%3A%2F%2Fdl.dropboxusercontent.com%2Fs%2FYourShortDropboxLink.plist 5. upload the html file to your server in http. Note the html file contains both links to ipa and provisioning files. 6. access to your html file from your device and now the ipa can be installed by OTA like usually. From now, only the ipa file has to be changed to provide next app versions by OTA to your beta testers. Until Apple is yet changing the security rules. I join here after the very simple HTML file I'm using: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>iPhone app for test</title> </head> <body> <h1>iPhone app for test</h1> <br/> <ul> <li><a href="http://www.yourdomain.com/with/directories/provision/v.last/yourprovision_adhoc.mobileprovision"> Install Provisioning File</a></li> <li><a href="itms-services://?action=download-manifest&url=https%3A%2F%2Fdl.dropboxusercontent.com%2Fs%2FYourShortDropboxLink.plist"> Install Application</a></li> </ul> </body> </html>  ### How do you get centered content using Twitter Bootstrap? NOTE: this was removed in Bootstrap 3. Pre-Bootstrap 3, you could use the CSS class pagination-centered like this: <div class="span12 pagination-centered"> Centered content. </div>  Class pagination-centered is already in bootstrap.css (or bootstrap.min.css) and has the only one rule: .pagination-centered{text-align:center;}  With Bootstrap 2.3.0. just use class text-center ### How to create python bytes object from long hex string? You can do this with the hex codec. ie: >>> s='000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44' >>> s.decode('hex') '\x00\x00\x00\x00\x00\x00HB@\xfa\x06=\xe5\xd0\xb7D\xad\xbe\xd6:\x81\xfa\xea9\x00\x00\xc8B\x86@\xa4=P\x05\xbdD'  ### HTML5 and frameborder HTML 5 doesn't support attributes such as frameborder, scrolling, marginwidth, and marginheight (which were supported in HTML 4.01). Instead, the HTML 5 specification has introduced the seamless attribute. The seamless attribute allows the inline frame to appear as though it is being rendered as part of the containing document. For example, borders and scrollbars will not appear. According to MDN frameborder Obsolete since HTML5 The value 1 (the default) draws a border around this frame. The value 0 removes the border around this frame, but you should instead use the CSS property border to control borders. Like the quote above says, you should remove the border with CSS; either inline (style="border: none;") or in your stylesheet (iframe { border: none; }). That being said, there doesn't seem to be a single iframe provider that doesn't use frameborder="0". Even YouTube still uses the attribute and doesn't even provide a style attribute to make iframes backwards compatible for when frameborder isn't supported anymore. It's safe to say that the attribute isn't going anywhere soon. This leaves you with 3 options: 1. Keep using frameborder, just to be sure it works (for now) 2. Use CSS, to do the "right" thing 3. Use both. Although this doesn't resolve the incompatibility problem (just like option 1), it does and will work in every browser that has been and will be As for the previous state of this decade-old answer: The seamless attribute has been supported for such a short time (or not at all by some browsers), that MDN doesn't even list it as a deprecated feature. Don't use it and don't get confused by the comments below. ### Detect when a window is resized using JavaScript ? You can use .resize() to get every time the width/height actually changes, like this: (window).resize(function() {
//resize just happened, pixels changed
});


You can view a working demo here, it takes the new height/width values and updates them in the page for you to see. Remember the event doesn't really start or end, it just "happens" when a resize occurs...there's nothing to say another one won't happen.

Edit: By comments it seems you want something like a "on-end" event, the solution you found does this, with a few exceptions (you can't distinguish between a mouse-up and a pause in a cross-browser way, the same for an end vs a pause). You can create that event though, to make it a bit cleaner, like this:

$(window).resize(function() { if(this.resizeTO) clearTimeout(this.resizeTO); this.resizeTO = setTimeout(function() {$(this).trigger('resizeEnd');
}, 500);
});


You could have this is a base file somewhere, whatever you want to do...then you can bind to that new resizeEnd event you're triggering, like this:

$(window).bind('resizeEnd', function() { //do something, window hasn't changed size in 500ms });  ### jQuery hover and class selector Since this is a menu, might as well take it to the next level, and clean up the HTML, and make it more semantic by using a list element: HTML:  <ul id="menu"> <li><a href="#">Bla</a></li> <li><a href="#">Bla</a></li> <li><a href="#">Bla</a></li> </ul>  CSS: #menu { margin: 0; } #menu li { float: left; list-style: none; margin: 0; } #menu li a { display: block; line-height:30px; width:100px; background-color:#000; } #menu li a:hover { background-color:#F00; }  ### Graphviz's executables are not found (Python 3.4) I had the same issue with Windows 10. First, I installed graphviz-2.38.0 with the following command without any problem... install -c anaconda graphviz=2.38.0  Second, I installed pydotplus with the following command without any problem... install -c conda-forge pydotplus  After that, when I got to my step to visualize my decision tree had the following issue with {InvocationException: GraphViz's executables not found}... C:\Users\admin\Anaconda3\lib\site-packages\pydotplus\graphviz.py in create(self, prog, format) 1958 if self.progs is None: 1959 raise InvocationException( -> 1960 'GraphViz\'s executables not found') 1961 1962 if prog not in self.progs: InvocationException: GraphViz's executables not found  In my case, all I had to do to fix it is to put the environment path of the graphviz executables in my user PATH environment variable and this fixed it. Just make sure it is the path where YOUR.exe files are located :) C:\Users\admin\Anaconda3\pkgs\graphviz-2.38.0-4\Library\bin\graphviz  ### How to convert the background to transparent? For Photoshop you need to download Photoshop portable.... Load image e press "w" click in image e suave as png or gif.... ### Parsing time string in Python It has discussed many times in SO. In short, "%z" is not supported because platform not support it. My solution is a new one, just skip the time zone.:  datetime.datetime.strptime(re.sub(r"[+-]([0-9])+", "", "Tue May 08 15:14:45 +0800 2012"),"%a %b %d %H:%M:%S %Y")  ### How do I install pip on macOS or OS X? Download this file: get-pip.py Then simply type sudo python get-pip.py  Make sure you are on the same directory as get-pip.py or you supply the correct path for that file. For details, you can visit: http://pip.readthedocs.org/en/latest/installing.html ### Generate preview image from Video file? Two ways come to mind: • Using a command-line tool like the popular ffmpeg, however you will almost always need an own server (or a very nice server administrator / hosting company) to get that • Using the "screenshoot" plugin for the LongTail Video player that allows the creation of manual screenshots that are then sent to a server-side script. ### Selecting multiple columns in a Pandas dataframe I found this method to be very useful: # iloc[row slicing, column slicing] surveys_df.iloc [0:3, 1:4]  More details can be found here. ### Understanding the results of Execute Explain Plan in Oracle SQL Developer The CBO builds a decision tree, estimating the costs of each possible execution path available per query. The costs are set by the CPU_cost or I/O_cost parameter set on the instance. And the CBO estimates the costs, as best it can with the existing statistics of the tables and indexes that the query will use. You should not tune your query based on cost alone. Cost allows you to understand WHY the optimizer is doing what it does. Without cost you could figure out why the optimizer chose the plan it did. Lower cost does not mean a faster query. There are cases where this is true and there will be cases where this is wrong. Cost is based on your table stats and if they are wrong the cost is going to be wrong. When tuning your query, you should take a look at the cardinality and the number of rows of each step. Do they make sense? Is the cardinality the optimizer is assuming correct? Is the rows being return reasonable. If the information present is wrong then its very likely the optimizer doesn't have the proper information it needs to make the right decision. This could be due to stale or missing statistics on the table and index as well as cpu-stats. Its best to have stats updated when tuning a query to get the most out of the optimizer. Knowing your schema is also of great help when tuning. Knowing when the optimizer chose a really bad decision and pointing it in the correct path with a small hint can save a load of time. ### AJAX jQuery refresh div every 5 seconds <script type="text/javascript">$(document).ready(function(){
refreshTable();
});

function refreshTable(){
$('#tableHolder').load('getTable.php', function(){ setTimeout(refreshTable, 5000); }); } </script>  ### How to choose an AWS profile when using boto3 to connect to CloudFront Do this to use a profile with name 'dev': session = boto3.session.Session(profile_name='dev') s3 = session.resource('s3') for bucket in s3.buckets.all(): print(bucket.name)  ### Finding the source code for built-in Python functions? I had to dig a little to find the source of the following Built-in Functions as the search would yield thousands of results. (Good luck searching for any of those to find where it's source is) Anyway, all those functions are defined in bltinmodule.c Functions start with builtin_{functionname} For Built-in Types: https://github.com/python/cpython/tree/master/Objects ### Trying to get property of non-object - CodeIgniter To get the value: $query = $this->db->query("YOUR QUERY");  Then, for single row from(in controller): $query1 = $query->row();$data['product'] = $query1;  In view, you can use your own code (above code) ### Add a scrollbar to a <textarea> textarea { overflow-y: scroll; /* Vertical scrollbar */ overflow: scroll; /* Horizontal and vertical scrollbar*/ }  ### Assert a function/method was not called using Mock Though an old question, I would like to add that currently mock library (backport of unittest.mock) supports assert_not_called method. Just upgrade yours; pip install mock --upgrade ### ASP.NET Web Application Message Box There are several options to create a client-side messagebox in ASP.NET - see here, here and here for example... ### How to get package name from anywhere? For those who are using Gradle, as @Billda mentioned, you can get the package name via: BuildConfig.APPLICATION_ID  This gives you the package name declared in your app gradle: android { defaultConfig { applicationId "com.domain.www" } }  If you are interested to get the package name used by your java classes (which sometimes is different than applicationId), you can use BuildConfig.class.getPackage().toString()  If you are confused which one to use, read here: Note: The application ID used to be directly tied to your code's package name; so some Android APIs use the term "package name" in their method names and parameter names, but this is actually your application ID. For example, the Context.getPackageName() method returns your application ID. There's no need to ever share your code's true package name outside your app code. ### JPQL IN clause: Java-Arrays (or Lists, Sets...)? The oracle limit is 1000 parameters. The issue has been resolved by hibernate in version 4.1.7 although by splitting the passed parameter list in sets of 500 see JIRA HHH-1123 ### Python recursive folder read This worked for me: import glob root_dir = "C:\\Users\\Scott\\" # Don't forget trailing (last) slashes for filename in glob.iglob(root_dir + '**/*.jpg', recursive=True): print(filename) # do stuff  ### Code for a simple JavaScript countdown timer? So far the answers seem to rely on code being run instantly. If you set a timer for 1000ms, it will actually be around 1008 instead. Here is how you should do it: function timer(time,update,complete) { var start = new Date().getTime(); var interval = setInterval(function() { var now = time-(new Date().getTime()-start); if( now <= 0) { clearInterval(interval); complete(); } else update(Math.floor(now/1000)); },100); // the smaller this number, the more accurate the timer will be }  To use, call: timer( 5000, // milliseconds function(timeleft) { // called every step to update the visible countdown document.getElementById('timer').innerHTML = timeleft+" second(s)"; }, function() { // what to do after alert("Timer complete!"); } );  ### How to get first object out from List<Object> using Linq var firstObjectsOfValues = (from d in dic select d.Value[0].ComponentValue("Dep"));  ### Create SQL identity as primary key? If you're using T-SQL, the only thing wrong with your code is that you used braces {} instead of parentheses (). PS: Both IDENTITY and PRIMARY KEY imply NOT NULL, so you can omit that if you wish. ### Add Class to Object on Page Load I would recommend using jQuery with this function: $(document).ready(function(){
$('#about').addClass('expand'); });  This will add the expand class to an element with id of about when the dom is ready on page load. ### Cannot install node modules that require compilation on Windows 7 x64/VS2012 For windows 8 64-bit, installing zmq and protobuf, the following worked for me: Install Visual Studio 2012 On the command line: SET VisualStudioVersion=11.0 npm install zmq npm install protobuf  ### How to remove element from an array in JavaScript? There are multiple ways to remove an element from an Array. Let me point out most used options below. I'm writing this answer because I couldn't find a proper reason as to what to use from all of these options. The answer to the question is option 3 (Splice()). 1) SHIFT() - Remove First Element from Original Array and Return the First Element See reference for Array.prototype.shift(). Use this only if you want to remove the first element, and only if you are okay with changing the original array. const array1 = [1, 2, 3]; const firstElement = array1.shift(); console.log(array1); // expected output: Array [2, 3] console.log(firstElement); // expected output: 1  2) SLICE() - Returns a Copy of the Array, Separated by a Begin Index and an End Index See reference for Array.prototype.slice(). You cannot remove a specific element from this option. You can take only slice the existing array and get a continuous portion of the array. It's like cutting the array from the indexes you specify. The original array does not get affected. const animals = ['ant', 'bison', 'camel', 'duck', 'elephant']; console.log(animals.slice(2)); // expected output: Array ["camel", "duck", "elephant"] console.log(animals.slice(2, 4)); // expected output: Array ["camel", "duck"] console.log(animals.slice(1, 5)); // expected output: Array ["bison", "camel", "duck", "elephant"]  3) SPLICE() - Change Contents of Array by Removing or Replacing Elements at Specific Indexes. See reference for Array.prototype.splice(). The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. Returns updated array. Original array gets updated. const months = ['Jan', 'March', 'April', 'June']; months.splice(1, 0, 'Feb'); // inserts at index 1 console.log(months); // expected output: Array ["Jan", "Feb", "March", "April", "June"] months.splice(4, 1, 'May'); // replaces 1 element at index 4 console.log(months); // expected output: Array ["Jan", "Feb", "March", "April", "May"]  ### Import functions from another js file. Javascript By default, scripts can't handle imports like that directly. You're probably getting another error about not being able to get Course or not doing the import. If you add type="module" to your <script> tag, and change the import to ./course.js (because browsers won't auto-append the .js portion), then the browser will pull down course for you and it'll probably work. import './course.js'; function Student() { this.firstName = ''; this.lastName = ''; this.course = new Course(); }  <html> <head> <script src="./models/student.js" type="module"></script> </head> <body> <div id="myDiv"> </div> <script> window.onload= function() { var x = new Student(); x.course.id = 1; document.getElementById('myDiv').innerHTML = x.course.id; } </script> </body> </html>  If you're serving files over file://, it likely won't work. Some IDEs have a way to run a quick sever. You can also write a quick express server to serve your files (install Node if you don't have it): //package.json { "scripts": { "start": "node server" }, "dependencies": { "express": "latest" } } // server/index.js const express = require('express'); const app = express(); app.use('/', express.static('PATH_TO_YOUR_FILES_HERE'); app.listen(8000);  With those two files, run npm install, then npm start and you'll have a server running over http://localhost:8000 which should point to your files. ### How to run html file using node js Move your HTML file in a folder "www". Create a file "server.js" with code : var express = require('express'); var app = express(); app.use(express.static(__dirname + '/www')); app.listen('3000'); console.log('working on 3000');  After creation of file, run the command "node server.js" ### PDF Parsing Using Python - extracting formatted and plain texts You can also take a look at PDFMiner (or for older versions of Python see PDFMiner and PDFMiner). A particular feature of interest in PDFMiner is that you can control how it regroups text parts when extracting them. You do this by specifying the space between lines, words, characters, etc. So, maybe by tweaking this you can achieve what you want (that depends of the variability of your documents). PDFMiner can also give you the location of the text in the page, it can extract data by Object ID and other stuff. So dig in PDFMiner and be creative! But your problem is really not an easy one to solve because, in a PDF, the text is not continuous, but made from a lot of small groups of characters positioned absolutely in the page. The focus of PDF is to keep the layout intact. It's not content oriented but presentation oriented. ### How to run regasm.exe from command line other than Visual Studio command prompt? Like Cheeso said: You don't need the directory on your path. You could put it on your path, but you don't NEED to do that. If you are calling regasm rarely, or calling it from a batch file, you may find it is simpler to just invoke regasm via the fully-qualified pathname on the exe, eg: %SystemRoot%\Microsoft.NET\Framework\v2.0.50727\regasm.exe MyAssembly.dll ### How to display a confirmation dialog when clicking an <a> link? This method is slightly different than either of the above answers if you attach your event handler using addEventListener (or attachEvent). function myClickHandler(evt) { var allowLink = confirm('Continue with link?'); if (!allowLink) { evt.returnValue = false; //for older Internet Explorer if (evt.preventDefault) { evt.preventDefault(); } return false; } }  You can attach this handler with either: document.getElementById('mylinkid').addEventListener('click', myClickHandler, false);  Or for older versions of internet explorer: document.getElementById('mylinkid').attachEvent('onclick', myClickHandler);  ### How to drop all user tables? The simplest way is to drop the user that owns the objects with the cascade command. DROP USER username CASCADE  ### Variables not showing while debugging in Eclipse My problem was that I couldn't see variables names, but just the value. After trying quite a while I got the solution: Click on the down arrow (in degub Variables tab) --> Layout --> show columns It did the trick! ### How do I pick randomly from an array? myArray.sample  will return 1 random value. myArray.shuffle.first  will also return 1 random value. ### How to deselect all selected rows in a DataGridView control? To deselect all rows and cells in a DataGridView, you can use the ClearSelection method: myDataGridView.ClearSelection()  If you don't want even the first row/cell to appear selected, you can set the CurrentCell property to Nothing/null, which will temporarily hide the focus rectangle until the control receives focus again: myDataGridView.CurrentCell = Nothing  To determine when the user has clicked on a blank part of the DataGridView, you're going to have to handle its MouseUp event. In that event, you can HitTest the click location and watch for this to indicate HitTestInfo.Nowhere. For example: Private Sub myDataGridView_MouseUp(ByVal sender as Object, ByVal e as System.Windows.Forms.MouseEventArgs) ''# See if the left mouse button was clicked If e.Button = MouseButtons.Left Then ''# Check the HitTest information for this click location If myDataGridView.HitTest(e.X, e.Y) = DataGridView.HitTestInfo.Nowhere Then myDataGridView.ClearSelection() myDataGridView.CurrentCell = Nothing End If End If End Sub  Of course, you could also subclass the existing DataGridView control to combine all of this functionality into a single custom control. You'll need to override its OnMouseUp method similar to the way shown above. I also like to provide a public DeselectAll method for convenience that both calls the ClearSelection method and sets the CurrentCell property to Nothing. (Code samples are all arbitrarily in VB.NET because the question doesn't specify a language—apologies if this is not your native dialect.) ### Java Serializable Object to Byte Array Can be done by SerializationUtils, by serialize & deserialize method by ApacheUtils to convert object to byte[] and vice-versa , as stated in @uris answer. To convert an object to byte[] by serializing: byte[] data = SerializationUtils.serialize(object);  To convert byte[] to object by deserializing:: Object object = (Object) SerializationUtils.deserialize(byte[] data)  Click on the link to Download org-apache-commons-lang.jar Integrate .jar file by clicking: FileName -> Open Medule Settings -> Select your module -> Dependencies -> Add Jar file and you are done. Hope this helps. ### java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.testing.models.Account When you use jackson to map from string to your concrete class, especially if you work with generic type. then this issue may happen because of different class loader. i met it one time with below scenarior: Project B depend on Library A in Library A: public class DocSearchResponse<T> { private T data; }  it has service to query data from external source, and use jackson to convert to concrete class public class ServiceA<T>{ @Autowired private ObjectMapper mapper; @Autowired private ClientDocSearch searchClient; public DocSearchResponse<T> query(Criteria criteria){ String resultInString = searchClient.search(criteria); return convertJson(resultInString) } } public DocSearchResponse<T> convertJson(String result){ return mapper.readValue(result, new TypeReference<DocSearchResponse<T>>() {}); } }  in Project B: public class Account{ private String name; //come with other attributes }  and i use ServiceA from library to make query and as well convert data public class ServiceAImpl extends ServiceA<Account> { }  and make use of that public class MakingAccountService { @Autowired private ServiceA service; public void execute(Criteria criteria){ DocSearchResponse<Account> result = service.query(criteria); Account acc = result.getData(); // java.util.LinkedHashMap cannot be cast to com.testing.models.Account } }  it happen because from classloader of LibraryA, jackson can not load Account class, then just override method convertJson in Project B to let jackson do its job public class ServiceAImpl extends ServiceA<Account> { @Override public DocSearchResponse<T> convertJson(String result){ return mapper.readValue(result, new TypeReference<DocSearchResponse<T>>() {}); } } }  ### SQL DELETE with JOIN another table for WHERE condition Due to the locking implementation issues, MySQL does not allow referencing the affected table with DELETE or UPDATE. You need to make a JOIN here instead: DELETE gc.* FROM guide_category AS gc LEFT JOIN guide AS g ON g.id_guide = gc.id_guide WHERE g.title IS NULL  or just use a NOT IN: DELETE FROM guide_category AS gc WHERE id_guide NOT IN ( SELECT id_guide FROM guide )  ### Reading a column from CSV file using JAVA Splitting by comma doesn't work all the time for instance if you have csv file like "Name" , "Job" , "Address" "Pratiyush, Singh" , "Teacher" , "Berlin, Germany"  So, I would recommend using the Apache Commons CSV API:  Reader in = new FileReader("input1.csv"); Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in); for (CSVRecord record : records) { System.out.println(record.get(0)); }  ### How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)? I'd like to amend PsychoCoders answer: as the user wants to get all controls of a certain type we could use generics in the following way:  public IEnumerable<T> FindControls<T>(Control control) where T : Control { // we can't cast here because some controls in here will most likely not be <T> var controls = control.Controls.Cast<Control>(); return controls.SelectMany(ctrl => FindControls<T>(ctrl)) .Concat(controls) .Where(c => c.GetType() == typeof(T)).Cast<T>(); }  This way, we can call the function as follows: private void Form1_Load(object sender, EventArgs e) { var c = FindControls<TextBox>(this); MessageBox.Show("Total Controls: " + c.Count()); }  ### Get elements by attribute when querySelectorAll is not available without using libraries? Use //find first element with "someAttr" attribute document.querySelector('[someAttr]')  or //find all elements with "someAttr" attribute document.querySelectorAll('[someAttr]')  to find elements by attribute. It's now supported in all relevant browsers (even IE8): http://caniuse.com/#search=queryselector ### How can I check if a string contains ANY letters from the alphabet? You can use regular expression like this: import re print re.search('[a-zA-Z]+',string)  ### Count distinct value pairs in multiple columns in SQL You can also do something like: SELECT COUNT(DISTINCT id + name + address) FROM mytable  ### How to show multiline text in a table cell Wrap the content in a <pre> (pre-formatted text) tag <pre>hello , my name is x.</pre>  ### Get a worksheet name using Excel VBA Extend Code for Show Selected Sheet(s) [ one or more sheets]. Sub Show_SelectSheet() For Each xSheet In ThisWorkbook.Worksheets For Each xSelectSheet In ActiveWindow.SelectedSheets If xSheet.Name = xSelectSheet.Name Then '=== Show Selected Sheet === GoTo xNext_SelectSheet End If Next xSelectSheet xSheet.Visible = False xNext_SelectSheet: Next xSheet MsgBox "Show Selected Sheet(s) Completed !!!" end sub  ### Java Map equivalent in C# class Test { Dictionary<int, string> entities; public string GetEntity(int code) { // java's get method returns null when the key has no mapping // so we'll do the same string val; if (entities.TryGetValue(code, out val)) return val; else return null; } }  ### Matching a space in regex In Perl the switch is \s (whitespace). ### How to "wait" a Thread in Android I just add this line exactly as it appears below (if you need a second delay): try { Thread.sleep(1000); } catch(InterruptedException e) { // Process exception }  I find the catch IS necessary (Your app can crash due to Android OS as much as your own code). ### install apt-get on linux Red Hat server I think you're running into problems because RedHat uses RPM for managing packages. Debian based systems use DEBs, which are managed with tools like apt. ### Abstract methods in Python Before abc was introduced you would see this frequently. class Base(object): def go(self): raise NotImplementedError("Please Implement this method") class Specialized(Base): def go(self): print "Consider me implemented"  ### Correct way to quit a Qt program? QApplication is derived from QCoreApplication and thereby inherits quit() which is a public slot of QCoreApplication, so there is no difference between QApplication::quit() and QCoreApplication::quit(). As we can read in the documentation of QCoreApplication::quit() it "tells the application to exit with return code 0 (success).". If you want to exit because you discovered file corruption then you may not want to exit with return code zero which means success, so you should call QCoreApplication::exit() because you can provide a non-zero returnCode which, by convention, indicates an error. It is important to note that "if the event loop is not running, this function (QCoreApplication::exit()) does nothing", so in that case you should call exit(EXIT_FAILURE). ### Is there a way to automatically generate getters and setters in Eclipse? Bring up the context menu (i.e. right click) in the source code window of the desired class. Then select the Source submenu; from that menu selecting Generate Getters and Setters... will cause a wizard window to appear. Source -> Generate Getters and Setters... Select the variables you wish to create getters and setters for and click OK. ### Stretch image to fit full container width bootstrap In bootstrap 4.1, the w-100 class is required along with img-fluid for images smaller than the page to be stretched: <div class="container"> <div class="row"> <img class='img-fluid w-100' src="#" alt="" /> </div> </div>  see closed issue: https://github.com/twbs/bootstrap/issues/20830 (As of 2018-04-20, the documentation is wrong: https://getbootstrap.com/docs/4.1/content/images/ says that img-fluid applies max-width: 100%; height: auto;" but img-fluid does not resolve the issue, and neither does manually adding those style attributes with or without bootstrap classes on the img tag.) ### Simple CSS: Text won't center in a button The problem is that buttons render differently across browsers. In Firefox, 24px is sufficient to cover the default padding and space allowed for your "A" character and center it. In IE and Chrome, it does not, so it defaults to the minimum value needed to cover the left padding and the text without cutting it off, but without adding any additional width to the button. You can either increase the width, or as suggested above, alter the padding. If you take away the explicit width, it should work too. ### How do I register a .NET DLL file in the GAC? In case on windows 7 gacutil.exe (to put assembly in GAC) and sn.exe(To ensure uniqueness of assembly) resides at C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin Then go to the path of gacutil as shown below execute the below command after replacing path of your assembly C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin>gacutil /i "replace with path of your assembly to be put into GAC" ### How to delete a module in Android Studio The "Mark as Excluded" option isn't there anymore. The current (Android Studio 0.8.x - 2.2.x) way to do this is via the Project Structure dialog. It can be accessed via "File -> Project Structure" or by right-clicking on a Module and selecting "Module Settings". Then select the module, and click the "minus" button to remove it. The directory will still be visible in the "Project" view (though not in the "Android" view) since it's not actually deleted, but it will no longer be treated as a module. If you want, you can then physically delete the files it by right-clicking on it and pressing "Delete". ### PHP - cannot use a scalar as an array warning A bit late, but to anyone who is wondering why they are getting the "Warning: Cannot use a scalar value as an array" message; the reason is because somewhere you have first declared your variable with a normal integer or string and then later you are trying to turn it into an array. hope that helps ### Efficient way to remove keys with empty strings from a dict #### Quick Answer (TL;DR) #### Example01 ### example01 ------------------- mydict = { "alpha":0, "bravo":"0", "charlie":"three", "delta":[], "echo":False, "foxy":"False", "golf":"", "hotel":" ", } newdict = dict([(vkey, vdata) for vkey, vdata in mydict.iteritems() if(vdata) ]) print newdict ### result01 ------------------- result01 =''' {'foxy': 'False', 'charlie': 'three', 'bravo': '0'} '''  #### Detailed Answer #### Problem • Context: Python 2.x • Scenario: Developer wishes modify a dictionary to exclude blank values • aka remove empty values from a dictionary • aka delete keys with blank values • aka filter dictionary for non-blank values over each key-value pair #### Solution • example01 use python list-comprehension syntax with simple conditional to remove "empty" values #### Pitfalls • example01 only operates on a copy of the original dictionary (does not modify in place) • example01 may produce unexpected results depending on what developer means by "empty" • Does developer mean to keep values that are falsy? • If the values in the dictionary are not gauranteed to be strings, developer may have unexpected data loss. • result01 shows that only three key-value pairs were preserved from the original set #### Alternate example • example02 helps deal with potential pitfalls • The approach is to use a more precise definition of "empty" by changing the conditional. • Here we only want to filter out values that evaluate to blank strings. • Here we also use .strip() to filter out values that consist of only whitespace. #### Example02 ### example02 ------------------- mydict = { "alpha":0, "bravo":"0", "charlie":"three", "delta":[], "echo":False, "foxy":"False", "golf":"", "hotel":" ", } newdict = dict([(vkey, vdata) for vkey, vdata in mydict.iteritems() if(str(vdata).strip()) ]) print newdict ### result02 ------------------- result02 =''' {'alpha': 0, 'bravo': '0', 'charlie': 'three', 'delta': [], 'echo': False, 'foxy': 'False' } '''  #### See also ### Calling stored procedure from another stored procedure SQL Server First of all, if table2's idProduct is an identity, you cannot insert it explicitly until you set IDENTITY_INSERT on that table SET IDENTITY_INSERT table2 ON;  before the insert. So one of two, you modify your second stored and call it with only the parameters productName and productDescription and then get the new ID EXEC test2 'productName', 'productDescription' SET @newID = SCOPE_IDENTIY()  or you already have the ID of the product and you don't need to call SCOPE_IDENTITY() and can make the insert on table1 with that ID ### Swift add icon/image in UITextField for Swift 3.0 add image on leftside of textField textField.leftView = UIImageView(image: "small-calendar") textField.leftView?.frame = CGRect(x: 0, y: 5, width: 20 , height:20) textField.leftViewMode = .always  ### Difference between git pull and git pull --rebase For this is important to understand the difference between Merge and Rebase. Rebases are how changes should pass from the top of hierarchy downwards and merges are how they flow back upwards. For details refer - http://www.derekgourlay.com/archives/428 ### Reload nginx configuration Maybe you're not doing it as root? Try sudo nginx -s reload, if it still doesn't work, you might want to try sudo pkill -HUP nginx. ### MVC Form not able to post List of objects Your model is null because the way you're supplying the inputs to your form means the model binder has no way to distinguish between the elements. Right now, this code: @foreach (var planVM in Model) { @Html.Partial("_partialView", planVM) }  is not supplying any kind of index to those items. So it would repeatedly generate HTML output like this: <input type="hidden" name="yourmodelprefix.PlanID" /> <input type="hidden" name="yourmodelprefix.CurrentPlan" /> <input type="checkbox" name="yourmodelprefix.ShouldCompare" />  However, as you're wanting to bind to a collection, you need your form elements to be named with an index, such as: <input type="hidden" name="yourmodelprefix[0].PlanID" /> <input type="hidden" name="yourmodelprefix[0].CurrentPlan" /> <input type="checkbox" name="yourmodelprefix[0].ShouldCompare" /> <input type="hidden" name="yourmodelprefix[1].PlanID" /> <input type="hidden" name="yourmodelprefix[1].CurrentPlan" /> <input type="checkbox" name="yourmodelprefix[1].ShouldCompare" />  That index is what enables the model binder to associate the separate pieces of data, allowing it to construct the correct model. So here's what I'd suggest you do to fix it. Rather than looping over your collection, using a partial view, leverage the power of templates instead. Here's the steps you'd need to follow: 1. Create an EditorTemplates folder inside your view's current folder (e.g. if your view is Home\Index.cshtml, create the folder Home\EditorTemplates). 2. Create a strongly-typed view in that directory with the name that matches your model. In your case that would be PlanCompareViewModel.cshtml. Now, everything you have in your partial view wants to go in that template: @model PlanCompareViewModel <div> @Html.HiddenFor(p => p.PlanID) @Html.HiddenFor(p => p.CurrentPlan) @Html.CheckBoxFor(p => p.ShouldCompare) <input type="submit" value="Compare"/> </div>  Finally, your parent view is simplified to this: @model IEnumerable<PlanCompareViewModel> @using (Html.BeginForm("ComparePlans", "Plans", FormMethod.Post, new { id = "compareForm" })) { <div> @Html.EditorForModel() </div> }  DisplayTemplates and EditorTemplates are smart enough to know when they are handling collections. That means they will automatically generate the correct names, including indices, for your form elements so that you can correctly model bind to a collection. ### Change width of select tag in Twitter Bootstrap This works for me to reduce select tag's width; <select id ="Select1" class="input-small">  You can use any one of these classes; class="input-small" class="input-medium" class="input-large" class="input-xlarge" class="input-xxlarge"  ### What are functional interfaces used for in Java 8? A lambda expression can be assigned to a functional interface type, but so can method references, and anonymous classes. One nice thing about the specific functional interfaces in java.util.function is that they can be composed to create new functions (like Function.andThen and Function.compose, Predicate.and, etc.) due to the handy default methods they contain. ### How to get a unix script to run every 15 seconds? I wrote a scheduler faster than cron. I have also implemented an overlapping guard. You can configure the scheduler to not start new process if previous one is still running. Take a look at https://github.com/sioux1977/scheduler/wiki ### PhoneGap Eclipse Issue - eglCodecCommon glUtilsParamSize: unknow param errors I Get the same message, when using Intel XHAM emulator (instead of ARM) and have "Use Host GPU" option enabled. I belive when you disable it, it goes away. ### How to work with progress indicator in flutter? Step 1: Create Dialog  showAlertDialog(BuildContext context){ AlertDialog alert=AlertDialog( content: new Row( children: [ CircularProgressIndicator(), Container(margin: EdgeInsets.only(left: 5),child:Text("Loading" )), ],), ); showDialog(barrierDismissible: false, context:context, builder:(BuildContext context){ return alert; }, ); }  Step 2:Call it showAlertDialog(context); await firebaseAuth.signInWithEmailAndPassword(email: email, password: password); Navigator.pop(context);  Example With Dialog and login form import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:firebase_auth/firebase_auth.dart'; class DynamicLayout extends StatefulWidget{ @override State<StatefulWidget> createState() { // TODO: implement createState return new MyWidget(); } } showAlertDialog(BuildContext context){ AlertDialog alert=AlertDialog( content: new Row( children: [ CircularProgressIndicator(), Container(margin: EdgeInsets.only(left: 5),child:Text("Loading" )), ],), ); showDialog(barrierDismissible: false, context:context, builder:(BuildContext context){ return alert; }, ); } class MyWidget extends State<DynamicLayout>{ Color color = Colors.indigoAccent; String title='app'; GlobalKey<FormState> globalKey=GlobalKey<FormState>(); String email,password; login() async{ var currentState= globalKey.currentState; if(currentState.validate()){ currentState.save(); FirebaseAuth firebaseAuth=FirebaseAuth.instance; try { showAlertDialog(context); AuthResult authResult=await firebaseAuth.signInWithEmailAndPassword( email: email, password: password); FirebaseUser user=authResult.user; Navigator.pop(context); }catch(e){ print(e); } }else{ } } @override Widget build(BuildContext context) { return new Scaffold( appBar:AppBar( title: Text("$title"),
) ,
body: Container(child: Form(
key: globalKey,
child: Container(
padding: EdgeInsets.all(10),
child: Column(children: <Widget>[
TextFormField(decoration: InputDecoration(icon: Icon(Icons.email),labelText: 'Email'),
// ignore: missing_return
validator:(val){
if(val.isEmpty)
return 'Please Enter Your Email';
},
onSaved:(val){
email=val;
},
),
TextFormField(decoration: InputDecoration(icon: Icon(Icons.lock),labelText: 'Password'),
obscureText: true,
// ignore: missing_return
validator:(val){
if(val.isEmpty)
return 'Please Enter Your Password';
},
onSaved:(val){
password=val;
},
),
RaisedButton(color: Colors.lightBlue,textColor: Colors.white,child: Text('Login'),
onPressed:login),
],)
,),)
),
);
}
}


### What is the use of "using namespace std"?

• using: You are going to use it.
• namespace: To use what? A namespace.
• std: The std namespace (where features of the C++ Standard Library, such as string or vector, are declared).

After you write this instruction, if the compiler sees string it will know that you may be referring to std::string, and if it sees vector, it will know that you may be referring to std::vector. (Provided that you have included in your compilation unit the header files where they are defined, of course.)

If you don't write it, when the compiler sees string or vector it will not know what you are refering to. You will need to explicitly tell it std::string or std::vector, and if you don't, you will get a compile error.

### Corrupt jar file

This will happen when you doubleclick a JAR file in Windows explorer, but the JAR is by itself actually not an executable JAR. A real executable JAR should have at least a class with a main() method and have it referenced in MANIFEST.MF.

In Eclispe, you need to export the project as Runnable JAR file instead of as JAR file to get a real executable JAR.

Or, if your JAR is solely a container of a bunch of closely related classes (a library), then you shouldn't doubleclick it, but open it using some ZIP tool. Windows explorer namely by default associates JAR files with java.exe, which won't work for those kind of libary JARs.

### Pytorch reshape tensor dimension

>>> import torch
>>> a = torch.Tensor([1,2,3,4,5])
>>> a

1
2
3
4
5
[torch.FloatTensor of size 5]

>>> a = a.unsqueeze(0)
>>> a

1  2  3  4  5
[torch.FloatTensor of size 1x5]


### jQuery DataTables Getting selected row values

var table = $('#myTableId').DataTable(); var a= [];$.each(table.rows('.myClassName').data(), function() {
a.push(this["productId"]);
});

console.log(a[0]);
`