jQuery.validator.methods.matches = function( value, element, params ) {
var re = new RegExp(params);
// window.console.log(re);
// window.console.log(value);
// window.console.log(re.test( value ));
return this.optional( element ) || re.test( value );
}
rules: {
input_telf: {
required : true,
matches : "^(\\d|\\s)+$",
minlength : 10,
maxlength : 20
}
}
Clipboard-polyfill library is a polyfill for the modern Promise-based asynchronous clipboard API.
install in CLI:
npm install clipboard-polyfill
import as clipboard in JS file
window.clipboard = require('clipboard-polyfill');
I'm using it in a bundle with require("babel-polyfill");
and tested it on chrome 67. All good for production.
declare you array as:
$car = array("bmw")
EDIT
now with powershell syntax:)
$car = [array]"bmw"
In Windows Forms, if your string is in a textbox, you can easily use this:
textBoxcsharp.SelectAll();
textBoxcsharp.Copy();
textBoxcsharp.DeselectAll();
To get all options in a drop-down list by Selenium WebDriver C#:
SelectElement TimeZoneSelect = new SelectElement(driver.FindElement(By.Name("time_zone")));
IList<IWebElement> ElementCount = TimeZoneSelect.Options;
int ItemSize = ElementCount.Count;
for (int i = 0; i < ItemSize; i++)
{
String ItemValue = ElementCount.ElementAt(i).Text;
Console.WriteLine(ItemValue);
}
Several people saying .cc
doesn't stand for anything? It might. C++ started life as "C with Classes".
True that .cc
and .cpp
are also command names on most Unix systems (c compiler and c preprocessor respectively).
I use .cpp
exclusively, but I started on Windows. .cc
is more a Unix convention, although I see it less and less even there. GNU make has rules for .cpp
so that's probably preferred, it will work by default on both Windows and everything else. On the other hand modern C++ uses no extension at all for headers, I really don't like that. All my projects use .h
for header files, and they support both C and C++ as much as possible via extern "C"
and testing __cplusplus
.
Change it like this and it should work:
var key = item.Key.ToString();
IQueryable<entity> pages = from p in context.pages
where p.Serial == key
select p;
The reason why the exception is not thrown in the line the LINQ query is declared but in the line of the foreach
is the deferred execution feature, i.e. the LINQ query is not executed until you try to access the result. And this happens in the foreach
and not earlier.
The best solution is to install the different Python versions in multiple paths.
eg. C:\Python27 for 2.7, and C:\Python33 for 3.3.
Read this for more info: How to run multiple Python versions on Windows
// Prepared By Muhammad Mubashir.
// 26, August, 2011.
// Chnage Back Ground Image of Activity.
package com.ChangeBg_01;
import com.ChangeBg_01.R;
import android.R.color;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class ChangeBg_01Activity extends Activity
{
TextView tv;
int[] arr = new int[2];
int i=0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.tv);
arr[0] = R.drawable.icon1;
arr[1] = R.drawable.icon;
// Load a background for the current screen from a drawable resource
//getWindow().setBackgroundDrawableResource(R.drawable.icon1) ;
final Handler handler=new Handler();
final Runnable r = new Runnable()
{
public void run()
{
//tv.append("Hello World");
if(i== 2){
i=0;
}
getWindow().setBackgroundDrawableResource(arr[i]);
handler.postDelayed(this, 1000);
i++;
}
};
handler.postDelayed(r, 1000);
Thread thread = new Thread()
{
@Override
public void run() {
try {
while(true)
{
if(i== 2){
//finish();
i=0;
}
sleep(1000);
handler.post(r);
//i++;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
}
}
/*android:background="#FFFFFF"*/
/*
ImageView imageView = (ImageView) findViewById(R.layout.main);
imageView.setImageResource(R.drawable.icon);*/
// Now get a handle to any View contained
// within the main layout you are using
/* View someView = (View)findViewById(R.layout.main);
// Find the root view
View root = someView.getRootView();*/
// Set the color
/*root.setBackgroundColor(color.darker_gray);*/
This code:
"127.0.0.1".equals(InetAddress.getLocalHost().getHostAddress().toString());
Returns - to me - true
if offline, and false
, otherwise. (well, I don't know if this true to all computers).
This works much faster than the other approaches, up here.
EDIT: I found this only working, if the "flip switch" (on a laptop), or some other system-defined option, for the internet connection, is off. That's, the system itself knows not to look for any IP addresses.
just go to the window bottom tray click on wamp icon ,click mysql->my.ini,then there is option ;sql-mode="" uncomment this make it like sql-mode="" and restart wamp worked for me
If you are doing it in Notepad++
[\w]+
Would give you the entire word, and you can add parenthesis to get it as a group. Example: conv1 = Conv2D(64, (3, 3), activation=LeakyReLU(alpha=a), padding='valid', kernel_initializer='he_normal')(inputs)
. I would like to move LeakyReLU
into its own line as a comment, and replace the current activation. In notepad++ this can be done using the follow find command:
([\w]+)( = .+)(LeakyReLU.alpha=a.)(.+)
and the replace command becomes:
\1\2'relu'\4 \n # \1 = LeakyReLU\(alpha=a\)\(\1\)
The spaces is to keep the right formatting in my code. :)
Unfortunately there is currently no designer support (unlike for SQL Server 2005) for building relationships between tables in SQL Server CE. To build relationships you need to use SQL commands such as:
ALTER TABLE Orders
ADD CONSTRAINT FK_Customer_Order
FOREIGN KEY (CustomerId) REFERENCES Customers(CustomerId)
If you are doing CE development, i would recomend this FAQ:
EDIT: In Visual Studio 2008 this is now possible to do in the GUI by right-clicking on your table.
In this case, the most proper way to exit the application in to override onExit() method in App.xaml.cs:
protected override void OnExit(ExitEventArgs e) {
base.OnExit(e);
}
You need to assign display: block;
property to the wrapping anchor. Otherwise it won't wrap correctly.
<a style="display:block" href="http://justinbieber.com">
<div class="xyz">My div contents</div>
</a>
Use the Apache XMLSerializer
here's an example: http://www.informit.com/articles/article.asp?p=31349&seqNum=3&rl=1
you can check this as well
As it solved the problem, I put it as an answer.
Don't use single and double quotes, especially when you define a raw string with r
in front of it.
The correct call is then
path = r"C:\Apps\CorVu\DATA\Reports\AlliD\Monthly Commission Reports\Output\pdcom1"
or
path = r'C:\Apps\CorVu\DATA\Reports\AlliD\Monthly Commission Reports\Output\pdcom1'
This is probably desirable for backwards compatibility.
Python3 breaks backwards compatibility, and programs invoking 'python' probably expect python2. You probably have many programs and scripts which you are not even aware of which expect python=python2, and changing this would break those programs and scripts.
The answer you are probably looking for is You should not change this.
You could, however, make a custom alias in your shell. The way you do so depends on the shell, but perhaps you could do alias py=python3
If you are confused about how to start the latest version of python, it is at least the case on Linux that python3
leaves your python2
installation intact (due to the above compatibility reasons); thus you can start python3 with the python3
command.
In my case, log4net wasn't logging properly due to having a space in my project name. Drove me nuts why the same code worked just fine in a different project, but didn't in the new one. Spaces. A simple space.
So, beware spaces in project names. I've learned my lesson.
Don't like any of those solutions.
this is how i do it:
$update_query = "UPDATE db.tablename SET insert_time=now() WHERE username='"
. sqlEsc($somename) . "' ;";
then i use my own sqlEsc function:
function sqlEsc($val)
{
global $mysqli;
return mysqli_real_escape_string($mysqli, $val);
}
I encountered this problem today and my issue was that when copying the public key from file, new line characters are included as well. You can use ":set list" in vim to see all the hidden new lines and make sure to delete all the new lines except for the last one. Also, my key was missing "ssh-rsa " in the beginning. Make sure you have that as well.
If you found authentication error problem when you entered correct password and username it's git problem. To solves this problem when you are installing the git in your machine uncheck the enable git credential manager
Most answers and explanations are not to explain what is a valid string of endDate
or startDate
.
Danny gave us two useful example.
$('#datepicker').datepicker({
startDate: '-2m',
endDate: '+2d'
});
But why?let's take a look at the source code at bootstrap-datetimepicker.js
.
There are some code begin line 1343 tell us how does it work.
if (/^[-+]\d+[dmwy]([\s,]+[-+]\d+[dmwy])*$/.test(date)) {
var part_re = /([-+]\d+)([dmwy])/,
parts = date.match(/([-+]\d+)([dmwy])/g),
part, dir;
date = new Date();
for (var i = 0; i < parts.length; i++) {
part = part_re.exec(parts[i]);
dir = parseInt(part[1]);
switch (part[2]) {
case 'd':
date.setUTCDate(date.getUTCDate() + dir);
break;
case 'm':
date = Datetimepicker.prototype.moveMonth.call(Datetimepicker.prototype, date, dir);
break;
case 'w':
date.setUTCDate(date.getUTCDate() + dir * 7);
break;
case 'y':
date = Datetimepicker.prototype.moveYear.call(Datetimepicker.prototype, date, dir);
break;
}
}
return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), 0);
}
There are four kinds of expressions.
w
means weekm
means monthy
means yeard
means dayLook at the regular expression ^[-+]\d+[dmwy]([\s,]+[-+]\d+[dmwy])*$
.
You can do more than these -0d
or +1m
.
Try harder like startDate:'+1y,-2m,+0d,-1w'
.And the separator ,
could be one of [\f\n\r\t\v,]
The book Java Generics and Collections has this information (pages: 188, 211, 222, 240).
List implementations:
get add contains next remove(0) iterator.remove
ArrayList O(1) O(1) O(n) O(1) O(n) O(n)
LinkedList O(n) O(1) O(n) O(1) O(1) O(1)
CopyOnWrite-ArrayList O(1) O(n) O(n) O(1) O(n) O(n)
Set implementations:
add contains next notes
HashSet O(1) O(1) O(h/n) h is the table capacity
LinkedHashSet O(1) O(1) O(1)
CopyOnWriteArraySet O(n) O(n) O(1)
EnumSet O(1) O(1) O(1)
TreeSet O(log n) O(log n) O(log n)
ConcurrentSkipListSet O(log n) O(log n) O(1)
Map implementations:
get containsKey next Notes
HashMap O(1) O(1) O(h/n) h is the table capacity
LinkedHashMap O(1) O(1) O(1)
IdentityHashMap O(1) O(1) O(h/n) h is the table capacity
EnumMap O(1) O(1) O(1)
TreeMap O(log n) O(log n) O(log n)
ConcurrentHashMap O(1) O(1) O(h/n) h is the table capacity
ConcurrentSkipListMap O(log n) O(log n) O(1)
Queue implementations:
offer peek poll size
PriorityQueue O(log n) O(1) O(log n) O(1)
ConcurrentLinkedQueue O(1) O(1) O(1) O(n)
ArrayBlockingQueue O(1) O(1) O(1) O(1)
LinkedBlockingQueue O(1) O(1) O(1) O(1)
PriorityBlockingQueue O(log n) O(1) O(log n) O(1)
DelayQueue O(log n) O(1) O(log n) O(1)
LinkedList O(1) O(1) O(1) O(1)
ArrayDeque O(1) O(1) O(1) O(1)
LinkedBlockingDeque O(1) O(1) O(1) O(1)
The bottom of the javadoc for the java.util package contains some good links:
Yes, we can run docker in docker, we'll need to attach the unix sockeet "/var/run/docker.sock" on which the docker daemon listens by default as volume to the parent docker using "-v /var/run/docker.sock:/var/run/docker.sock". Sometimes, permissions issues may arise for docker daemon socket for which you can write "sudo chmod 757 /var/run/docker.sock".
And also it would require to run the docker in privileged mode, so the commands would be:
sudo chmod 757 /var/run/docker.sock
docker run --privileged=true -v /var/run/docker.sock:/var/run/docker.sock -it ...
I recommend using .htaccess
. You only need to add:
DirectoryIndex home.php
or whatever page name you want to have for it.
EDIT: basic htaccess tutorial.
1) Create .htaccess
file in the directory where you want to change the index file.
.
in front, to ensure it is a "hidden" fileEnter the line above in there. There will likely be many, many other things you will add to this (AddTypes for webfonts / media files, caching for headers, gzip declaration for compression, etc.), but that one line declares your new "home" page.
2) Set server to allow reading of .htaccess
files (may only be needed on your localhost, if your hosting servce defaults to allow it as most do)
Assuming you have access, go to your server's enabled site location. I run a Debian server for development, and the default site setup is at /etc/apache2/sites-available/default
for Debian / Ubuntu. Not sure what server you run, but just search for "sites-available" and go into the "default" document. In there you will see an entry for Directory. Modify it to look like this:
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
Then restart your apache server. Again, not sure about your server, but the command on Debian / Ubuntu is:
sudo service apache2 restart
Technically you only need to reload, but I restart just because I feel safer with a full refresh like that.
Once that is done, your site should be reading from your .htaccess file, and you should have a new default home page! A side note, if you have a sub-directory that runs a site (like an admin section or something) and you want to have a different "home page" for that directory, you can just plop another .htaccess
file in that sub-site's root and it will overwrite the declaration in the parent.
I don't think this can be done using jQuery's animate
function because the background image does not have the necessary CSS properties to do such fading. jQuery can only utilize what the browser makes possible. (jQuery experts, correct me if I'm wrong of course.)
I guess you would have to work around this by not using genuine background-image
s, but div
elements containing the image, positioned using position: absolute
(or fixed
) and z-index
for stacking. You would then animate those div
s.
Navigate to the directory on the terminal cd [your directory]
Navigate to the directory on the terminal
use charm .
to open the project in PyCharm
Simplest and quickest way to open a project in PyCharm
There's always System.Web.Security.Membership.GeneratePassword(int length, int numberOfNonAlphanumericCharacters
).
Regex isn't needed, nor is plugins
if (isNaN($('#Field').val() / 1) == false) {
your code here
}
/C
Carries out the command specified by the string and then terminates.
You can get all the cmd command line switches by typing cmd /?
.
Also, if your service is sending an object instead of an array add isArray:false to its declaration.
'query': {method: 'GET', isArray: false }
Try replacing <%# Eval("item") %>
with <%# If(Eval("item"), "0 value") %>
(or <%# Eval("item") ?? "0 value" %>
, when using C#).
And how I implemented this
<script type="text/javascript">
!(window.ActiveXObject) && "ActiveXObject"
function isIE11(){
return !!navigator.userAgent.match(/Trident.*rv[ :]*11\./);
}
</script>
If you want to alter order for columns in Sql server, There is no direct way to do this in SQL Server currently.
Have a look at http://blog.sqlauthority.com/2008/04/08/sql-server-change-order-of-column-in-database-tables/
You can change order while edit design for table.
Simple answer to this; I was trying to figure out the same thing, and it just hit me.
GitHub IS a program installed on your computer, and when it runs, it WILL use threads and RAM. So that makes it a process. All you have to do is open Task Manager, click the Processes tab, find 'Github.exe', right click, Open File Location. Voila! Mine is in some App folder in Local, about 4 layers deep.
I got this working with the following directive:
app.directive('datatableSetup', function () {
return { link: function (scope, elm, attrs) { elm.dataTable(); } }
});
And in the HTML:
<table class="table table-hover dataTable dataTable-columnfilter " datatable-setup="">
trouble shooting if the above doesnt work for you.
1) note that 'datatableSetup' is the equivalent of 'datatable-setup'. Angular changes the format into camel case.
2) make sure that app is defined before the directive. e.g. simple app definition and directive.
var app = angular.module('app', []);
app.directive('datatableSetup', function () {
return { link: function (scope, elm, attrs) { elm.dataTable(); } }
});
You may simple get it with s3cmd command:
s3cmd get --recursive --continue s3://test-bucket local-directory/
Putting each of your top-level windows into it's own separate class gives you code re-use and better code organization. Any buttons and relevant methods that are present in the window should be defined inside this class. Here's an example (taken from here):
import tkinter as tk
class Demo1:
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
self.button1 = tk.Button(self.frame, text = 'New Window', width = 25, command = self.new_window)
self.button1.pack()
self.frame.pack()
def new_window(self):
self.newWindow = tk.Toplevel(self.master)
self.app = Demo2(self.newWindow)
class Demo2:
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
self.quitButton.pack()
self.frame.pack()
def close_windows(self):
self.master.destroy()
def main():
root = tk.Tk()
app = Demo1(root)
root.mainloop()
if __name__ == '__main__':
main()
Also see:
Hope that helps.
Please note that since Spring Boot 1.3.0.M1, you are able to build fully executable jars using Maven and Gradle.
For Maven, just include the following in your pom.xml
:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<executable>true</executable>
</configuration>
</plugin>
For Gradle add the following snippet to your build.gradle
:
springBoot {
executable = true
}
The fully executable jar contains an extra script at the front of the file, which allows you to just symlink your Spring Boot jar to init.d
or use a systemd
script.
init.d
example:
$ln -s /var/yourapp/yourapp.jar /etc/init.d/yourapp
This allows you to start, stop and restart your application like:
$/etc/init.d/yourapp start|stop|restart
Or use a systemd
script:
[Unit]
Description=yourapp
After=syslog.target
[Service]
ExecStart=/var/yourapp/yourapp.jar
User=yourapp
WorkingDirectory=/var/yourapp
SuccessExitStatus=143
[Install]
WantedBy=multi-user.target
More information at the following links:
Another option is to use Descendant selectors
HTML:
<div class="social">
<p class="first">burrito</p>
<p class="last">chimichanga</p>
</div>
Reference first one in CSS: .social .first { color: blue; }
Reference last one in CSS: .social .last { color: green; }
Jsfiddle: https://jsfiddle.net/covbtpaq/153/
I highly recommend the reading of a lecture in SciPy-lectures organization:
https://scipy-lectures.org/intro/language/reusing_code.html
It explains all the commented doubts.
But, new paths can be easily added and avoiding duplication with the following code:
import sys
new_path = 'insert here the new path'
if new_path not in sys.path:
sys.path.append(new_path)
import funcoes_python #Useful python functions saved in a different script
echo $line | tr " " "\n"
gives the output similar to those of most of the answers above; without using loops.
In your case, you also mention ll=<...output...>
,
so, (given that I don't know much python and assuming you need to assign output to a variable),
ll=`echo $line | tr " " "\n"`
should suffice (remember to echo "$ll"
instead of echo $ll
)
By closing and opening, the main form usually runs all related queries (including the subform related ones). I had a similar problem and resolved it by adding the following to Save Command button on click event.
DoCmd.Close acForm, "formname", acSaveYes
DoCmd.OpenForm "formname"
If there are duplicate keys in the first list that map to different values in the second list, like a 1-to-many relationship, but you need the values to be combined or added or something instead of updating, you can do this:
i = iter(["a", "a", "b", "c", "b"])
j = iter([1,2,3,4,5])
k = list(zip(i, j))
for (x,y) in k:
if x in d:
d[x] = d[x] + y #or whatever your function needs to be to combine them
else:
d[x] = y
In that example, d == {'a': 3, 'c': 4, 'b': 8}
My Java version was the 1.6 and I found that was using 1.7 with CDI however after that I changed the Java version to 1.7 and import the package javax.faces.bean.ManagedBean and everything worked.
Thanks @PM77-1
Just use break, like that:
int cont = 0;
foreach (ListViewItem lvi in listView.Items) {
if(cont==50) { //if listViewItem reach 50 break out.
break;
}
cont++; //increment cont.
}
Run this Command
alter user myuser with superuser;
If you want to see the permission to a user run following command
\du
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
vector<string>V;
int num;
cin>>num;
string input;
while (cin>>input && num != 0) //enter any non-integer to end the loop!
{
//cin>>input;
V.push_back(input);
num--;
if(num==0)
{
vector<string>::iterator it;
for(it=V.begin();it!=V.end();it++)
cout<<*it<<endl;
};
}
return 0;
};
Define myurl command:
\def\myurl{\hfil\penalty 100 \hfilneg \hbox}
I don't want to cause line overflows,
I'd just rather LaTeX insert linebreaks before
\myurl{\tt http://stackoverflow.com/questions/1012799/}
regions rather than inside them.
Following on from Richard's comment. Here's the easy way to convert your file to UNIX line endings. If you're like me you created it in Windows Notepad and then tried to run it in Linux - bad idea.
Unix script file (*.sh;*.bsh)
chmod 755 the_script_filename
./the_script_filename
Any other problems try this link.
In case someone else finds this topic while using localhost
in the file URIs - Internet Explorer acts completely different if the host name is localhost
or 127.0.0.1
- if you use the actual hostname, it works fine (from trusted sites/intranet zone).
Another big difference between IE and FF - IE is fine with uris like file://server/share/file.txt
but FF requires additional slashes file:////server/share/file.txt
.
At the end of foo()
, create a Timer
which calls foo()
itself after 10 seconds.
Because, Timer
create a new thread
to call foo()
.
You can do other stuff without being blocked.
import time, threading
def foo():
print(time.ctime())
threading.Timer(10, foo).start()
foo()
#output:
#Thu Dec 22 14:46:08 2011
#Thu Dec 22 14:46:18 2011
#Thu Dec 22 14:46:28 2011
#Thu Dec 22 14:46:38 2011
If response is in json and not a string then
alert(response.id);
or
alert(response['id']);
otherwise
var response = JSON.parse('{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}');
response.id ; //# => 2231f87c-a62c-4c2c-8f5d-b76d11942301
If you want to use the reset_index
method and also preserve your existing index you should use:
df.reset_index().set_index('index', drop=False)
or to change it in place:
df.reset_index(inplace=True)
df.set_index('index', drop=False, inplace=True)
For example:
print(df)
gi ptt_loc
0 384444683 593
4 384444684 594
9 384444686 596
print(df.reset_index())
index gi ptt_loc
0 0 384444683 593
1 4 384444684 594
2 9 384444686 596
print(df.reset_index().set_index('index', drop=False))
index gi ptt_loc
index
0 0 384444683 593
4 4 384444684 594
9 9 384444686 596
And if you want to get rid of the index label you can do:
df2 = df.reset_index().set_index('index', drop=False)
df2.index.name = None
print(df2)
index gi ptt_loc
0 0 384444683 593
4 4 384444684 594
9 9 384444686 596
simple solution is this:
game.js:
document.addEventListener('click', printMousePos, true);
function printMousePos(e){
cursorX = e.pageX;
cursorY= e.pageY;
$( "#test" ).text( "pageX: " + cursorX +",pageY: " + cursorY );
}
There is also this useful function on String: components(separatedBy: String)
let string = "1;2;3"
let array = string.components(separatedBy: ";")
print(array) // returns ["1", "2", "3"]
Works well to deal with strings separated by a character like ";" or even "\n"
You can add values to the HttpWebRequest.Headers collection.
According to MSDN, it should be supported in windows phone: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.headers%28v=vs.95%29.aspx
You can use the StringUtils.compare("a", "b")
If you have a text as
var sampleText ="ä_öü_ßÄ_ TESTED Ö_Ü!@#$%^&())(&&++===.XYZ"
To replace all special character (!@#$%^&())(&&++= ==.) without replacing the characters(including umlaut)
Use below regex
sampleText = sampleText.replace(/[`~!@#$%^&*()|+-=?;:'",.<>{}[]\/\s]/gi,'');
OUTPUT : sampleText = "ä_öü_ßÄ____TESTED_Ö_Ü_____________________XYZ"
This would replace all with an underscore which is provided as second argument to the replace function.You can add whatever you want as per your requirement
I know it has been quite sometime that you asked this but, if someone else needs, I did what was saying here " How to upload a project to Github " and after the top answer of this question right here. And after was the top answer was saying here "git error: failed to push some refs to" I don't know what exactly made everything work. But now is working.
If you are trying to load a file which is not in the same directory as your Java class, you've got to use the runtime directory structure rather than the one which appears at design time.
To find out what the runtime directory structure is, check your {root project dir}/target/classes directory. This directory is accessible via the "." URL.
Based on user4284592's answer, the following worked for me:
ClassLoader cl = getClass().getClassLoader();
File file = new File(cl.getResource("./docs/doc.pdf").getFile());
with the following directory structure:
{root dir}/target/classes/docs/doc.pdf
Here's an explanation, so you don't just blindly copy and paste my code:
For your reference, I believe you can "hard cut" commits out of your current branch not only with git reset --hard, but also with the following command:
git checkout -B <branch-name> <SHA>
In fact, if you don't care about checking out, you can set the branch to whatever you want with:
git branch -f <branch-name> <SHA>
This would be a programmatic way to remove commits from a branch, for instance, in order to copy new commits to it (using rebase).
Suppose you have a branch that is disconnected from master because you have taken sources from some other location and dumped it into the branch.
You now have a branch in which you have applied changes, let's call it "topic".
You will now create a duplicate of your topic branch and then rebase it onto the source code dump that is sitting in branch "dump":
git branch topic_duplicate topic
git rebase --onto dump master topic_duplicate
Now your changes are reapplied in branch topic_duplicate based on the starting point of "dump" but only the commits that have happened since "master". So your changes since master are now reapplied on top of "dump" but the result ends up in "topic_duplicate".
You could then replace "dump" with "topic_duplicate" by doing:
git branch -f dump topic_duplicate
git branch -D topic_duplicate
Or with
git branch -M topic_duplicate dump
Or just by discarding the dump
git branch -D dump
Perhaps you could also just cherry-pick after clearing the current "topic_duplicate".
What I am trying to say is that if you want to update the current "duplicate" branch based off of a different ancestor you must first delete the previously "cherrypicked" commits by doing a git reset --hard <last-commit-to-retain>
or git branch -f topic_duplicate <last-commit-to-retain>
and then copying the other commits over (from the main topic branch) by either rebasing or cherry-picking.
Rebasing only works on a branch that already has the commits, so you need to duplicate your topic branch each time you want to do that.
Cherrypicking is much easier:
git cherry-pick master..topic
So the entire sequence will come down to:
git reset --hard <latest-commit-to-keep>
git cherry-pick master..topic
When your topic-duplicate branch has been checked out. That would remove previously-cherry-picked commits from the current duplicate, and just re-apply all of the changes happening in "topic" on top of your current "dump" (different ancestor). It seems a reasonably convenient way to base your development on the "real" upstream master while using a different "downstream" master to check whether your local changes also still apply to that. Alternatively you could just generate a diff and then apply it outside of any Git source tree. But in this way you can keep an up-to-date modified (patched) version that is based on your distribution's version while your actual development is against the real upstream master.
So just to demonstrate:
Hope this helps someone. I was meaning to rewrite this, but I cannot manage now. Regards.
Go to apache-tomcat\conf folder add these lines in
tomcat-users.xml file
<role rolename="manager-gui"/>
<user username="admin" password="admin" roles="manager-gui"/>
and restart server
@Min
and @Max
are used for validating numeric fields which could be String
(representing number), int
, short
, byte
etc and their respective primitive wrappers.
@Size
is used to check the length constraints on the fields.
As per documentation @Size
supports String
, Collection
, Map
and arrays
while @Min
and @Max
supports primitives and their wrappers. See the documentation.
Arrays have numerical indexes. So,
a = new Array();
a['a1']='foo';
a['a2']='bar';
and
b = new Array(2);
b['b1']='foo';
b['b2']='bar';
are not adding elements to the array, but adding .a1
and .a2
properties to the a
object (arrays are objects too). As further evidence, if you did this:
a = new Array();
a['a1']='foo';
a['a2']='bar';
console.log(a.length); // outputs zero because there are no items in the array
Your third option:
c=['c1','c2','c3'];
is assigning the variable c
an array with three elements. Those three elements can be accessed as: c[0]
, c[1]
and c[2]
. In other words, c[0] === 'c1'
and c.length === 3
.
Javascript does not use its array functionality for what other languages call associative arrays where you can use any type of key in the array. You can implement most of the functionality of an associative array by just using an object in javascript where each item is just a property like this.
a = {};
a['a1']='foo';
a['a2']='bar';
It is generally a mistake to use an array for this purpose as it just confuses people reading your code and leads to false assumptions about how the code works.
The API's will provide full access to LIVE data, and developers can thus provide applications and develop against the API without paying licencing fees. Consumers will pay for any data received from the apps provided by third party developers, and so BB will grow their audience and revenue in that way.
NOTE: Bloomberg is offering this programming interface (BLPAPI) under a free-use license. This license does not include nor provide access to any Bloomberg data or content.
Run Gunicorn with --log-level debug
.
It should give you an app stack trace.
In case this happens to anyone else who tried both alphazero and Paul's method and still didn't work.
For me, eclipse somehow 'cached' the compile errors even after doing a Project > Clean...
I had to uncheck Project > Build Automatically, then do a Project > Clean, and then build again.
Also, when in doubt, try restarting Eclipse. This can fix a lot of awkward, unexplainable errors.
No. Go to database tools (for 2007) and click checkmark on the Message Bar. Then, after the message bar apears, click on Options, and then Enable. Hope this helps.
Dimitri
from selenium import webdriver
driver = webdriver.Firefox()
driver.implicitly_wait(12)
driver.set_page_load_timeout(10)
def _post_selenium(self, url: str, data: dict):
input_template = '{k} <input type="text" name="{k}" id="{k}" value="{v}"><BR>\n'
inputs = ""
if data:
for k, v in data.items():
inputs += input_template.format(k=k, v=v)
html = f'<html><body>\n<form action="{url}" method="post" id="formid">\n{inputs}<input type="submit" id="inputbox">\n</form></body></html>'
html_file = os.path.join(os.getcwd(), 'temp.html')
with open(html_file, "w") as text_file:
text_file.write(html)
driver.get(f"file://{html_file}")
driver.find_element_by_id('inputbox').click()
_post_selenium("post.to.my.site.url", {"field1": "val1"})
driver.close()
Swift 3 & IOS 10.2
UIApplication.shared.open(URL(string: "http://www.stackoverflow.com")!, options: [:], completionHandler: nil)
Swift 3 & IOS 10.2
My suggestion for google maps api v3 would be(don't think it can be done more effeciently):
gmap : {
fitBounds: function(bounds, mapId)
{
//incoming: bounds - bounds object/array; mapid - map id if it was initialized in global variable before "var maps = [];"
if (bounds==null) return false;
maps[mapId].fitBounds(bounds);
}
}
In the result u will fit all points in bounds in your map window.
Example works perfectly and u freely can check it here www.zemelapis.lt
PyDub (http://pydub.com/) has not been mentioned and that should be fixed. IMO this is the most comprehensive library for reading audio files in Python right now, although not without its faults. Reading a wav file:
from pydub import AudioSegment
audio_file = AudioSegment.from_wav('path_to.wav')
# or
audio_file = AudioSegment.from_file('path_to.wav')
# do whatever you want with the audio, change bitrate, export, convert, read info, etc.
# Check out the API docs http://pydub.com/
PS. The example is about reading a wav file, but PyDub can handle a lot of various formats out of the box. The caveat is that it's based on both native Python wav support and ffmpeg, so you have to have ffmpeg installed and a lot of the pydub capabilities rely on the ffmpeg version. Usually if ffmpeg can do it, so can pydub (which is quite powerful).
Non-disclaimer: I'm not related to the project, but I am a heavy user.
zero(myarray);
is all you need in C++.
Just add this to a header:
template<typename T, size_t SIZE> inline void zero(T(&arr)[SIZE]){
memset(arr, 0, SIZE*sizeof(T));
}
For me, it was getting the nuget package Microsoft.Net.Http .(https://blogs.msdn.microsoft.com/bclteam/p/httpclient/)
Easy as this:
string[] folders = System.IO.Directory.GetDirectories(@"C:\My Sample Path\","*", System.IO.SearchOption.AllDirectories);
My scenario was a bit different. I had an object with nested objects as well as functions. Therefore, Object.assign()
and JSON.stringify()
were not solutions to my problem. Using third-party libraries was not an option for me neither.
Hence, I decided to make a simple function to use built-in methods to copy an object with its literal properties, its nested objects, and functions.
let deepCopy = (target, source) => {
Object.assign(target, source);
// check if there's any nested objects
Object.keys(source).forEach((prop) => {
/**
* assign function copies functions and
* literals (int, strings, etc...)
* except for objects and arrays, so:
*/
if (typeof(source[prop]) === 'object') {
// check if the item is, in fact, an array
if (Array.isArray(source[prop])) {
// clear the copied referenece of nested array
target[prop] = Array();
// iterate array's item and copy over
source[prop].forEach((item, index) => {
// array's items could be objects too!
if (typeof(item) === 'object') {
// clear the copied referenece of nested objects
target[prop][index] = Object();
// and re do the process for nested objects
deepCopy(target[prop][index], item);
} else {
target[prop].push(item);
}
});
// otherwise, treat it as an object
} else {
// clear the copied referenece of nested objects
target[prop] = Object();
// and re do the process for nested objects
deepCopy(target[prop], source[prop]);
}
}
});
};
Here's a test code:
let a = {
name: 'Human',
func: () => {
console.log('Hi!');
},
prop: {
age: 21,
info: {
hasShirt: true,
hasHat: false
}
},
mark: [89, 92, { exam: [1, 2, 3] }]
};
let b = Object();
deepCopy(b, a);
a.name = 'Alien';
a.func = () => { console.log('Wassup!'); };
a.prop.age = 1024;
a.prop.info.hasShirt = false;
a.mark[0] = 87;
a.mark[1] = 91;
a.mark[2].exam = [4, 5, 6];
console.log(a); // updated props
console.log(b);
For efficiency-related concerns, I believe this is the simplest and most efficient solution to the problem I had. I would appreciate any comments on this algorithm that could make it more efficient.
You can use AJAX for that. Whenever you scan a barcode, your scanner will act as if it is a keyboard typing into your input type="text"
components. With JavaScript, capture the corresponding event, and send HTTP REQUEST and process responses accordingly.
Its really working if we use Doctype on our web page jquery(window) will return the viewport height else it will return the complete document height.
Define the following tag on the top of your web page:
<!DOCTYPE html>
I solved the problem by changing my AndroidManifest.xml
.
old : <uses-permission android:name="android.permission.internet"/>
new: <uses-permission android:name="android.permission.INTERNET"/>
I faced this problem for one month,Putting context tag inside server.xml is not safe it affect context elements deploying for all other host ,for big apps it take connection errors also not good isolation for example you may access other sites by folder name domain2.com/domain1Folder !! also database session connections loaded twice ! the other way is put ROOT.xml file that has context tag with full path such :
<Context path="" docBase="/var/lib/tomcat7/webapps/ROOT" />
in conf/catalina/webappsfoldername and deploy war file as ROOT.war inside webappsfoldername and also specify host such
<Host name="domianname" appBase="webapps2" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false" >
<Logger className="org.apache.catalina.logger.FileLogger"
directory="logs" prefix="localhost_log." suffix=".txt"
timestamp="true"/>
</Host>
In this approach also for same type apps user sessions has not good isolation ! you may inside app1 if app1 same as app2 you may after login by server side session automatically can login to app2 ?! So you have to keep users session in client side cache and not with jsessionid ! we may change engine name from localhost to solve it. but let say playing with tomcat need more time than play with other cats!
Try this:
SET /A ARGS_COUNT=0
FOR %%A in (%*) DO SET /A ARGS_COUNT+=1
ECHO %ARGS_COUNT%
parseInt(num) === num
when passed a number, parseInt()
just returns the number as int:
parseInt(3.3) === 3.3 // false because 3 !== 3.3
parseInt(3) === 3 // true
give your boxes the class foo
(or whatever) and add the css
.foo{
float: left;
}
Use the dist()
function, but you need to form a matrix from the two inputs for the first argument to dist()
:
dist(rbind(x1, x2))
For the input in the OP's question we get:
> dist(rbind(x1, x2))
x1
x2 7.94821
a single value that is the Euclidean distance between x1
and x2
.
You can't set the field having data-type "text". Only because of that thing you are getting this error. Try to change the data-type with int
Ok, finally found the solution.
Probably due to lack of experience with ReactJS and web development...
var Task = React.createClass({
render: function() {
var percentage = this.props.children + '%';
....
<div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
...
I created the percentage variable outside in the render function.
you can just wrap it into another element and call html
after that:
$('<div><iframe width="854" height="480" src="http://www.youtube.com/embed/gYKqrjq5IjU?feature=oembed" frameborder="0" allowfullscreen></iframe></div>').html();
note that outerHTML
doesn't exist on older browsers but innerHTML
still does (it doesn't exist for example in ff < 11 while it's still used on many older computers)
Swift 3
let vc0 : ViewController1 = ViewController1()
let vc2: NavigationController1 = NavigationController1(rootViewController: vc0)
self.present(vc2, animated: true, completion: nil)
What I use everywhere :
Runtime.getRuntime().exec("pm clear me.myapp");
Executing above piece of code closes application and removes all databases and shared preferences
A CRC is pretty simple; you take a polynomial represented as bits and the data, and divide the polynomial into the data (or you represent the data as a polynomial and do the same thing). The remainder, which is between 0 and the polynomial is the CRC. Your code is a bit hard to understand, partly because it's incomplete: temp and testcrc are not declared, so it's unclear what's being indexed, and how much data is running through the algorithm.
The way to understand CRCs is to try to compute a few using a short piece of data (16 bits or so) with a short polynomial -- 4 bits, perhaps. If you practice this way, you'll really understand how you might go about coding it.
If you're doing it frequently, a CRC is quite slow to compute in software. Hardware computation is much more efficient, and requires just a few gates.
Short answer in bolds:
collect
is mainly to serialize
(loss of parallelism preserving all other data characteristics of the dataframe)
For example with a PrintWriter pw
you can't do direct df.foreach( r => pw.write(r) )
, must to use collect
before foreach
, df.collect.foreach(etc)
.
PS: the "loss of parallelism" is not a "total loss" because after serialization it can be distributed again to executors.
select
is mainly to select columns, similar to projection in relational algebra
(only similar in framework's context because Spark select
not deduplicate data).
So, it is also a complement of filter
in the framework's context.
Commenting explanations of other answers: I like the Jeff's classification of Spark operations in transformations (as select
) and actions (as collect
). It is also good remember that transforms (including select
) are lazily evaluated.
On Solaris, you can use the option -I to read the filenames that you would normally state on the command line from a file. In contrast to the command line, this can create tar archives with hundreds of thousands of files (just did that).
So the example would read
tar -cvf allfiles.tar -I mylist.txt
If you have a js file that references the jquery, it could be because the js file is in the body and not in the head section (that was my problem). You should move your js file to the head section AFTER the jquery.js reference.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js"></script>
<script src="myfile.js" type="text/javascript"></script>
</head>
<body>
</body>
</html>
function checkLectureStatus($lectureName) {
global $con;
$lectureName = mysql_real_escape_string($lectureName);
$sql = "SELECT 1 FROM preditors_assigned WHERE lecture_name='$lectureName'";
$result = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
if (mysql_fetch_row($result)) {
return 'Assigned';
}
return 'Available';
}
however you have to use some abstraction library for the database access.
the code would become
function checkLectureStatus($lectureName) {
$res = db::getOne("SELECT 1 FROM preditors_assigned WHERE lecture_name=?",$lectureName);
if($res) {
return 'Assigned';
}
return 'Available';
}
byte test[] = new byte[3];
test[0] = 0x0A;
test[1] = 0xFF;
test[2] = 0x01;
for (byte theByte : test)
{
System.out.println(Integer.toHexString(theByte));
}
NOTE: test[1] = 0xFF; this wont compile, you cant put 255 (FF) into a byte, java will want to use an int.
you might be able to do...
test[1] = (byte) 0xFF;
I'd test if I was near my IDE (if I was near my IDE I wouln't be on Stackoverflow)
If you need special memory alignment on the object controlled by shared_ptr, you cannot rely on make_shared, but I think it's the only one good reason about not using it.
employees.ToList().Foreach(u=> { u.SomeProperty = null; u.OtherProperty = null; });
Notice that I used semicolons after each set statement
that is -->
u.SomeProperty = null;
u.OtherProperty = null;
I hope this will definitely solve your problem.
SELECT SCHEMA_NAME
FROM INFORMATION_SCHEMA.SCHEMATA
WHERE SCHEMA_NAME = 'DBName'
If you just need to know if a db exists so you won't get an error when you try to create it, simply use (From here):
CREATE DATABASE IF NOT EXISTS DBName;
This problem mostly occurs due to the error in setText()
method
Solution is simple put your Integer
value by converting into string
type
as
textview.setText(Integer.toString(integer_value));
You can also use a Bridged Network (or "Bridge Adapter", in newer versions) in network settings. This will put your VM in a VLAN with your machine. So you can just ssh into the VM like this.
ssh user@IP_OF_VM
/***Your Code***/
public void paintComponent(Graphics g){
/***Your Code***/
g.setColor(Color.RED);
g.fillOval(50,50,20,20);
}
g.fillOval(x-axis,y-axis,width,height);
conda create --name new_name --copy --clone old_name
is better
I use conda create --name new_name --clone old_name
which is without --copy
but encountered pip breaks...
the following url may help Installing tensorflow in cloned conda environment breaks conda environment it was cloned from
My point is that I just want the raw DATETIME string, so I can parse it myself as is.
That makes me think that your "workaround" is not a workaround, but in fact the only way to get the value from the database into your code:
SELECT CAST(add_date AS CHAR) as add_date
By the way, some more notes from the MySQL documentation:
MySQL Constraints on Invalid Data:
Before MySQL 5.0.2, MySQL is forgiving of illegal or improper data values and coerces them to legal values for data entry. In MySQL 5.0.2 and up, that remains the default behavior, but you can change the server SQL mode to select more traditional treatment of bad values such that the server rejects them and aborts the statement in which they occur.
[..]
If you try to store NULL into a column that doesn't take NULL values, an error occurs for single-row INSERT statements. For multiple-row INSERT statements or for INSERT INTO ... SELECT statements, MySQL Server stores the implicit default value for the column data type.
MySQL 5.x Date and Time Types:
MySQL also allows you to store '0000-00-00' as a “dummy date” (if you are not using the NO_ZERO_DATE SQL mode). This is in some cases more convenient (and uses less data and index space) than using NULL values.
[..]
By default, when MySQL encounters a value for a date or time type that is out of range or otherwise illegal for the type (as described at the beginning of this section), it converts the value to the “zero” value for that type.
Am I doing something wrong here?
Yes, you are. One servlet container is already running on port 8080 and you are trying to run another one on port 8080 again.
Either restart the server (If there is button for that in STS) or stop and start it
You should always pay attention to types.
Although they all seem like strings, "Hello"
and ",world"
are literals.
And in your example, exclam
is a std::string
object.
C++ has an operator overload that takes a std::string
object and adds another string to it. When you concatenate a std::string
object with a literal it will make the appropriate casting for the literal.
But if you try to concatenate two literals, the compiler won't be able to find an operator that takes two literals.
Use an abstract class if you want to provide some basic implementations.
You just use this code
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:baselineAligned="false">
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.80">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_vertical|start"
android:paddingBottom="5dp"
android:paddingTop="5dp">
<Spinner
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/spiner_back"
android:visibility="visible" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|end"
android:src="@drawable/ic_arrow_drop_down_black_24dp" />
</FrameLayout>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.20">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/colorred"
android:fontFamily="@font/raleway_extrabold"
android:text="GO"
android:textColor="@color/colorwhite" />
</LinearLayout>
</LinearLayout>
And This is background which i used...
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="5dp" />
<solid android:color="@color/colorwhite" />
add this cookie plugin for jquery.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
Add XAttribute
in the constructor of the XElement
, like
new XElement("Conn", new XAttribute("Server", comboBox1.Text));
You can also add multiple attributes or elements via the constructor
new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));
or you can use the Add-Method of the XElement
to add attributes
XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);
Answering your question in this format is quite challenging.
On the other hand you ask about navigation and then about current $state
acting all weird.
For the first I'd say it's too broad question and for the second I'd say... well, you are doing something wrong or missing the obvious :)
Take the following controller:
app.controller('MainCtrl', function($scope, $state) {
$scope.state = $state;
});
Where app
is configured as:
app.config(function($stateProvider) {
$stateProvider
.state('main', {
url: '/main',
templateUrl: 'main.html',
controller: 'MainCtrl'
})
.state('main.thiscontent', {
url: '/thiscontent',
templateUrl: 'this.html',
controller: 'ThisCtrl'
})
.state('main.thatcontent', {
url: '/thatcontent',
templateUrl: 'that.html'
});
});
Then simple HTML template having
<div>
{{ state | json }}
</div>
Would "print out" e.g. the following
{
"params": {},
"current": {
"url": "/thatcontent",
"templateUrl": "that.html",
"name": "main.thatcontent"
},
"transition": null
}
I put up a small example showing this, using ui.router
and pascalprecht.translate
for the menus. I hope you find it useful and figure out what is it you are doing wrong.
Plunker here http://plnkr.co/edit/XIW4ZE
Screencap
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
You are replacing the starting tag and then putting that back in innerHTML
, so the code will be invalid. Make all the replacements before you put the code back in the element:
var html = strMessage1.innerHTML;
html = html.replace( /aaaaaa./g,'<a href=\"http://www.google.com/');
html = html.replace( /.bbbbbb/g,'/world\">Helloworld</a>');
strMessage1.innerHTML = html;
How to set default values in twig: http://twig.sensiolabs.org/doc/filters/default.html
{{ my_var | default("my_var doesn't exist") }}
Or if you don't want it to display when null:
{{ my_var | default("") }}
try this
In your controller use
> $scope.onMapOverlayCompleted = onMapOverlayCompleted;
>
> function onMapOverlayCompleted(e) {
>
> e.overlay.getPath().getArray().forEach(function (position) {
> console.log('lat', position.lat());
> console.log('lng', position.lng());
> });
>
> }
**In Your html page , include drawning manaer**
<ng-map id="geofence-map" zoom="8" center="current" default-style="true" class="map-layout map-area"
tilt="45"
heading="90">
<drawing-manager
on-overlaycomplete="onMapOverlayCompleted()"
drawing-control-options="{position: 'TOP_CENTER',drawingModes:['polygon','circle']}"
drawingControl="true"
drawingMode="null"
markerOptions="{icon:'www.example.com/icon'}"
rectangleOptions="{fillColor:'#B43115'}"
circleOptions="{fillColor: '#F05635',fillOpacity: 0.50,strokeWeight: 5,clickable: false,zIndex: 1,editable: true}">
</drawing-manager>
</ng-map>
Either set the openssl present in Git as your default openssl and include that into your path in environmental variables (quick way)
OR
Escape characters are dependent on whatever system is interpreting them. \n
is interpreted as a newline character by many programming languages, but that doesn't necessarily hold true for the other utilities you mention. Even if they do treat \n
as newline, there may be some other techniques to get them to behave how you want. You would have to consult their documentation (or see other answers here).
For DOS/Windows systems, the newline is actually two characters: Carriage Return (ASCII 13, AKA \r
), followed by Line Feed (ASCII 10). On Unix systems (including Mac OSX) it's just Line Feed. On older Macs it was a single Carriage Return.
Below are the methods which have always worked for me
Set the display of the parent div to display: flex;
and the you can align the child elements inside the div using the justify-content: center;
(to align the items on main axis) and align-items: center;
(to align the items on cross axis).
If you have more than one child element and want to control the way they are arranged (column/rows), then you can also add flex-direction
property.
Working example:
.parent {_x000D_
align-items: center;_x000D_
border: 1px solid black;_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
height: 250px;_x000D_
width: 250px;_x000D_
}_x000D_
_x000D_
.child {_x000D_
border: 1px solid black;_x000D_
height: 50px;_x000D_
width: 50px;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child"></div>_x000D_
</div>
_x000D_
2. (older method) Using position, margin properties and fixed size
Working example:
.parent {_x000D_
border: 1px solid black;_x000D_
height: 250px;_x000D_
position: relative;_x000D_
width: 250px;_x000D_
}_x000D_
_x000D_
.child {_x000D_
border: 1px solid black;_x000D_
margin: auto;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
height: 50px;_x000D_
position: absolute;_x000D_
width: 50px;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child"></div>_x000D_
</div>
_x000D_
The answers are commonly found in Java books.
cloning: If you don't override clone method, the default behavior is shallow copy. If your objects have only primitive member variables, it's totally ok. But in a typeless language with another object as member variables, it's a headache.
serialization/deserialization
$new_object = unserialize(serialize($your_object))
This achieves deep copy with a heavy cost depending on the complexity of the object.
What about this one :
<DockPanel Margin="8">
<Border CornerRadius="6" BorderBrush="Gray" Background="LightGray" BorderThickness="2" DockPanel.Dock="Top">
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="14" Padding="0 0 8 0" HorizontalAlignment="Center" VerticalAlignment="Center">Search:</TextBlock>
<TextBox x:Name="txtSearchTerm" HorizontalAlignment="Center" VerticalAlignment="Center" />
<Image Source="lock.png" Width="32" Height="32" HorizontalAlignment="Center" VerticalAlignment="Center" />
</StackPanel>
</Border>
<StackPanel Orientation="Horizontal" DockPanel.Dock="Bottom" Height="25" />
</DockPanel>
If you are using Git Extensions: go into the Commit screen, there should be a checkbox that says "Amend Commit" at the bottom, as can be seen below:
Once you have the package name, as described Chris Smith's answer, you could/should use an intent url for the link. It's a special format URL that will launch the package if the user has already installed it, or open the play store at the application's page if not...
intent://#Intent;package=qualified.package.name;end
The app needs to support this, with an activity tagged as browsable, but many will.
This should work
gsub('\u009c','','\u009cYes yes for ever for ever the boys ')
"Yes yes for ever for ever the boys "
Here 009c is the hexadecimal number of unicode. You must always specify 4 hexadecimal digits. If you have many , one solution is to separate them by a pipe:
gsub('\u009c|\u00F0','','\u009cYes yes \u00F0for ever for ever the boys and the girls')
"Yes yes for ever for ever the boys and the girls"
CAST both fields to datatype DATE and you can use a minus:
(CAST(MAX(joindate) AS date) - CAST(MIN(joindate) AS date)) as DateDifference
Test case:
SELECT (CAST(MAX(joindate) AS date) - CAST(MIN(joindate) AS date)) as DateDifference
FROM
generate_series('2014-01-01'::timestamp, '2014-02-01'::timestamp, interval '1 hour') g(joindate);
Result: 31
Or create a function datediff():
CREATE OR REPLACE FUNCTION datediff(timestamp, timestamp)
RETURNS int
LANGUAGE sql
AS
$$
SELECT CAST($1 AS date) - CAST($2 AS date) as DateDifference
$$;
Try layout()
which I have used for this in the past by simply creating an empty plot below, properly scaled at around 1/4 or so and placing the legend parts manually in it.
There are some older questions here about legend()
which should get you started.
There are lots of options out there. Many of which are available as downloadable software as well as public websites. I do not think many of them expect to be used as API's unless they explicitly state that.
The one that I found effective was Enju which did not have the character limit that the Marc's Carnagie Mellon link had. Marc also mentioned a VISL scanner in comments, but that requires java in the browser, which is a non-starter for me.
Note that recently, Google has offered a new NLP Machine Learning API that providers amoung other features, a automatic sentence parser. I will likely not update this answer again, especially since the question is closed, but I suspect that the other big ML cloud stacks will soon support the same.
You can do this through a regular UPDATE
with a JOIN
UPDATE T1
SET Description = T2.Description
FROM Table1 T1
JOIN Table2 T2
ON T2.ID = T1.DescriptionId
Add a unique id to all your instances, i.e.
public interface Idable {
int id();
}
public class IdGenerator {
private static int id = 0;
public static synchronized int generate() { return id++; }
}
public abstract class AbstractSomething implements Idable {
private int id;
public AbstractSomething () {
this.id = IdGenerator.generate();
}
public int id() { return id; }
}
Extend from AbstractSomething and query this property. Will be safe inside a single vm (assuming no game playing with classloaders to get around statics).
I discovered while following the above suggestions that for line in f: does not work for a pandas dataframe (not that anyone said it would) because the end of file in a dataframe is the last column, not the last row. for example if you have a data frame with 3 fields (columns) and 9 records (rows), the for loop will stop after the 3rd iteration, not after the 9th iteration. Teresa
This isn't as straightforward as opening a plain text file and will require some sort of external module since nothing is built-in to do this. Here are some options:
If possible, you may want to consider exporting the excel spreadsheet as a CSV file and then using the built-in python csv module to read it:
Its not very elegant but in case you cant change the creation of dictionary, and all you need is a dirty hack, how about this:
var item = MyDictionary.Where(x => x.Key.ToLower() == MyIndex.ToLower()).FirstOrDefault();
if (item != null)
{
TheValue = item.Value;
}
SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
where entityManagerFactory
is an JPA EntityManagerFactory
.
static void InsertSettings(IEnumerable<Entry> settings) {
using (SqlConnection oConnection = new SqlConnection("Data Source=(local);Initial Catalog=Wip;Integrated Security=True")) {
oConnection.Open();
using (SqlTransaction oTransaction = oConnection.BeginTransaction()) {
using (SqlCommand oCommand = oConnection.CreateCommand()) {
oCommand.Transaction = oTransaction;
oCommand.CommandType = CommandType.Text;
oCommand.CommandText = "INSERT INTO [Setting] ([Key], [Value]) VALUES (@key, @value);";
oCommand.Parameters.Add(new SqlParameter("@key", SqlDbType.NChar));
oCommand.Parameters.Add(new SqlParameter("@value", SqlDbType.NChar));
try {
foreach (var oSetting in settings) {
oCommand.Parameters[0].Value = oSetting.Key;
oCommand.Parameters[1].Value = oSetting.Value;
if (oCommand.ExecuteNonQuery() != 1) {
//'handled as needed,
//' but this snippet will throw an exception to force a rollback
throw new InvalidProgramException();
}
}
oTransaction.Commit();
} catch (Exception) {
oTransaction.Rollback();
throw;
}
}
}
}
}
Only "keyboard focusable" elements can be focused with .focus()
. div
aren't meant to be natively focusable. You have to add tabindex="0"
attributes to it to achieve that. input
, button
, a
etc... are natively focusable.
If you want to return the altered document you need to set the option {new:true}
API reference you can use Cat.findOneAndUpdate(conditions, update, options, callback) // executes
Taken by the official Mongoose API http://mongoosejs.com/docs/api.html#findoneandupdate_findOneAndUpdate you can use the following parameters
A.findOneAndUpdate(conditions, update, options, callback) // executes
A.findOneAndUpdate(conditions, update, options) // returns Query
A.findOneAndUpdate(conditions, update, callback) // executes
A.findOneAndUpdate(conditions, update) // returns Query
A.findOneAndUpdate() // returns Query
Another implementation thats is not expressed in the official API page and is what I prefer to use is the Promise
base implementation that allow you to have .catch
where you can deal with all your various error there.
let cat: catInterface = {
name: "Naomi"
};
Cat.findOneAndUpdate({age:17}, cat,{new: true}).then((data) =>{
if(data === null){
throw new Error('Cat Not Found');
}
res.json({ message: 'Cat updated!' })
console.log("New cat data", data);
}).catch( (error) => {
/*
Deal with all your errors here with your preferred error handle middleware / method
*/
res.status(500).json({ message: 'Some Error!' })
console.log(error);
});
See my comment in @gsk3 answer. A simple example:
> m <- matrix(sample(c(NA, 1:10), 100, replace = TRUE), 10)
> d <- as.data.frame(m)
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1 4 3 NA 3 7 6 6 10 6 5
2 9 8 9 5 10 NA 2 1 7 2
3 1 1 6 3 6 NA 1 4 1 6
4 NA 4 NA 7 10 2 NA 4 1 8
5 1 2 4 NA 2 6 2 6 7 4
6 NA 3 NA NA 10 2 1 10 8 4
7 4 4 9 10 9 8 9 4 10 NA
8 5 8 3 2 1 4 5 9 4 7
9 3 9 10 1 9 9 10 5 3 3
10 4 2 2 5 NA 9 7 2 5 5
> d[is.na(d)] <- 0
> d
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1 4 3 0 3 7 6 6 10 6 5
2 9 8 9 5 10 0 2 1 7 2
3 1 1 6 3 6 0 1 4 1 6
4 0 4 0 7 10 2 0 4 1 8
5 1 2 4 0 2 6 2 6 7 4
6 0 3 0 0 10 2 1 10 8 4
7 4 4 9 10 9 8 9 4 10 0
8 5 8 3 2 1 4 5 9 4 7
9 3 9 10 1 9 9 10 5 3 3
10 4 2 2 5 0 9 7 2 5 5
There's no need to apply apply
. =)
EDIT
You should also take a look at norm
package. It has a lot of nice features for missing data analysis. =)
You can do injection on Directives, and it looks just like it does everywhere else.
app.directive('changeIt', ['myData', function(myData){
return {
restrict: 'C',
link: function (scope, element, attrs) {
scope.name = myData.name;
}
}
}]);
On Windows, you can add a quicklink for that to your explorer right click menu. Just start this registry script:
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\Folder\shell\DeleteSVN]
@="Delete SVN Folders"
[HKEY_CLASSES_ROOT\Folder\shell\DeleteSVN\command]
@="cmd.exe /c \"TITLE Removing SVN Folders in %1 && COLOR 9A && FOR /r \"%1\" %%f IN (.svn) DO RD /s /q \"%%f\" \""
This will add an item called "Delete SVN Folders" to your right click menu. This will delete all .svn folders in this folder and all subfolders.
Source (German): http://www.sjmp.de/software/alle-svn-ordner-und-dateien-loeschen/
The accepted/high-voted answers are great, but they are lacking a few nitty-gritty details. This post covers the cases on how to better handle when the shell path-name expansion (glob) fails, when filenames contain embedded newlines/dash symbols and moving the command output re-direction out of the for-loop when writing the results to a file.
When running the shell glob expansion using *
there is a possibility for the expansion to fail if there are no files present in the directory and an un-expanded glob string will be passed to the command to be run, which could have undesirable results. The bash
shell provides an extended shell option for this using nullglob
. So the loop basically becomes as follows inside the directory containing your files
shopt -s nullglob
for file in ./*; do
cmdToRun [option] -- "$file"
done
This lets you safely exit the for loop when the expression ./*
doesn't return any files (if the directory is empty)
or in a POSIX compliant way (nullglob
is bash
specific)
for file in ./*; do
[ -f "$file" ] || continue
cmdToRun [option] -- "$file"
done
This lets you go inside the loop when the expression fails for once and the condition [ -f "$file" ]
check if the un-expanded string ./*
is a valid filename in that directory, which wouldn't be. So on this condition failure, using continue
we resume back to the for
loop which won't run subsequently.
Also note the usage of --
just before passing the file name argument. This is needed because as noted previously, the shell filenames can contain dashes anywhere in the filename. Some of the shell commands interpret that and treat them as a command option when the name are not quoted properly and executes the command thinking if the flag is provided.
The --
signals the end of command line options in that case which means, the command shouldn't parse any strings beyond this point as command flags but only as filenames.
Double-quoting the filenames properly solves the cases when the names contain glob characters or white-spaces. But *nix filenames can also contain newlines in them. So we de-limit filenames with the only character that cannot be part of a valid filename - the null byte (\0
). Since bash
internally uses C
style strings in which the null bytes are used to indicate the end of string, it is the right candidate for this.
So using the printf
option of shell to delimit files with this NULL byte using the -d
option of read
command, we can do below
( shopt -s nullglob; printf '%s\0' ./* ) | while read -rd '' file; do
cmdToRun [option] -- "$file"
done
The nullglob
and the printf
are wrapped around (..)
which means they are basically run in a sub-shell (child shell), because to avoid the nullglob
option to reflect on the parent shell, once the command exits. The -d ''
option of read
command is not POSIX compliant, so needs a bash
shell for this to be done. Using find
command this can be done as
while IFS= read -r -d '' file; do
cmdToRun [option] -- "$file"
done < <(find -maxdepth 1 -type f -print0)
For find
implementations that don't support -print0
(other than the GNU and the FreeBSD implementations), this can be emulated using printf
find . -maxdepth 1 -type f -exec printf '%s\0' {} \; | xargs -0 cmdToRun [option] --
Another important fix is to move the re-direction out of the for-loop to reduce a high number of file I/O. When used inside the loop, the shell has to execute system-calls twice for each iteration of the for-loop, once for opening and once for closing the file descriptor associated with the file. This will become a bottle-neck on your performance for running large iterations. Recommended suggestion would be to move it outside the loop.
Extending the above code with this fixes, you could do
( shopt -s nullglob; printf '%s\0' ./* ) | while read -rd '' file; do
cmdToRun [option] -- "$file"
done > results.out
which will basically put the contents of your command for each iteration of your file input to stdout and when the loop ends, open the target file once for writing the contents of the stdout and saving it. The equivalent find
version of the same would be
while IFS= read -r -d '' file; do
cmdToRun [option] -- "$file"
done < <(find -maxdepth 1 -type f -print0) > results.out
There are multiple ways we can add a new column in pySpark.
Let's first create a simple DataFrame.
date = [27, 28, 29, None, 30, 31]
df = spark.createDataFrame(date, IntegerType())
Now let's try to double the column value and store it in a new column. PFB few different approaches to achieve the same.
# Approach - 1 : using withColumn function
df.withColumn("double", df.value * 2).show()
# Approach - 2 : using select with alias function.
df.select("*", (df.value * 2).alias("double")).show()
# Approach - 3 : using selectExpr function with as clause.
df.selectExpr("*", "value * 2 as double").show()
# Approach - 4 : Using as clause in SQL statement.
df.createTempView("temp")
spark.sql("select *, value * 2 as double from temp").show()
For more examples and explanation on spark DataFrame functions, you can visit my blog.
I hope this helps.
In Python 3.8+ you can do
import hashlib
with open("your_filename.txt", "rb") as f:
file_hash = hashlib.md5()
while chunk := f.read(8192):
file_hash.update(chunk)
print(file_hash.digest())
print(file_hash.hexdigest()) # to get a printable str instead of bytes
Consider using hashlib.blake2b
instead of md5
(just replace md5
with blake2b
in the above snippet). It's cryptographically secure and faster than MD5.
It's not as straightforward as looks. I just run into a similar question, and here is what I got: First, a little background on wikipedia.
Next, in CSS, for paper, they have pt
, which is point, or 1/72 inch. So if you want to have the same size of image as on the monitor, first you have to know the DPI/PPI of your monitor (usually 96, as mentioned on the wikipedia article), then convert it to inches, then convert it to points (divide by 72).
But then again, the browsers have all sorts of problems with printable content, for example, if you try to use float css tags, the Gecko-based browsers will cut your images mid page, even if you use page-break-inside: avoid; on your images (see here, in the Mozilla bug tracking system).
There is (much) more about printing from a browser in this article on A List Apart.
Furthermore, you have to deal width "Shrink to Fit" in the print preview, and the various paper sizes and orientations.
So either you just figure out a good image size in inches, I mean points, (7.1" * 72 = 511.2 so width: 511pt;
would work for the letter sized paper) regardless of the pixel sizes, or go width percentage widths, and base your image widths on the paper size.
Good luck...
I bet this is related to a wrong Content-Length
header sent by the peer.
My advice is to let curl set the length by itself.
The JAVA_HOME should point to the JDK home rather than the JRE home if you are going to be compiling stuff, likewise - I would try and install the JDK in a directory that doesn't include a space. Even if this is not your problem now, it can cause problems in the future!
Among other already mentioned tools you can use also readelf
(manual). It is similar to objdump
but goes more into detail. See this for the difference explanation.
$ readelf -sW /lib/liblzma.so.5 |head -n10
Symbol table '.dynsym' contains 128 entries:
Num: Value Size Type Bind Vis Ndx Name
0: 00000000 0 NOTYPE LOCAL DEFAULT UND
1: 00000000 0 FUNC GLOBAL DEFAULT UND pthread_mutex_unlock@GLIBC_2.0 (4)
2: 00000000 0 FUNC GLOBAL DEFAULT UND pthread_mutex_destroy@GLIBC_2.0 (4)
3: 00000000 0 NOTYPE WEAK DEFAULT UND _ITM_deregisterTMCloneTable
4: 00000000 0 FUNC GLOBAL DEFAULT UND memmove@GLIBC_2.0 (5)
5: 00000000 0 FUNC GLOBAL DEFAULT UND free@GLIBC_2.0 (5)
6: 00000000 0 FUNC GLOBAL DEFAULT UND memcpy@GLIBC_2.0 (5)
You want rows where that condition is true so you need a comma:
data[data$Ozone > 14, ]
e.which doesn't work in IE try e.keyCode, also you probably want to use keydown() instead of keypress() if you are targeting IE.
See http://unixpapa.com/js/key.html for more information.
The black div
will display the full 500px unless overflow:hidden
is set on the 100px li
You need to use the change directory command 'cd' to change directory
cd C:\Users\MyName\Desktop
you can use cd \d
to change the drive as well.
link for additional resources http://ss64.com/nt/cd.html
Round tripping dates through strings has always been a pain...but the docs to indicate that the 'o' specifier is the one to use for round tripping which captures the UTC state. When parsed the result will usually have Kind == Utc if the original was UTC. I've found that the best thing to do is always normalize dates to either UTC or local prior to serializing then instruct the parser on which normalization you've chosen.
DateTime now = DateTime.Now;
DateTime utcNow = now.ToUniversalTime();
string nowStr = now.ToString( "o" );
string utcNowStr = utcNow.ToString( "o" );
now = DateTime.Parse( nowStr );
utcNow = DateTime.Parse( nowStr, null, DateTimeStyles.AdjustToUniversal );
Debug.Assert( now == utcNow );
If your ListView row item refers to a separate XML file, be sure to add android:longClickable="true"
to that layout file in addition to setting setOnItemLongClickListener()
to your ListView.
0 is, by definition, a magic number. EXIT_SUCCESS is almost universally equal to 0, happily enough. So why not just return/exit 0?
exit(EXIT_SUCCESS); is abundantly clear in meaning.
exit(0); on the other hand, is counterintuitive in some ways. Someone not familiar with shell behavior might assume that 0 == false == bad, just like every other usage of 0 in C. But no - in this one special case, 0 == success == good. For most experienced devs, not going to be a problem. But why trip up the new guy for absolutely no reason?
tl;dr - if there's a defined constant for your magic number, there's almost never a reason not to used the constant in the first place. It's more searchable, often clearer, etc. and it doesn't cost you anything.
This applies to Mac and Windows users (I use on Mac) . I've used several of the listed answers over the years and have found that FileZilla suits my needs well when editing files on a remote host that I have SSH access to. It's also quick to setup.
View/Edit
. This brings up my default editor (Sublime) but it will work with any editor you have installed.
Around 4gb/hr is quite common.
You can use a memory watchpoint in unmanaged code. Not sure if these are available in managed code though.
Don't over complicate the problem.
string osVer = System.Environment.OSVersion.Version.ToString();
if (osVer.StartsWith("5")) // windows 2000, xp win2k3
{
MessageBox.Show("xp!");
}
else // windows vista and windows 7 start with 6 in the version #
{
MessageBox.Show("Win7!");
}
Interface to be implemented by any object that wishes to be notified of the ApplicationContext that it runs in.
above is excerpted from the Spring doc website https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/ApplicationContextAware.html.
So, it seemed to be invoked when Spring container has started, if you want to do something at that time.
It just has one method to set the context, so you will get the context and do something to sth now already in context I think.
Laravel 5 uses .env
file to configure your app. .env
should not be committed on your repository, like github or bitbucket. On your local environment your .env
will look like the following:
# .env
APP_ENV=local
For your production server, you might have the following config:
# .env
APP_ENV=production
I like the dynamic query way of Dave Rincon as it does not use cursors and is small and easy. Thank you Dave for sharing.
But for my needs on Azure SQL and with a "distinct" in the query, i had to modify the code like this:
Declare @SQL nvarchar(max);
-- Set SQL Variable
-- Prepare exec command for each distinctive tenantid found in Machines
SELECT @SQL = (Select distinct 'exec dbo.sp_S2_Laser_to_cache ' +
convert(varchar(8),tenantid) + ';'
from Dim_Machine
where iscurrent = 1
FOR XML PATH(''))
--for debugging print the sql
print @SQL;
--execute the generated sql script
exec sp_executesql @SQL;
I hope this helps someone...
I have went through most of the answers and im pretty sure that it's unachievable. Whatever you try to divide two int into double or float is not gonna happen. But you have tons of methods to make the calculation happen, just cast them into float or double before the calculation will be fine.
first you have to assign blank value in first option. i.e. Select here.than only required will work.
One line that always goes in my .vimrc:
set tags=./tags;/
This will look in the current directory for "tags", and work up the tree towards root until one is found. IOW, you can be anywhere in your source tree instead of just the root of it.
DATE: It is used for values with a date part but no time part. MySQL retrieves and displays DATE values in YYYY-MM-DD format. The supported range is 1000-01-01
to 9999-12-31
.
DATETIME: It is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in YYYY-MM-DD HH:MM:SS format. The supported range is 1000-01-01 00:00:00
to 9999-12-31 23:59:59
.
TIMESTAMP: It is also used for values that contain both date and time parts, and includes the time zone. TIMESTAMP has a range of 1970-01-01 00:00:01
UTC to 2038-01-19 03:14:07
UTC.
TIME: Its values are in HH:MM:SS format (or HHH:MM:SS format for large hours values). TIME values may range from -838:59:59
to 838:59:59
. The hours part may be so large because the TIME type can be used not only to represent a time of day (which must be less than 24 hours), but also elapsed time or a time interval between two events (which may be much greater than 24 hours, or even negative).
I can think of 2 ways in which we can extract the keys from the dictionary.
Method 1: - To get the keys using .keys() method and then convert it to list.
some_dict = {1: 'one', 2: 'two', 3: 'three'}
list_of_keys = list(some_dict.keys())
print(list_of_keys)
-->[1,2,3]
Method 2: - To create an empty list and then append keys to the list via a loop. You can get the values with this loop as well (use .keys() for just keys and .items() for both keys and values extraction)
list_of_keys = []
list_of_values = []
for key,val in some_dict.items():
list_of_keys.append(key)
list_of_values.append(val)
print(list_of_keys)
-->[1,2,3]
print(list_of_values)
-->['one','two','three']
for (Bullet bullet : gunList.get(2).getBullet()) System.out.println(bullet);
If you add JDK_PATH in gradle.properties your build become dependent on on that particular path. Instead Run gradle task with following command line parametemer
gradle build -Dorg.gradle.java.home=/JDK_PATH
This way your build is not dependent on some concrete path.
It is almost fine. Just have:
Player[] thePlayers = new Player[playerCount + 1];
And let the loop be:
for(int i = 0; i < thePlayers.length; i++)
And note that java convention dictates that names of methods and variables should start with lower-case.
Update: put your method within the class body.
If you are using Google Cloud Messaging, then this issue will not be solved by simply changing your icon. For example, this will not work:
Notification notification = new Notification.Builder(this)
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(R.drawable.ic_notification)
.setContentIntent(pIntent)
.setDefaults(Notification.DEFAULT_SOUND|Notification.DEFAULT_LIGHTS|Notification.DEFAULT_VIBRATE)
.setAutoCancel(true)
.build();
Even if ic_notification is transparant and white. It must be also defined in the Manifest meta data, like so:
<meta-data android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/ic_notification" />
Meta-data goes under the application
tag, for reference.
Don't make your code so complicated. It can be done simply as below by using a foreach-like iterator:
$.each(buildings, function (index, value) {
$('#dropListBuilding').append($('<option/>', {
value: value,
text : value
}));
});
You have the join statement backwards try:
print ', '.join(set_3)
Logs are set in your settings.py
file. A new, default project, looks like this:
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
By default, these don't create log files. If you want those, you need to add a filename
parameter to your handlers
'applogfile': {
'level':'DEBUG',
'class':'logging.handlers.RotatingFileHandler',
'filename': os.path.join(DJANGO_ROOT, 'APPNAME.log'),
'maxBytes': 1024*1024*15, # 15MB
'backupCount': 10,
},
This will set up a rotating log that can get 15 MB in size and keep 10 historical versions.
In the loggers
section from above, you need to add applogfile
to the handlers
for your application
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
'APPNAME': {
'handlers': ['applogfile',],
'level': 'DEBUG',
},
}
This example will put your logs in your Django root in a file named APPNAME.log
The List
interface supports random access via the get
method - to get line 0, use list.get(0)
. You'll need to use array access on that, ie, lines.get(0)[0]
is the first element of the first line.
See the javadoc here.
public int getAge(Date birthDate) {
Calendar a = Calendar.getInstance(Locale.US);
a.setTime(date);
Calendar b = Calendar.getInstance(Locale.US);
int age = b.get(YEAR) - a.get(YEAR);
if (a.get(MONTH) > b.get(MONTH) || (a.get(MONTH) == b.get(MONTH) && a.get(DATE) > b.get(DATE))) {
age--;
}
return age;
}
Another solution, based on @Kitet's.
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
header("Status: 404 Not Found");
$_SERVER['REDIRECT_STATUS'] = 404;
//If you don't know which web page is in use, use any page that doesn't exists
$handle = curl_init('http://'. $_SERVER["HTTP_HOST"] .'/404missing.html');
curl_exec($handle);
If you are programming a website that hosted in a server you do not have control, you will not know which file is the "404missing.html". However you can still do this.
In this way, you provided exactly the same outcome of a normal 404 page on the same server. An observer will not be able to distinguish between an existing PHP page returns 404 and a non-existing page.
Before I get to my reiterated answer; I am confessing that the only answer I would accept here is this one by KM. above. I down voted the other answers because none of them actually answered the question asked or they were not adequate. PRINT output does indeed show up in the Message window, but that is not what was asked at all.
Why doesn't the PRINT statement output show during my Stored Procedure execution?
The short version of this answer is that you are sending your sproc's execution over to the SQL server and it isn't going to respond until it is finished with the whole transaction. Here is a better answer located at this external link.
Don't do these things
Alternative to PRINT inside of a Stored Procedure
Really this is kind of an icky work around in my opinion because the syntax is confusing in the context that it is being used in, but who knows maybe it will be updated in the future by Microsoft. I just don't like the idea of raising an error for the sole purpose of printing out debug info...
It seems like the only way around this issue is to use, as has been explained numerous times already RAISERROR WITH NOWAIT. I am providing an example and pointing out a small problem with this approach:
ALTER
--CREATE
PROCEDURE [dbo].[PrintVsRaiseErrorSprocExample]
AS
BEGIN
SET NOCOUNT ON;
-- This will print immediately
RAISERROR ('RE Start', 0, 1) WITH NOWAIT
SELECT 1;
-- Five second delay to simulate lengthy execution
WAITFOR DELAY '00:00:05'
-- This will print after the five second delay
RAISERROR ('RE End', 0, 1) WITH NOWAIT
SELECT 2;
END
GO
EXEC [dbo].[PrintVsRaiseErrorSprocExample]
Both SELECT statement results will only show after the execution is finished and the print statements will show in the order shown above.
Potential problem with this approach
Let's say you have both your PRINT statement and RAISERROR statement one after the other, then they both print. I'm sure this has something to do with buffering, but just be aware that this can happen.
ALTER
--CREATE
PROCEDURE [dbo].[PrintVsRaiseErrorSprocExample2]
AS
BEGIN
SET NOCOUNT ON;
-- Both the PRINT and RAISERROR statements will show
PRINT 'P Start';
RAISERROR ('RE Start', 0, 1) WITH NOWAIT
SELECT 1;
WAITFOR DELAY '00:00:05'
-- Both the PRINT and RAISERROR statements will show
PRINT 'P End'
RAISERROR ('RE End', 0, 1) WITH NOWAIT
SELECT 2;
END
GO
EXEC [dbo].[PrintVsRaiseErrorSprocExample2]
Therefore the work around here is, don't use both PRINT and RAISERROR, just choose one over the other. If you want your output to show during the execution of a sproc then use RAISERROR WITH NOWAIT.
If you (unlike the OP) need a specific number of records (which makes the CHECKSUM approach difficult) and desire a more random sample than TABLESAMPLE provides by itself, and also want better speed than CHECKSUM, you may make do with a merger of the TABLESAMPLE and NEWID() methods, like this:
DECLARE @sampleCount int = 50
SET STATISTICS TIME ON
SELECT TOP (@sampleCount) *
FROM [yourtable] TABLESAMPLE(10 PERCENT)
ORDER BY NEWID()
SET STATISTICS TIME OFF
In my case this is the most straightforward compromise between randomness (it's not really, I know) and speed. Vary the TABLESAMPLE percentage (or rows) as appropriate - the higher the percentage, the more random the sample, but expect a linear drop off in speed. (Note that TABLESAMPLE will not accept a variable)
You could do it like this:
<a class="btn btn-primary announce" data-toggle="modal" data-id="107" >Announce</a>
Then use jQuery to bind the click and send the Announce data-id as the value in the modals #cafeId:
$(document).ready(function(){
$(".announce").click(function(){ // Click to only happen on announce links
$("#cafeId").val($(this).data('id'));
$('#createFormId').modal('show');
});
});
I face Similar problem now I understand we have some more option : varStatus="loop", Here will be loop will variable which will hold the index of lop.
It can use for use to read for Zeor base index or 1 one base index.
${loop.count}` it will give 1 starting base index.
${loop.index} it will give 0 base index as normal Index of array
start from 0.
For Example :
<c:forEach var="currentImage" items="${cityBannerImages}" varStatus="loop">
<picture>
<source srcset="${currentImage}" media="(min-width: 1000px)"></source>
<source srcset="${cityMobileImages[loop.count]}" media="(min-width:600px)"></source>
<img srcset="${cityMobileImages[loop.count]}" alt=""></img>
</picture>
</c:forEach>
For more Info please refer this link
Shift
+ Alt
+ F
indents the whole file.
If you're modifying your class to accept a Stream instead of a filename, don't bother converting to a MemoryStream. Let the underlying Stream handle the operations:
public class MyClass
{
Stream _s;
public MyClass(Stream s) { _s = s; }
}
But if you really need a MemoryStream for internal operations, you'll have to copy the data out of the source Stream into the MemoryStream:
public MyClass(Stream stream)
{
_ms = new MemoryStream();
CopyStream(stream, _ms);
}
// Merged From linked CopyStream below and Jon Skeet's ReadFully example
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[16*1024];
int read;
while((read = input.Read (buffer, 0, buffer.Length)) > 0)
{
output.Write (buffer, 0, read);
}
}
I believe the example you've posted is using HTML5, which allows you to jump to any DOM element with the matching ID
attribute. To support older browsers, you'll need to change:
<div id="timeline" name="timeline" ...>
To the old format:
<a name="timeline" />
You'll then be able to navigate to /academics/page.html#timeline
and jump right to that section.
Also, check out this similar question.
Static Array :
Dynamic Array :
In modern browsers you can use the Map
data structure instead of a object.
A Map object can iterate its elements in insertion order...
LocalDate.parse( "2011-01-01" )
.format( DateTimeFormatter.ofPattern( "MM-dd-uuuu" ) )
The other Answers are now outdated. The troublesome old date-time classes such as java.util.Date
, java.util.Calendar
, and java.text.SimpleDateFormat
are now legacy, supplanted by the java.time classes.
The input string 2011-01-01
happens to comply with the ISO 8601 standard formats for date-time text. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.
LocalDate
The LocalDate
class represents a date-only value without time-of-day and without time zone.
LocalDate ld = LocalDate.parse( "2011-01-01" ) ;
Generate a String in the same format by calling toString
.
String output = ld.toString() ;
2011-01-01
DateTimeFormatter
To parse/generate other formats, use a DateTimeFormatter
.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu" ) ;
String output = ld.format( f ) ;
01-01-2011
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Another way around this would be to insert a DEFAULT element in the other table. For example, any reference to uuid=00000000-0000-0000-0000-000000000000 on the other table would indicate no action. You also need to set all the values for that id to be "neutral", e.g. 0, empty string, null in order to not affect your code logic.
Just to be complete, C++
#include <iostream>
#include <algorithm>
#include <string>
std::string theSeq = "abc";
do
{
std::cout << theSeq << endl;
}
while (std::next_permutation(theSeq.begin(), theSeq.end()));
...
abc
acb
bac
bca
cab
cba
Here you get all available services and their status in your local machine.
ServiceController[] services = ServiceController.GetServices();
foreach(ServiceController service in services)
{
Console.WriteLine(service.ServiceName+"=="+ service.Status);
}
You can Compare your service with service.name property inside loop and you get status of your service. For details go with the http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.aspx also http://msdn.microsoft.com/en-us/library/microsoft.windows.design.servicemanager(v=vs.90).aspx
If you have SELINUX enabled, it will prevent this file being created. You need to turn it off.
vi /etc/selinux/config
set SELINUX=disabled
This method works for me well and I think the simplest way to do this is to use this javascript code inside the reloaded page's HTML.
if ( window.history.replaceState ) {_x000D_
window.history.replaceState( null, null, window.location.href );_x000D_
}
_x000D_
You can directly define a char type vector as below.
vector<char> c = {'a', 'b', 'c'};
vector < vector<char> > t = {{'a','a'}, 'b','b'};
Just install the updated versions of all of them.
apt-get install -y gnupg2 gnupg gnupg1
The universal solution is using the HTML tag <sup>
, as suggested in the main answer.
However, the idea behind Markdown is precisely to avoid the use of such tags:
The document should look nice as plain text, not only when rendered.
Another answer proposes using Unicode characters, which makes the document look nice as a plain text document but could reduce compatibility.
Finally, I would like to remember the simplest solution for some documents: the character ^
.
Some Markdown implementation (e.g. MacDown in macOS) interprets the caret as an instruction for superscript.
Ex.
Sin^2 + Cos^2 = 1
Clearly, Stack Overflow does not interpret the caret as a superscript instruction. However, the text is comprehensible, and this is what really matters when using Markdown.
This solution works fine for all major browsers, except IE. So keep that in mind.
In this example, basicaly I use positioning, horizontal and vertical transform for the UI element to center it.
.container {_x000D_
/* set the the position to relative */_x000D_
position: relative;_x000D_
width: 30rem;_x000D_
height: 20rem;_x000D_
background-color: #2196F3;_x000D_
}_x000D_
_x000D_
_x000D_
.paragh {_x000D_
/* set the the position to absolute */_x000D_
position: absolute;_x000D_
/* set the the position of the helper container into the middle of its space */_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
font-size: 30px;_x000D_
/* make sure padding and margin do not disturb the calculation of the center point */_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
/* using centers for the transform */_x000D_
transform-origin: center center;_x000D_
/* calling calc() function for the calculation to move left and up the element from the center point */_x000D_
transform: translateX(calc((100% / 2) * (-1))) translateY(calc((100% / 2) * (-1)));_x000D_
}
_x000D_
<div class="container">_x000D_
<p class="paragh">Text</p>_x000D_
</div>
_x000D_
I hope this help.
Another way is to use only a '-' in the argument for argsort as in : "df[np.argsort(-df[:, 0])]", provided df is the dataframe and you want to sort it by the first column (represented by the column number '0'). Change the column-name as appropriate. Of course, the column has to be a numeric one.
The difference between .dylib and .so on mac os x is how they are compiled. For .so files you use -shared and for .dylib you use -dynamiclib. Both .so and .dylib are interchangeable as dynamic library files and either have a type as DYLIB or BUNDLE. Heres the readout for different files showing this.
libtriangle.dylib:
Mach header
magic cputype cpusubtype caps filetype ncmds sizeofcmds flags
MH_MAGIC_64 X86_64 ALL 0x00 DYLIB 17 1368 NOUNDEFS DYLDLINK TWOLEVEL NO_REEXPORTED_DYLIBS
libtriangle.so:
Mach header
magic cputype cpusubtype caps filetype ncmds sizeofcmds flags
MH_MAGIC_64 X86_64 ALL 0x00 DYLIB 17 1256 NOUNDEFS DYLDLINK TWOLEVEL NO_REEXPORTED_DYLIBS
triangle.so:
Mach header
magic cputype cpusubtype caps filetype ncmds sizeofcmds flags
MH_MAGIC_64 X86_64 ALL 0x00 BUNDLE 16 1696 NOUNDEFS DYLDLINK TWOLEVEL
The reason the two are equivalent on Mac OS X is for backwards compatibility with other UNIX OS programs that compile to the .so file type.
Compilation notes: whether you compile a .so file or a .dylib file you need to insert the correct path into the dynamic library during the linking step. You do this by adding -install_name and the file path to the linking command. If you dont do this you will run into the problem seen in this post: Mac Dynamic Library Craziness (May be Fortran Only).
As others have pointed out, ideally, the foreign key would be created as a reference to a primary key (usually an IDENTITY column). However, we don't live in an ideal world, and sometimes even a "small" change to a schema can have significant ripple effects to the application logic.
Consider the case of a Customer table with a SSN column (and a dumb primary key), and a Claim table that also contains a SSN column (populated by business logic from the Customer data, but no FK exists). The design is flawed, but has been in use for several years, and three different applications have been built on the schema. It should be obvious that ripping out Claim.SSN and putting in a real PK-FK relationship would be ideal, but would also be a significant overhaul. On the other hand, putting a UNIQUE constraint on Customer.SSN, and adding a FK on Claim.SSN, could provide referential integrity, with little or no impact on the applications.
Don't get me wrong, I'm all for normalization, but sometimes pragmatism wins over idealism. If a mediocre design can be helped with a band-aid, surgery might be avoided.
If you prefer named parameters, it's possible (with a few tricks) to actually pass named parameters to functions (also makes it possible to pass arrays and references).
The method I developed allows you to define named parameters passed to a function like this:
function example { args : string firstName , string lastName , integer age } {
echo "My name is ${firstName} ${lastName} and I am ${age} years old."
}
You can also annotate arguments as @required or @readonly, create ...rest arguments, create arrays from sequential arguments (using e.g. string[4]
) and optionally list the arguments in multiple lines:
function example {
args
: @required string firstName
: string lastName
: integer age
: string[] ...favoriteHobbies
echo "My name is ${firstName} ${lastName} and I am ${age} years old."
echo "My favorite hobbies include: ${favoriteHobbies[*]}"
}
In other words, not only you can call your parameters by their names (which makes up for a more readable core), you can actually pass arrays (and references to variables - this feature works only in Bash 4.3 though)! Plus, the mapped variables are all in the local scope, just as $1
(and others).
The code that makes this work is pretty light and works both in Bash 3 and Bash 4 (these are the only versions I've tested it with). If you're interested in more tricks like this that make developing with bash much nicer and easier, you can take a look at my Bash Infinity Framework, the code below is available as one of its functionalities.
shopt -s expand_aliases
function assignTrap {
local evalString
local -i paramIndex=${__paramIndex-0}
local initialCommand="${1-}"
if [[ "$initialCommand" != ":" ]]
then
echo "trap - DEBUG; eval \"${__previousTrap}\"; unset __previousTrap; unset __paramIndex;"
return
fi
while [[ "${1-}" == "," || "${1-}" == "${initialCommand}" ]] || [[ "${#@}" -gt 0 && "$paramIndex" -eq 0 ]]
do
shift # First colon ":" or next parameter's comma ","
paramIndex+=1
local -a decorators=()
while [[ "${1-}" == "@"* ]]
do
decorators+=( "$1" )
shift
done
local declaration=
local wrapLeft='"'
local wrapRight='"'
local nextType="$1"
local length=1
case ${nextType} in
string | boolean) declaration="local " ;;
integer) declaration="local -i" ;;
reference) declaration="local -n" ;;
arrayDeclaration) declaration="local -a"; wrapLeft= ; wrapRight= ;;
assocDeclaration) declaration="local -A"; wrapLeft= ; wrapRight= ;;
"string["*"]") declaration="local -a"; length="${nextType//[a-z\[\]]}" ;;
"integer["*"]") declaration="local -ai"; length="${nextType//[a-z\[\]]}" ;;
esac
if [[ "${declaration}" != "" ]]
then
shift
local nextName="$1"
for decorator in "${decorators[@]}"
do
case ${decorator} in
@readonly) declaration+="r" ;;
@required) evalString+="[[ ! -z \$${paramIndex} ]] || echo \"Parameter '$nextName' ($nextType) is marked as required by '${FUNCNAME[1]}' function.\"; " >&2 ;;
@global) declaration+="g" ;;
esac
done
local paramRange="$paramIndex"
if [[ -z "$length" ]]
then
# ...rest
paramRange="{@:$paramIndex}"
# trim leading ...
nextName="${nextName//\./}"
if [[ "${#@}" -gt 1 ]]
then
echo "Unexpected arguments after a rest array ($nextName) in '${FUNCNAME[1]}' function." >&2
fi
elif [[ "$length" -gt 1 ]]
then
paramRange="{@:$paramIndex:$length}"
paramIndex+=$((length - 1))
fi
evalString+="${declaration} ${nextName}=${wrapLeft}\$${paramRange}${wrapRight}; "
# Continue to the next parameter:
shift
fi
done
echo "${evalString} local -i __paramIndex=${paramIndex};"
}
alias args='local __previousTrap=$(trap -p DEBUG); trap "eval \"\$(assignTrap \$BASH_COMMAND)\";" DEBUG;'
You can go with POSTMAN, an application who makes APIs easy. Fill request fields and then it will generate code for you in different languages. Just click code on the right side and select your prefered language.