Note: As of 17.0 from_csv
is discouraged: use pd.read_csv
instead
The documentation lists a .from_csv function that appears to do what you want:
DataFrame.from_csv('c:/~/trainSetRel3.txt', sep='\t')
If you have a header, you can pass header=0
.
DataFrame.from_csv('c:/~/trainSetRel3.txt', sep='\t', header=0)
I know this is quite old, but I recently had to do something similar... After seeing how difficult this is, I came up with a much simpler solution:
In my case, I needed an EditText that had the ability to clear the text with a button. I wanted it to look like SearchView, but for a number of reasons I didn't want to use that class. The example below shows how I accomplished this. Even though it doesn't have to do with focus change, the principles are the same and I figured it would be more beneficial to post actual working code than to put together an example that may not work exactly as I intended:
Here is my layout: clearable_edit_text.xml
<merge
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/edit_text_field"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<!-- NOTE: Visibility cannot be set to "gone" or the padding won't get set properly in code -->
<ImageButton
android:id="@+id/edit_text_clear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|center_vertical"
android:background="@drawable/ic_cancel_x"
android:visibility="invisible"/>
</merge>
And here is the Class that inflates that layout: ClearableEditText.java
public class ClearableEditText extends FrameLayout {
private boolean mPaddingSet = false;
/**
* Creates a new instance of this class.
* @param context The context used to create the instance
*/
public ClearableEditText (final Context context) {
this(context, null, 0);
}
/**
* Creates a new instance of this class.
* @param context The context used to create the instance
* @param attrs The attribute set used to customize this instance
*/
public ClearableEditText (final Context context, final AttributeSet attrs) {
this(context, attrs, 0);
}
/**
* Creates a new instance of this class.
* @param context The context used to create the instance
* @param attrs The attribute set used to customize this instance
* @param defStyle The default style to be applied to this instance
*/
public ClearableEditText (final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
final LayoutInflater inflater = LayoutInflater.from(context);
inflater.inflate(R.layout.clearable_edit_text, this, true);
}
@Override
protected void onFinishInflate () {
super.onFinishInflate();
final EditText editField = (EditText) findViewById(R.id.edit_text_field);
final ImageButton clearButton = (ImageButton) findViewById(R.id.edit_text_clear);
//Set text listener so we can show/hide the close button based on whether or not it has text
editField.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged (final CharSequence charSequence, final int i, final int i2, final int i3) {
//Do nothing here
}
@Override
public void onTextChanged (final CharSequence charSequence, final int i, final int i2, final int i3) {
//Do nothing here
}
@Override
public void afterTextChanged (final Editable editable) {
clearButton.setVisibility(editable.length() > 0 ? View.VISIBLE : View.INVISIBLE);
}
});
//Set the click listener for the button to clear the text. The act of clearing the text will hide this button because of the
//text listener
clearButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick (final View view) {
editField.setText("");
}
});
}
@Override
protected void onLayout (final boolean changed, final int left, final int top, final int right, final int bottom) {
super.onLayout(changed, left, top, right, bottom);
//Set padding here in the code so the text doesn't run into the close button. This could be done in the XML layout, but then if
//the size of the image changes then we constantly need to tweak the padding when the image changes. This way it happens automatically
if (!mPaddingSet) {
final EditText editField = (EditText) findViewById(R.id.edit_text_field);
final ImageButton clearButton = (ImageButton) findViewById(R.id.edit_text_clear);
editField.setPadding(editField.getPaddingLeft(), editField.getPaddingTop(), clearButton.getWidth(), editField.getPaddingBottom());
mPaddingSet = true;
}
}
}
To make this answer more in line with the question the following steps should be taken:
If you use Material Components:
CustomDialog.kt
class CustomDialog: DialogFragment() {
override fun getTheme() = R.style.RoundedCornersDialog
}
styles.xml
<style name="RoundedCornersDialog" parent="Theme.MaterialComponents.Dialog">
<item name="dialogCornerRadius">dimen</item>
</style>
I know the question asks for a javascript way of simulating a keypress. But for those who are looking for a jQuery way of doing things:
var e = jQuery.Event("keypress");
e.which = 13 //or e.keyCode = 13 that simulates an <ENTER>
$("#element_id").trigger(e);
There might be another solution to this:
Your code was:
geom_point(aes(..., show.legend = FALSE))
You can specify the show.legend
parameter after the aes
call:
geom_point(aes(...), show.legend = FALSE)
then the corresponding legend should disappear
You can also install simplejson.
If you have pip (see https://pypi.python.org/pypi/pip) as your Python package manager you can install simplejson with:
pip install simplejson
This is similar to the comment of installing with easy_install, but I prefer pip to easy_install as you can easily uninstall in pip with "pip uninstall package".
A constructor should no have a return type . remove void before each constructor .
Some very basic characteristic of a constructor :
a. Same name as class b. no return type. c. will be called every time an object is made with the class. for eg- in your program if u made two objects of Flow, Flow flow1=new Flow(); Flow flow2=new Flow(); then Flow constructor will be called for 2 times.
d. If you want to call the constructor just for once then declare that as static (static constructor) and dont forget to remove any access modifier from static constructor ..
You should be able to use filter: orderBy
orderBy
can accept a third option for the reverse
flag.
<select ng-option="item.name for item in items | orderBy:'name':true"></select>
Here item is sorted by 'name' property in a reversed order. The 2nd argument can be any order function, so you can sort in any rule.
Use seaborn instead i am using distplot of seaborn with mean=5 std=3 of 1000 values
value = np.random.normal(loc=5,scale=3,size=1000)
sns.distplot(value)
You will get a normal distribution curve
i think you try to align the content to the right within the div, the div with offset already push itself to the right, here some code and LIVE sample:
FYI: .pull-right
only push the div to the right, but not the content inside the div.
HTML:
<div class="row">
<div class="container">
<div class="col-md-4 someclass">
left content
</div>
<div class="col-md-4 col-md-offset-4 someclass">
<div class="yellow_background totheright">right content</div>
</div>
</div>
</div>
CSS:
.someclass{ /*this class for testing purpose only*/
border:1px solid blue;
line-height:2em;
}
.totheright{ /*this will align the text to the right*/
text-align:right;
}
.yellow_background{
background-color:yellow;
}
Another modification:
...
<div class="yellow_background totheright">
<span>right content</span>
<br/>image also align-right<br/>
<img width="15%" src="https://www.google.com/images/srpr/logo11w.png"/>
</div>
...
hope it will clear your problem
To print all lines in text file from command line (with delayedExpansion):
set input="path/to/file.txt"
for /f "tokens=* delims=[" %i in ('type "%input%" ^| find /v /n ""') do (
set a=%i
set a=!a:*]=]!
echo:!a:~1!)
Works with leading whitespace, blank lines, whitespace lines.
Tested on Win 10 CMD
I just want to add that orderby is way more useful.
Why? Because I can do this:
Dim thisAccountBalances = account.DictOfBalances.Values.ToList
thisAccountBalances.ForEach(Sub(x) x.computeBalanceOtherFactors())
thisAccountBalances=thisAccountBalances.OrderBy(Function(x) x.TotalBalance).tolist
listOfBalances.AddRange(thisAccountBalances)
Why complicated comparer? Just sort based on a field. Here I am sorting based on TotalBalance.
Very easy.
I can't do that with sort. I wonder why. Do fine with orderBy.
As for speed it's always O(n).
Use ISNULL(field, 0)
It can also be used with aggregates:
ISNULL(count(field), 0)
However, you might consider changing count(field) to count(*)
Edit:
try:
closedcases = ISNULL(
(select count(closed) from ticket
where assigned_to = c.user_id and closed is not null
group by assigned_to), 0),
opencases = ISNULL(
(select count(closed) from ticket
where assigned_to = c.user_id and closed is null
group by assigned_to), 0),
$mysearch="Your Search Name";
$query = mysql_query("SELECT * FROM table");
$c=0;
// set array
$array = array();
// look through query
while($row = mysql_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row;
$c++;
}
for($i=0;$i=$c;$i++)
{
if($array[i]['username']==$mysearch)
{
// name found
}
}
1.Create new folder in d drive D:/data/db
2.Open terminal on D:/data/db
3.Type mongod and enter.
4.Type mongo and enter.
and your mongodb has strated............
If still not working you can call garbage collector to close the file and free up memory
System.gc();
if(new File("./__tmp.txt").delete()){
System.out.println("OK");
}
Don't forget to close that file, if any previous opening using code snippet fio.close()
I tested in Java 1.8, works well.
For SSMS 18, I found the files at:
C:\Users\YourUserName\Documents\Visual Studio 2017\Backup Files\Solution1
For SSMS 17, It was used to be at:
C:\Users\YourUserName\Documents\Visual Studio 2015\Backup Files\Solution1
So you're trying to get the search term and category into the URL?
I would advise against this as you'll have to deal with multi-word search terms etc, and could end up with all manner of unpleasantness with disallowed characters.
I would suggest POSTing the data, sanitising it and then returning a results page.
Laravel routing is not designed to accept GET requests from forms, it is designed to use URL segments as get parameters, and built around that idea.
Another info: If you want use a Route Constraint, imagine that you want force that parameter has int datatype, then you need use this syntax:
[Route("v1/location/**{deviceOrAppid:int?}**", Name = "AddNewLocation")]
The ? character is put always before the last } character
For more information see: Optional URI Parameters and Default Values
I wrote a script and created a git repository, which solves this issue here: https://github.com/Cazaimi/boot-github-shell-win .
The readme contains instructions on how to set the script up, so that each time you open a new window/tab the private key is added to ssh-agent
automatically, and you don't have to worry about this, if you're working with remote git repositories.
You need to use multiple rules to implement OR-like semantics, since matches are always AND-ed together within a rule. Alternatively, you can do matching against port-indexing ipsets (ipset create blah bitmap:port
).
Use ifelse
:
frame$twohouses <- ifelse(frame$data>=2, 2, 1)
frame
data twohouses
1 0 1
2 1 1
3 2 2
4 3 2
5 4 2
...
16 0 1
17 2 2
18 1 1
19 2 2
20 0 1
21 4 2
The difference between if
and ifelse
:
if
is a control flow statement, taking a single logical value as an argumentifelse
is a vectorised function, taking vectors as all its arguments.The help page for if
, accessible via ?"if"
will also point you to ?ifelse
You could try:
tr:hover {
background-color: #000;
}
tr:hover td {
background-color: transparent; /* or #000 */
}
One can directly store the returned output of a function in a file.
print(output statement, file=open("filename", "a"))
RFC 2616 (Hypertext Transfer Protocol — HTTP/1.1) states there is no limit to the length of a query string (section 3.2.1). RFC 3986 (Uniform Resource Identifier — URI) also states there is no limit, but indicates the hostname is limited to 255 characters because of DNS limitations (section 2.3.3).
While the specifications do not specify any maximum length, practical limits are imposed by web browser and server software. Based on research which is unfortunately no longer available on its original site (it leads to a shady seeming loan site) but which can still be found at Internet Archive Of Boutell.com:
Microsoft Internet Explorer (Browser)
Microsoft states that the maximum length of a URL in Internet Explorer is 2,083 characters, with no more than 2,048 characters in the path portion of the URL. Attempts to use URLs longer than this produced a clear error message in Internet Explorer.
Microsoft Edge (Browser)
The limit appears to be around 81578 characters. See URL Length limitation of Microsoft Edge
Chrome
It stops displaying the URL after 64k characters, but can serve more than 100k characters. No further testing was done beyond that.
Firefox (Browser)
After 65,536 characters, the location bar no longer displays the URL in Windows Firefox 1.5.x. However, longer URLs will work. No further testing was done after 100,000 characters.
Safari (Browser)
At least 80,000 characters will work. Testing was not tried beyond that.
Opera (Browser)
At least 190,000 characters will work. Stopped testing after 190,000 characters. Opera 9 for Windows continued to display a fully editable,
copyable and pasteable URL in the location bar even at 190,000 characters.
Apache (Server)
Early attempts to measure the maximum URL length in web browsers bumped into a server URL length limit of approximately 4,000 characters, after which Apache produces a "413 Entity Too Large" error. The current up to date Apache build found in Red Hat Enterprise Linux 4 was used. The official Apache documentation only mentions an 8,192-byte limit on an individual field in a request.
Microsoft Internet Information Server (Server)
The default limit is 16,384 characters (yes, Microsoft's web server accepts longer URLs than Microsoft's web browser). This is configurable.
Perl HTTP::Daemon (Server)
Up to 8,000 bytes will work. Those constructing web application servers with Perl's HTTP::Daemon module will encounter a 16,384 byte limit on the combined size of all HTTP request headers. This does not include POST-method form data, file uploads, etc., but it does include the URL. In practice this resulted in a 413 error when a URL was significantly longer than 8,000 characters. This limitation can be easily removed. Look for all occurrences of 16x1024 in Daemon.pm and replace them with a larger value. Of course, this does increase your exposure to denial of service attacks.
There is now a HDF5 based clone of pickle
called hickle
!
https://github.com/telegraphic/hickle
import hickle as hkl
data = { 'name' : 'test', 'data_arr' : [1, 2, 3, 4] }
# Dump data to file
hkl.dump( data, 'new_data_file.hkl' )
# Load data from file
data2 = hkl.load( 'new_data_file.hkl' )
print( data == data2 )
EDIT:
There also is the possibility to "pickle" directly into a compressed archive by doing:
import pickle, gzip, lzma, bz2
pickle.dump( data, gzip.open( 'data.pkl.gz', 'wb' ) )
pickle.dump( data, lzma.open( 'data.pkl.lzma', 'wb' ) )
pickle.dump( data, bz2.open( 'data.pkl.bz2', 'wb' ) )
Appendix
import numpy as np
import matplotlib.pyplot as plt
import pickle, os, time
import gzip, lzma, bz2, h5py
compressions = [ 'pickle', 'h5py', 'gzip', 'lzma', 'bz2' ]
labels = [ 'pickle', 'h5py', 'pickle+gzip', 'pickle+lzma', 'pickle+bz2' ]
size = 1000
data = {}
# Random data
data['random'] = np.random.random((size, size))
# Not that random data
data['semi-random'] = np.zeros((size, size))
for i in range(size):
for j in range(size):
data['semi-random'][i,j] = np.sum(data['random'][i,:]) + np.sum(data['random'][:,j])
# Not random data
data['not-random'] = np.arange( size*size, dtype=np.float64 ).reshape( (size, size) )
sizes = {}
for key in data:
sizes[key] = {}
for compression in compressions:
if compression == 'pickle':
time_start = time.time()
pickle.dump( data[key], open( 'data.pkl', 'wb' ) )
time_tot = time.time() - time_start
sizes[key]['pickle'] = ( os.path.getsize( 'data.pkl' ) * 10**(-6), time_tot )
os.remove( 'data.pkl' )
elif compression == 'h5py':
time_start = time.time()
with h5py.File( 'data.pkl.{}'.format(compression), 'w' ) as h5f:
h5f.create_dataset('data', data=data[key])
time_tot = time.time() - time_start
sizes[key][compression] = ( os.path.getsize( 'data.pkl.{}'.format(compression) ) * 10**(-6), time_tot)
os.remove( 'data.pkl.{}'.format(compression) )
else:
time_start = time.time()
pickle.dump( data[key], eval(compression).open( 'data.pkl.{}'.format(compression), 'wb' ) )
time_tot = time.time() - time_start
sizes[key][ labels[ compressions.index(compression) ] ] = ( os.path.getsize( 'data.pkl.{}'.format(compression) ) * 10**(-6), time_tot )
os.remove( 'data.pkl.{}'.format(compression) )
f, ax_size = plt.subplots()
ax_time = ax_size.twinx()
x_ticks = labels
x = np.arange( len(x_ticks) )
y_size = {}
y_time = {}
for key in data:
y_size[key] = [ sizes[key][ x_ticks[i] ][0] for i in x ]
y_time[key] = [ sizes[key][ x_ticks[i] ][1] for i in x ]
width = .2
viridis = plt.cm.viridis
p1 = ax_size.bar( x-width, y_size['random'] , width, color = viridis(0) )
p2 = ax_size.bar( x , y_size['semi-random'] , width, color = viridis(.45))
p3 = ax_size.bar( x+width, y_size['not-random'] , width, color = viridis(.9) )
p4 = ax_time.bar( x-width, y_time['random'] , .02, color = 'red')
ax_time.bar( x , y_time['semi-random'] , .02, color = 'red')
ax_time.bar( x+width, y_time['not-random'] , .02, color = 'red')
ax_size.legend( (p1, p2, p3, p4), ('random', 'semi-random', 'not-random', 'saving time'), loc='upper center',bbox_to_anchor=(.5, -.1), ncol=4 )
ax_size.set_xticks( x )
ax_size.set_xticklabels( x_ticks )
f.suptitle( 'Pickle Compression Comparison' )
ax_size.set_ylabel( 'Size [MB]' )
ax_time.set_ylabel( 'Time [s]' )
f.savefig( 'sizes.pdf', bbox_inches='tight' )
What is the difference between Git and GitHub?
Linus Torvalds would kill you for this. Git is the name of the version manager program he wrote. GitHub is a website on which there are source code repositories manageable by Git. Thus, GitHub is completely unrelated to the original Git tool.
Is git saving every repository locally (in the user's machine) and in GitHub?
If you commit changes, it stores locally. Then, if you push the commits, it also sotres them remotely.
Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?
You can, but I'm sure you don't want to manually set up a git server for yourself. Benefits of GitHub? Well, easy to use, lot of people know it so others may find your code and follow/fork it to make improvements as well.
How does Git compare to a backup system such as Time Machine?
Git is specifically designed and optimized for source code.
Is this a manual process, in other words if you don't commit you wont have a new version of the changes made?
Exactly.
If are not collaborating and you are already using a backup system why would you use Git?
See #4.
I understand you asked about converting images to a gif; however, if the original format is MP4, you could use FFmpeg:
ffmpeg -i input.mp4 output.gif
The main point of the differences as pointed out @BizApps is that Load event happens right after the ViewState is populated while PreRender event happens later, right before Rendering phase, and after all individual children controls' action event handlers are already executing. Therefore, any modifications done by the controls' actions event handler should be updated in the control hierarchy during PreRender as it happens after.
var $iframe = document.getElementByID('myIfreme');
var childDocument = iframe.contentDocument ? iframe.contentDocument : iframe.contentWindow.document;
childDocument.documentElement.scrollTop = 0;
implementation androidx.recyclerview:recyclerview:.... It is advised to update to the androidx libraries which are here:
https://developer.android.com/jetpack/androidx/releases/recyclerview
The layout file Widget XML tag then must be updated to: androidx.recyclerview.widget.RecyclerView
The inner join will give the result of matched records between two tables where as the cross join gives you the possible combinations between two tables.
Using raw javascript, suppose you have:
var j = {0: "1", 1: "2", 2: "3", 3: "4"};
You could get the values with:
Object.keys(j).map(function(_) { return j[_]; })
Output:
["1", "2", "3", "4"]
Set the html and body tags height
to 100%
and remove the margin around the body:
html, body {
height: 100%;
margin: 0px; /* Remove the margin around the body */
}
Now set the position
of your div to fixed
:
#dimScreen
{
width: 100%;
height: 100%;
background:rgba(255,255,255,0.5);
position: fixed;
top: 0px;
left: 0px;
z-index: 1000; /* Now the div will be on top */
}
Sorry not sure what was going on this worked in the end:
<VirtualHost *>
ServerName example.com
DocumentRoot /var/www/html/mjp
Alias /ncn "/var/www/html/ncn"
<Directory "/var/www/html/ncn">
Options None
AllowOverride None
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
queryString = "SELECT name FROM user WHERE id=" & Worksheets("Sheet1").Range("D4").Value
Annotate your method in controller with @ResponseBody
:
@RequestMapping(value="/controller", method=GET)
@ResponseBody
public String foo() {
return "Response!";
}
From: 15.3.2.6 Mapping the response body with the @ResponseBody
annotation:
The
@ResponseBody
annotation [...] can be put on a method and indicates that the return type should be written straight to the HTTP response body (and not placed in a Model, or interpreted as a view name).
if you just need a timestamp in unix /epoch time, this one line works:
created_timestamp = int((datetime.datetime.now() - datetime.datetime(1970,1,1)).total_seconds())
>>> created_timestamp
1522942073L
and depends only on datetime
works in python2 and python3
If you wish to keep the carriage return characters from the string into a file here is an code example:
jLabel1 = new JLabel("Enter SQL Statements or SQL Commands:");
orderButton = new JButton("Execute");
textArea = new JTextArea();
...
// String captured from JTextArea()
orderButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// When Execute button is pressed
String tempQuery = textArea.getText();
tempQuery = tempQuery.replaceAll("\n", "\r\n");
try (PrintStream out = new PrintStream(new FileOutputStream("C:/Temp/tempQuery.sql"))) {
out.print(tempQuery);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(tempQuery);
}
});
Use prop() instead of attr() to set the value of checked
. Also use :checkbox
in find method instead of input
and be specific.
$("#news_list tr").click(function() {
var ele = $(this).find('input');
if(ele.is(':checked')){
ele.prop('checked', false);
$(this).removeClass('admin_checked');
}else{
ele.prop('checked', true);
$(this).addClass('admin_checked');
}
});
Use prop instead of attr for properties like checked
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method
I would use a generic iterator of property/value over the array. No jQuery required.
arr = [{prop1: 'val1', prop2: 'val2'}, {prop1: 'val3', prop2: 'val4'}];
objectPropInArray(arr, 'prop1', 'val3'); // <-- returns true
function objectPropInArray(list, prop, val) {
if (list.length > 0 ) {
for (i in list) {
if (list[i][prop] === val) {
return true;
}
}
}
return false;
}
I'm on Ubuntu 20.04 and I kept getting the message that soon I wouldn't be able to login from console. I was terribly confused. Finally, I got to the URL below which will work. But you need to know how to create a PAT (Personal Access Token) which you are going to have to keep in a file on your computer.
Here's what the final URL will look like:
git push https://[email protected]/user-name/repo.git
long PAT (Personal Access Token) value -- The entire long value between the // and the @ sign in the url is your PAT.
user-name will be your exact username
repo.git will be your exact repo name
You need to generate a PAT following the steps at: https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token
That will give you the PAT value that you will place in your URL.
When you create the PAT make sure you choose the following options so it has the ability to allow you to manage your REPOs.
Save Your PAT Or Lose It
Once you have your PAT. You're going to need to save it in a file locally so you can use it again. If you don't save it somewhere there is no way to ever see it again and you'll be forced to create a new PAT
Now you're going to need at the very least :
For 1, just use :
$ cat ~/files/myPatFile.txt
Where the path is a real path to the location and file where you stored your PAT value.
For 2
$ xclip -selection clipboard < ~/files/myPatFile.txt
That'll copy the contents of the file to the clipboard so you can use your PAT more easily.
FYI - if you don't have xclip do the following:
$ sudo apt-get install xclip
Downloads and installs xclip. If you don't have apt-get
, you might need to use another installer (like yum
)
Here is example given which so how to use open
and "python close
from sys import argv
script,filename=argv
txt=open(filename)
print "filename %r" %(filename)
print txt.read()
txt.close()
print "Change the file name"
file_again=raw_input('>')
print "New file name %r" %(file_again)
txt_again=open(file_again)
print txt_again.read()
txt_again.close()
It's necessary to how many times you opened file have to close that times.
With resources, there's built-in support for providing alternatives for different languages, OS versions, screen orientations, etc., as described here. None of that is available with assets. Also, many parts of the API support the use of resource identifiers. Finally, the names of the resources are turned into constant field names that are checked at compile time, so there's less of an opportunity for mismatches between the code and the resources themselves. None of that applies to assets.
So why have an assets folder at all? If you want to compute the asset you want to use at run time, it's pretty easy. With resources, you would have to declare a list of all the resource IDs that might be used and compute an index into the the list. (This is kind of awkward and introduces opportunities for error if the set of resources changes in the development cycle.) (EDIT: you can retrieve a resource ID by name using getIdentifier
, but this loses the benefits of compile-time checking.) Assets can also be organized into a folder hierarchy, which is not supported by resources. It's a different way of managing data. Although resources cover most of the cases, assets have their occasional use.
One other difference: resources defined in a library project are automatically imported to application projects that depend on the library. For assets, that doesn't happen; asset files must be present in the assets directory of the application project(s). [EDIT: With Android's new Gradle-based build system (used with Android Studio), this is no longer true. Asset directories for library projects are packaged into the .aar files, so assets defined in library projects are merged into application projects (so they do not have to be present in the application's /assets
directory if they are in a referenced library).]
EDIT: Yet another difference arises if you want to package a custom font with your app. There are API calls to create a Typeface
from a font file stored in the file system or in your app's assets/
directory. But there is no API to create a Typeface
from a font file stored in the res/
directory (or from an InputStream
, which would allow use of the res/
directory). [NOTE: With Android O (now available in alpha preview) you will be able to include custom fonts as resources. See the description here of this long-overdue feature. However, as long as your minimum API level is 25 or less, you'll have to stick with packaging custom fonts as assets rather than as resources.]
The problem is that you have not included bootstrap.min.css
. Also, the sequence of imports could be causing issue. Please try rearranging your resources as following:
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
You'll find it in the AppData
folder if you choose to install it in the default location. Otherwise, it will be located at the folder where you installed your Android SDK/platform-tools
folder.
Instead of storing the output of grep in a variable and then checking whether the variable is empty, you can do this:
if grep -q "poet" $file_name
then
echo "poet was found in $file_name"
fi
============
Here are some commonly used tests:
-d FILE
FILE exists and is a directory
-e FILE
FILE exists
-f FILE
FILE exists and is a regular file
-h FILE
FILE exists and is a symbolic link (same as -L)
-r FILE
FILE exists and is readable
-s FILE
FILE exists and has a size greater than zero
-w FILE
FILE exists and is writable
-x FILE
FILE exists and is executable
-z STRING
the length of STRING is zero
Example:
if [ -e "$file_name" ] && [ ! -z "$used_var" ]
then
echo "$file_name exists and $used_var is not empty"
fi
The appropriate way for doing this:
@app.route('/')
def index():
if form.validate_on_submit():
if 'download' in request.form:
pass # do something
elif 'watch' in request.form:
pass # do something else
Put watch
and download
buttons into your template:
<input type="submit" name="download" value="Download">
<input type="submit" name="watch" value="Watch">
This will give you a very compact list of all messages for any specified time.
git log --since=1/11/2011 --until=28/11/2011 --no-merges --format=%B > CHANGELOG.TXT
To check if the property is present, irrespective of the value, use:
if (array_key_exists('userName', $_POST)) {}
To check if the property is set (property is present and value is not null
or false
), use:
if (isset($_POST['userName'])) {}
To check if the property is set and not empty (not an empty string, 0
(integer), 0.0
(float), '0'
(string), null
, false
or []
(empty array)), use:
if (!empty($_POST['userName'])) {}
Something I stumbled upon today for a DLL I knew was working fine with my VS2013 project, but not with VS2015:
Go to: Project -> XXXX Properties -> Build -> Uncheck "Prefer 32-bit"
This answer is way overdue and probably won't do any good, but if you. But I hope this will help somebody someday.
If you want to pass props to a component inside a route, the simplest way is by utilizing the render
, like this:
<Route exact path="/details/:id" render={(props) => <DetailsPage globalStore={globalStore} {...props} /> } />
You can access the props inside the DetailPage
using:
this.props.match
this.props.globalStore
The {...props}
is needed to pass the original Route's props, otherwise you will only get this.props.globalStore
inside the DetailPage
.
To find a class in a folder (and subfolders) bunch of JARs: https://jarscan.com/
Usage: java -jar jarscan.jar [-help | /?]
[-dir directory name]
[-zip]
[-showProgress]
<-files | -class | -package>
<search string 1> [search string 2]
[search string n]
Help:
-help or /? Displays this message.
-dir The directory to start searching
from default is "."
-zip Also search Zip files
-showProgress Show a running count of files read in
-files or -class Search for a file or Java class
contained in some library.
i.e. HttpServlet
-package Search for a Java package
contained in some library.
i.e. javax.servlet.http
search string The file or package to
search for.
i.e. see examples above
Example:
java -jar jarscan.jar -dir C:\Folder\To\Search -showProgress -class GenericServlet
you must #include <algorithm>
, then you can use std::find
Or you can use the ^M+^J shortcut also. All a matter of preference. the "CTRL-CHAR" codes are translated by the compiler.
MyString := 'Hello,' + ^M + ^J + 'world!';
You can take the + away between the ^M and ^J, but then you will get a warning by the compiler (but it will still compile fine).
INSERT INTO `table` ( `data` , `date` ) VALUES('".$data."',NOW()+INTERVAL 1 DAY);
You use uninstall the app and change the sharedPreferences name then run this application. I think it will resolve the issue.
A sample code to retrieve values from sharedPreferences you can use the following set of code,
SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
String channel = (shared.getString(keyValue, ""));
The getParent
method returns a ViewParent
, not a View
. You need to cast the first call to getParent()
also:
RelativeLayout r = (RelativeLayout) ((ViewGroup) this.getParent()).getParent();
As stated in the comments by the OP, this is causing a NPE
. To debug, split this up into multiple parts:
ViewParent parent = this.getParent();
RelativeLayout r;
if (parent == null) {
Log.d("TEST", "this.getParent() is null");
}
else {
if (parent instanceof ViewGroup) {
ViewParent grandparent = ((ViewGroup) parent).getParent();
if (grandparent == null) {
Log.d("TEST", "((ViewGroup) this.getParent()).getParent() is null");
}
else {
if (parent instanceof RelativeLayout) {
r = (RelativeLayout) grandparent;
}
else {
Log.d("TEST", "((ViewGroup) this.getParent()).getParent() is not a RelativeLayout");
}
}
}
else {
Log.d("TEST", "this.getParent() is not a ViewGroup");
}
}
//now r is set to the desired RelativeLayout.
There is actually a property for this in the CSS4 media query draft.
The ‘pointer’ media feature is used to query about the presence and accuracy of a pointing device such as a mouse. If a device has multiple input mechanisms, it is recommended that the UA reports the characteristics of the least capable pointing device of the primary input mechanisms. This media query takes the following values:
‘none’
- The input mechanism of the device does not include a pointing device.‘coarse’
- The input mechanism of the device includes a pointing device of limited accuracy.‘fine’
- The input mechanism of the device includes an accurate pointing device.
This would be used as such:
/* Make radio buttons and check boxes larger if we have an inaccurate pointing device */
@media (pointer:coarse) {
input[type="checkbox"], input[type="radio"] {
min-width:30px;
min-height:40px;
background:transparent;
}
}
I also found a ticket in the Chromium project related to this.
Browser compatibility can be tested at Quirksmode. These are my results (22 jan 2013):
You can (should) declare it as extern
in a header file, and define it in exactly 1 .c file.
Note that that .c file should also use the header and that the standard pattern looks like:
// file.h
extern int x; // declaration
// file.c
#include "file.h"
int x = 1; // definition and re-declaration
As a general rule, you can use Database_Default collation so you don't need to figure out which one to use. However, I strongly suggest reading Simons Liew's excellent article Understanding the COLLATE DATABASE_DEFAULT clause in SQL Server
SELECT *
FROM [FAEB].[dbo].[ExportaComisiones] AS f
JOIN [zCredifiel].[dbo].[optPerson] AS p
ON (p.vTreasuryId = f.RFC) COLLATE Database_Default
table
{
margin-left: auto;
margin-right: auto;
}
This will definitely work. Cheers
My answer is based on the koma's but it doesn't require to override onStart but only onCreateView which is almost always overridden by default when you create new fragments.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.your_fragment_layout, container);
Rect displayRectangle = new Rect();
Window window = getDialog().getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);
v.setMinimumWidth((int)(displayRectangle.width() * 0.9f));
v.setMinimumHeight((int)(displayRectangle.height() * 0.9f));
return v;
}
I've tested it on Android 5.0.1.
Not sure what you mean with "class constructor" but I'd assume you mean one of the ones below.
Instance constructor:
Public Sub New()
End Sub
Shared constructor:
Shared Sub New()
End Sub
And an idea with a negative check.
/^(?!\d*$|[a-z]*$)[a-z\d]+$/i
^(?!
at start look ahead if string does not\d*$
contain only digits |
or[a-z]*$
contain only letters[a-z\d]+$
matches one or more letters or digits until $
end.Have a look at this regex101 demo
(the i
flag turns on caseless matching: a-z
matches a-zA-Z
)
As you already found the -T flag that create a PTY, I will just respond to the second part:
shell request failed on channel 0
You should pass a command:
ssh [email protected] -p 22 help
After reading back the manual here: https://www.jenkins.io/doc/book/managing/cli/, I find it not really clear that it would not work without a command. But as stated by @U.V., the ssh interface is not a console interface, rather a connection utility. So you need to pass a command...
If someone from the "jenkins" team pass accross this post, it would be great that if we pass no command, the help would show up :-)
I ran into this scenario recently (well over 7 million rows) and eneded up using sqlcmd via powershell (after parsing raw data into SQL insert statements) in segments of 5,000 at a time (SQL can't handle 7 million lines in one lump job or even 500,000 lines for that matter unless its broken down into smaller 5K pieces. You can then run each 5K script one after the other.) as I needed to leverage the new sequence command in SQL Server 2012 Enterprise. I couldn't find a programatic way to insert seven million rows of data quickly and efficiently with said sequence command.
Secondly, one of the things to look out for when inserting a million rows or more of data in one sitting is the CPU and memory consumption (mostly memory) during the insert process. SQL will eat up memory/CPU with a job of this magnitude without releasing said processes. Needless to say if you don't have enough processing power or memory on your server you can crash it pretty easily in a short time (which I found out the hard way). If you get to the point to where your memory consumption is over 70-75% just reboot the server and the processes will be released back to normal.
I had to run a bunch of trial and error tests to see what the limits for my server was (given the limited CPU/Memory resources to work with) before I could actually have a final execution plan. I would suggest you do the same in a test environment before rolling this out into production.
See all Available Controller : You can do PHP artisan list to view all commands
For help: PHP artisan help make:controller
php artisan make:controller MyControllerName
I don't know about "standard way".
def remove_prefix(text, prefix):
if text.startswith(prefix):
return text[len(prefix):]
return text # or whatever
As noted by @Boris and @Stefan, on Python 3.9+ you can use
text.removeprefix(prefix)
with the same behavior.
After adding this line of code, the issue will be fixed:
nltk.download('punkt')
contentType
is the type of data you're sending, so application/json; charset=utf-8
is a common one, as is application/x-www-form-urlencoded; charset=UTF-8
, which is the default.
dataType
is what you're expecting back from the server: json
, html
, text
, etc. jQuery will use this to figure out how to populate the success function's parameter.
If you're posting something like:
{"name":"John Doe"}
and expecting back:
{"success":true}
Then you should have:
var data = {"name":"John Doe"}
$.ajax({
dataType : "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(data),
success : function(result) {
alert(result.success); // result is an object which is created from the returned JSON
},
});
If you're expecting the following:
<div>SUCCESS!!!</div>
Then you should do:
var data = {"name":"John Doe"}
$.ajax({
dataType : "html",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(data),
success : function(result) {
jQuery("#someContainer").html(result); // result is the HTML text
},
});
One more - if you want to post:
name=John&age=34
Then don't stringify
the data, and do:
var data = {"name":"John", "age": 34}
$.ajax({
dataType : "html",
contentType: "application/x-www-form-urlencoded; charset=UTF-8", // this is the default value, so it's optional
data : data,
success : function(result) {
jQuery("#someContainer").html(result); // result is the HTML text
},
});
This is the working code...
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class JavaCalculator extends JFrame {
private JButton jbtNum1;
private JButton jbtNum2;
private JButton jbtNum3;
private JButton jbtNum4;
private JButton jbtNum5;
private JButton jbtNum6;
private JButton jbtNum7;
private JButton jbtNum8;
private JButton jbtNum9;
private JButton jbtNum0;
private JButton jbtEqual;
private JButton jbtAdd;
private JButton jbtSubtract;
private JButton jbtMultiply;
private JButton jbtDivide;
private JButton jbtSolve;
private JButton jbtClear;
private double TEMP;
private double SolveTEMP;
private JTextField jtfResult;
Boolean addBool = false;
Boolean subBool = false;
Boolean divBool = false;
Boolean mulBool = false;
String display = "";
public JavaCalculator() {
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(4, 3));
p1.add(jbtNum1 = new JButton("1"));
p1.add(jbtNum2 = new JButton("2"));
p1.add(jbtNum3 = new JButton("3"));
p1.add(jbtNum4 = new JButton("4"));
p1.add(jbtNum5 = new JButton("5"));
p1.add(jbtNum6 = new JButton("6"));
p1.add(jbtNum7 = new JButton("7"));
p1.add(jbtNum8 = new JButton("8"));
p1.add(jbtNum9 = new JButton("9"));
p1.add(jbtNum0 = new JButton("0"));
p1.add(jbtClear = new JButton("C"));
JPanel p2 = new JPanel();
p2.setLayout(new FlowLayout());
p2.add(jtfResult = new JTextField(20));
jtfResult.setHorizontalAlignment(JTextField.RIGHT);
jtfResult.setEditable(false);
JPanel p3 = new JPanel();
p3.setLayout(new GridLayout(5, 1));
p3.add(jbtAdd = new JButton("+"));
p3.add(jbtSubtract = new JButton("-"));
p3.add(jbtMultiply = new JButton("*"));
p3.add(jbtDivide = new JButton("/"));
p3.add(jbtSolve = new JButton("="));
JPanel p = new JPanel();
p.setLayout(new GridLayout());
p.add(p2, BorderLayout.NORTH);
p.add(p1, BorderLayout.SOUTH);
p.add(p3, BorderLayout.EAST);
add(p);
jbtNum1.addActionListener(new ListenToOne());
jbtNum2.addActionListener(new ListenToTwo());
jbtNum3.addActionListener(new ListenToThree());
jbtNum4.addActionListener(new ListenToFour());
jbtNum5.addActionListener(new ListenToFive());
jbtNum6.addActionListener(new ListenToSix());
jbtNum7.addActionListener(new ListenToSeven());
jbtNum8.addActionListener(new ListenToEight());
jbtNum9.addActionListener(new ListenToNine());
jbtNum0.addActionListener(new ListenToZero());
jbtAdd.addActionListener(new ListenToAdd());
jbtSubtract.addActionListener(new ListenToSubtract());
jbtMultiply.addActionListener(new ListenToMultiply());
jbtDivide.addActionListener(new ListenToDivide());
jbtSolve.addActionListener(new ListenToSolve());
jbtClear.addActionListener(new ListenToClear());
} //JavaCaluclator()
class ListenToClear implements ActionListener {
public void actionPerformed(ActionEvent e) {
//display = jtfResult.getText();
jtfResult.setText("");
addBool = false;
subBool = false;
mulBool = false;
divBool = false;
TEMP = 0;
SolveTEMP = 0;
}
}
class ListenToOne implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "1");
}
}
class ListenToTwo implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "2");
}
}
class ListenToThree implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "3");
}
}
class ListenToFour implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "4");
}
}
class ListenToFive implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "5");
}
}
class ListenToSix implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "6");
}
}
class ListenToSeven implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "7");
}
}
class ListenToEight implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "8");
}
}
class ListenToNine implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "9");
}
}
class ListenToZero implements ActionListener {
public void actionPerformed(ActionEvent e) {
display = jtfResult.getText();
jtfResult.setText(display + "0");
}
}
class ListenToAdd implements ActionListener {
public void actionPerformed(ActionEvent e) {
TEMP = Double.parseDouble(jtfResult.getText());
jtfResult.setText("");
addBool = true;
}
}
class ListenToSubtract implements ActionListener {
public void actionPerformed(ActionEvent e) {
TEMP = Double.parseDouble(jtfResult.getText());
jtfResult.setText("");
subBool = true;
}
}
class ListenToMultiply implements ActionListener {
public void actionPerformed(ActionEvent e) {
TEMP = Double.parseDouble(jtfResult.getText());
jtfResult.setText("");
mulBool = true;
}
}
class ListenToDivide implements ActionListener {
public void actionPerformed(ActionEvent e) {
TEMP = Double.parseDouble(jtfResult.getText());
jtfResult.setText("");
divBool = true;
}
}
class ListenToSolve implements ActionListener {
public void actionPerformed(ActionEvent e) {
SolveTEMP = Double.parseDouble(jtfResult.getText());
if (addBool == true)
SolveTEMP = SolveTEMP + TEMP;
else if ( subBool == true)
SolveTEMP = SolveTEMP - TEMP;
else if ( mulBool == true)
SolveTEMP = SolveTEMP * TEMP;
else if ( divBool == true)
SolveTEMP = SolveTEMP / TEMP;
jtfResult.setText( Double.toString(SolveTEMP));
addBool = false;
subBool = false;
mulBool = false;
divBool = false;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
JavaCalculator calc = new JavaCalculator();
calc.pack();
calc.setLocationRelativeTo(null);
calc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
calc.setVisible(true);
}
} //JavaCalculator
Change this:
using (var dataContext = new dataContext())
{
users = dataContext.Users.Where(x => x.AccountID == accountId && x.IsAdmin == false);
if(users.Any())
{
ret = users.Select(x => x.ToInfo()).ToList();
}
}
to this:
using (var dataContext = new dataContext())
{
return = dataContext.Users.Where(x => x.AccountID == accountId && x.IsAdmin == false).Select(x => x.ToInfo()).ToList();
}
The gist is that you only want to force the enumeration of the context dataset once. Let the caller deal with empty set scenario, as they should.
Please note that you must install the driver for the version of your software client(MS access) not the version of the OS. that's mean that if your MS Access is a 32-bits version,you must install a 32-bit odbc driver. regards
I have design google map infowindow with image & some content as per below.
map_script (Just for infowindow html reference)
for (i = 0; i < locations.length; i++) {
var latlng = new google.maps.LatLng(locations[i][1], locations[i][2]);
marker = new google.maps.Marker({
position: latlng,
map: map,
icon: "<?php echo plugins_url( 'assets/img/map-pin.png', ELEMENTOR_ES__FILE__ ); ?>"
});
var property_img = locations[i][6],
title = locations[i][0],
price = locations[i][3],
bedrooms = locations[i][4],
type = locations[i][5],
listed_on = locations[i][7],
prop_url = locations[i][8];
content = "<div class='map_info_wrapper'><a href="+prop_url+"><div class='img_wrapper'><img src="+property_img+"></div>"+
"<div class='property_content_wrap'>"+
"<div class='property_title'>"+
"<span>"+title+"</span>"+
"</div>"+
"<div class='property_price'>"+
"<span>"+price+"</span>"+
"</div>"+
"<div class='property_bed_type'>"+
"<span>"+bedrooms+"</span>"+
"<ul><li>"+type+"</li></ul>"+
"</div>"+
"<div class='property_listed_date'>"+
"<span>Listed on "+listed_on+"</span>"+
"</div>"+
"</div></a></div>";
google.maps.event.addListener(marker, 'click', (function(marker, content, i) {
return function() {
infowindow.setContent(content);
infowindow.open(map, marker);
}
})(marker, content, i));
}
Most important thing is CSS
#propertymap .gm-style-iw{
box-shadow:none;
color:#515151;
font-family: "Georgia", "Open Sans", Sans-serif;
text-align: center;
width: 100% !important;
border-radius: 0;
left: 0 !important;
top: 20px !important;
}
#propertymap .gm-style > div > div > div > div > div > div > div {
background: none!important;
}
.gm-style > div > div > div > div > div > div > div:nth-child(2) {
box-shadow: none!important;
}
#propertymap .gm-style-iw > div > div{
background: #FFF!important;
}
#propertymap .gm-style-iw a{
text-decoration: none;
}
#propertymap .gm-style-iw > div{
width: 245px !important
}
#propertymap .gm-style-iw .img_wrapper {
height: 150px;
overflow: hidden;
width: 100%;
text-align: center;
margin: 0px auto;
}
#propertymap .gm-style-iw .img_wrapper > img {
width: 100%;
height:auto;
}
#propertymap .gm-style-iw .property_content_wrap {
padding: 0px 20px;
}
#propertymap .gm-style-iw .property_title{
min-height: auto;
}
Aergistal's answer works, but I found that converting to mp4 can make some m3u8 videos broken. If you are stuck with this problem, try to convert them to mkv, and convert them to mp4 later.
If you use that forumla in the name manager you are creating a dynamic range which uses "this sheet" in place of a specific sheet.
As Jerry says, Sheet1!A1 refers to cell A1 on Sheet1. If you create a named range and omit the Sheet1 part you will reference cell A1 on the currently active sheet. (omitting the sheet reference and using it in a cell formula will error).
edit: my bad, I was using $A$1 which will lock it to the A1 cell as above, thanks pnuts :p
To go twice as fast by using multiple processor cores HPCsharp nuget package provides:
list.ToArrayPar();
Also you can try opensource WebRTC Media Server Kurento
Which can play RTSP video stream and send it to WebRTC or transcode to RTMP or saving on server.
We are useing it on Production for the following cases:
- WebRTC to Webrtc (many to many) - WebRTC to RTMP - RTSP to WebRTC
code:
TextView your_text_view = (TextView) findViewById(R.id.your_id_textview);
your_text_view.setEllipsize(TextUtils.TruncateAt.END);
xml:
android:maxLines = "5"
e.g.
In Matthew 13, the disciples asked Jesus why He spoke to the crowds in parables. He answered, "It has been given to you to know the mysteries of the kingdom of heaven, but to them it has not been given.
Output: In Matthew 13, the disciples asked Jesus why He spoke to the crowds in parables. He answered, "It has been given to you to know...
hi it worked for me from the recommended link from Fredy Andersen
sudo install_name_tool -change libmysqlclient.16.dylib /usr/local/mysql /lib/libmysqlclient.16.dylib /Library/Ruby/Gems/1.8/gems/mysql2-0.2.6/lib/mysql2/mysql2.bundle
just had to change to my version of mysql, in the command, thanks
Answer:
c
is the only valid hex character in chucknorris, the value turns into: c00c00000000
(0 for all values that were invalid). Red = c00c
, Green = 0000
, Blue = 0000
.c00000
which is a brick-reddish toned color.Use StringUtils.isEmpty
instead, it will also check for null.
Examples are:
StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true
StringUtils.isEmpty(" ") = false
StringUtils.isEmpty("bob") = false
StringUtils.isEmpty(" bob ") = false
See more on official Documentation on String Utils.
So the issue is actually that you are not waiting for the init to complete. This will cause random results. Here is what I use.
window.fbAsyncInit = function () {
FB.init({ appId: 'your-app-id', cookie: true, xfbml: true, oauth: true });
// *** here is my code ***
if (typeof facebookInit == 'function') {
facebookInit();
}
};
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
This will ensure that once everything is loaded, the function facebookInit is available and executed. That way you don't have to duplicate the init code every time you want to use it.
function facebookInit() {
// do what you would like here
}
Solved the problem with:
sudo chown -R $USER:$USER /var/www/folder-name
sudo chmod -R 755 /var/www
Grant permissions
Firstly this is a very good question.
e.g. The authorization header or content type header. Which is absolutely required by the server to understand the request. This can differ from server to server.
This is less severe than 400. The request has reached the server. The server has acknowledged the request has got the basic structure right. But the information in the request body can't be parsed or understood.
e.g. Content-Type: application/xml
when request body is JSON.
Here's an article listing status codes and its use in REST APIs. https://metamug.com/article/status-codes-for-rest-api.php
There's another CURL method if you are going that way.
This is pretty straightforward once you get your head around the way the PHP curl extension works, combining various flags with setopt() calls. In this example I've got a variable $xml which holds the XML I have prepared to send - I'm going to post the contents of that to example's test method.
$url = 'http://api.example.com/services/xmlrpc/';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
//process $response
First we initialised the connection, then we set some options using setopt(). These tell PHP that we are making a post request, and that we are sending some data with it, supplying the data. The CURLOPT_RETURNTRANSFER flag tells curl to give us the output as the return value of curl_exec rather than outputting it. Then we make the call and close the connection - the result is in $response.
An easy way to deal with refs:
class UserInfo extends React.Component {_x000D_
_x000D_
constructor(props) {_x000D_
super(props);_x000D_
this.handleSubmit = this.handleSubmit.bind(this);_x000D_
}_x000D_
_x000D_
handleSubmit(e) {_x000D_
e.preventDefault();_x000D_
_x000D_
const formData = {};_x000D_
for (const field in this.refs) {_x000D_
formData[field] = this.refs[field].value;_x000D_
}_x000D_
console.log('-->', formData);_x000D_
}_x000D_
_x000D_
render() {_x000D_
return (_x000D_
<div>_x000D_
<form onSubmit={this.handleSubmit}>_x000D_
<input ref="phone" className="phone" type='tel' name="phone"/>_x000D_
<input ref="email" className="email" type='tel' name="email"/>_x000D_
<input type="submit" value="Submit"/>_x000D_
</form>_x000D_
</div>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
export default UserInfo;
_x000D_
typedef void (Dog::*memfun)();
memfun doSomething = &Dog::bark;
....
(pDog->*doSomething)(); // if pDog is a pointer
// (pDog.*doSomething)(); // if pDog is a reference
I asked one angle of this question here, and the answers will lead you to all the token-based timing-out cookie links you need.
Basically, you do not store the userId in the cookie. You store a one-time token (huge string) which the user uses to pick-up their old login session. Then to make it really secure, you ask for a password for heavy operations (like changing the password itself).
My Xcode Version 6.1.1 (6A2008a)
In playground, test like this:
// I'm in East Timezone 8
let x = NSDate() //Output:"Dec 29, 2014, 11:37 AM"
let y = NSDate.init() //Output:"Dec 29, 2014, 11:37 AM"
println(x) //Output:"2014-12-29 03:37:24 +0000"
// seconds since 2001
x.hash //Output:441,517,044
x.hashValue //Output:441,517,044
x.timeIntervalSinceReferenceDate //Output:441,517,044.875367
// seconds since 1970
x.timeIntervalSince1970 //Output:1,419,824,244.87537
First you have to install a module call Serial. To do that go to the folder call Scripts which is located in python installed folder. If you are using Python 3 version it's normally located in location below,
C:\Python34\Scripts
Once you open that folder right click on that folder with shift key. Then click on 'open command window here'. After that cmd
will pop up. Write the below code in that cmd
window,
pip install PySerial
and press enter.after that PySerial module will be installed. Remember to install the module u must have an INTERNET connection.
after successfully installed the module open python IDLE and write down the bellow code and run it.
import serial
# "COM11" is the port that your Arduino board is connected.set it to port that your are using
ser = serial.Serial("COM11", 9600)
while True:
cc=str(ser.readline())
print(cc[2:][:-5])
awk '
{
for (i=1; i<=NF; i++) {
a[NR,i] = $i
}
}
NF>p { p = NF }
END {
for(j=1; j<=p; j++) {
str=a[1,j]
for(i=2; i<=NR; i++){
str=str" "a[i,j];
}
print str
}
}' file
output
$ more file
0 1 2
3 4 5
6 7 8
9 10 11
$ ./shell.sh
0 3 6 9
1 4 7 10
2 5 8 11
Performance against Perl solution by Jonathan on a 10000 lines file
$ head -5 file
1 0 1 2
2 3 4 5
3 6 7 8
4 9 10 11
1 0 1 2
$ wc -l < file
10000
$ time perl test.pl file >/dev/null
real 0m0.480s
user 0m0.442s
sys 0m0.026s
$ time awk -f test.awk file >/dev/null
real 0m0.382s
user 0m0.367s
sys 0m0.011s
$ time perl test.pl file >/dev/null
real 0m0.481s
user 0m0.431s
sys 0m0.022s
$ time awk -f test.awk file >/dev/null
real 0m0.390s
user 0m0.370s
sys 0m0.010s
EDIT by Ed Morton (@ghostdog74 feel free to delete if you disapprove).
Maybe this version with some more explicit variable names will help answer some of the questions below and generally clarify what the script is doing. It also uses tabs as the separator which the OP had originally asked for so it'd handle empty fields and it coincidentally pretties-up the output a bit for this particular case.
$ cat tst.awk
BEGIN { FS=OFS="\t" }
{
for (rowNr=1;rowNr<=NF;rowNr++) {
cell[rowNr,NR] = $rowNr
}
maxRows = (NF > maxRows ? NF : maxRows)
maxCols = NR
}
END {
for (rowNr=1;rowNr<=maxRows;rowNr++) {
for (colNr=1;colNr<=maxCols;colNr++) {
printf "%s%s", cell[rowNr,colNr], (colNr < maxCols ? OFS : ORS)
}
}
}
$ awk -f tst.awk file
X row1 row2 row3 row4
column1 0 3 6 9
column2 1 4 7 10
column3 2 5 8 11
The above solutions will work in any awk (except old, broken awk of course - there YMMV).
The above solutions do read the whole file into memory though - if the input files are too large for that then you can do this:
$ cat tst.awk
BEGIN { FS=OFS="\t" }
{ printf "%s%s", (FNR>1 ? OFS : ""), $ARGIND }
ENDFILE {
print ""
if (ARGIND < NF) {
ARGV[ARGC] = FILENAME
ARGC++
}
}
$ awk -f tst.awk file
X row1 row2 row3 row4
column1 0 3 6 9
column2 1 4 7 10
column3 2 5 8 11
which uses almost no memory but reads the input file once per number of fields on a line so it will be much slower than the version that reads the whole file into memory. It also assumes the number of fields is the same on each line and it uses GNU awk for ENDFILE
and ARGIND
but any awk can do the same with tests on FNR==1
and END
.
try:
var url = '/Home/Index/' + e.value;
window.location = window.location.host + url;
That should get you where you want.
The accepted answer detects digits but does not detect formated numbers, e.g. 2,000, nor decimals, e.g. 4.8. For such use -?\\d+(,\\d+)*?\\.?\\d+?
:
Pattern p = Pattern.compile("-?\\d+(,\\d+)*?\\.?\\d+?");
List<String> numbers = new ArrayList<String>();
Matcher m = p.matcher("Government has distributed 4.8 million textbooks to 2,000 schools");
while (m.find()) {
numbers.add(m.group());
}
System.out.println(numbers);
Output:
[4.8, 2,000]
I was facing issues and the problem was a whitespace at the end of spring.datasource.type = com.zaxxer.hikari.HikariDataSource
You need to add uppercase L
at the end like so
long i = 12345678910L;
Same goes true for float with 3.0f
Which should answer both of your questions
A proper way to search for a substring is to use position
function instead of like
expression, which requires escaping %
, _
and an escape character (\
by default):
SELECT id FROM TAG_TABLE WHERE position(tag_name in 'aaaaaaaaaaa')>0;
Rephrasing Yuri, Fábio, and Frosts answers for the Django noob (i.e. me) - almost certainly a simplification, but a good starting point?
render_to_response()
is the "original", but requires you putting context_instance=RequestContext(request)
in nearly all the time, a PITA.
direct_to_template()
is designed to be used just in urls.py without a view defined in views.py but it can be used in views.py to avoid having to type RequestContext
render()
is a shortcut for render_to_response()
that automatically supplies context_instance=Request
....
Its available in the django development version (1.2.1) but many have created their own shortcuts such as this one, this one or the one that threw me initially, Nathans basic.tools.shortcuts.py
if your text doesn't spill over two rows then you can do line-height: ;
in your CSS, the more line-height you give, the lower on the container it will hold.
As we can read here (Peter Gulutzan) there is difference on sorting/comparing polish letter "L" (L with stroke - html esc: Ł
) (lower case: "l" - html esc: ł
) - we have following assumption:
utf8_polish_ci L greater than L and less than M
utf8_unicode_ci L greater than L and less than M
utf8_unicode_520_ci L equal to L
utf8_general_ci L greater than Z
In polish language letter L
is after letter L
and before M
. No one of this coding is better or worse - it depends of your needs.
Besides just using include()
or include_once()
to include the header and footer, one thing I have found useful is being able to have a custom page title or custom head tags to be included for each page, yet still have the header in a partial include. I usually accomplish this as follows:
In the site pages:
<?php
$PageTitle="New Page Title";
function customPageHeader(){?>
<!--Arbitrary HTML Tags-->
<?php }
include_once('header.php');
//body contents go here
include_once('footer.php');
?>
And, in the header.php file:
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title><?= isset($PageTitle) ? $PageTitle : "Default Title"?></title>
<!-- Additional tags here -->
<?php if (function_exists('customPageHeader')){
customPageHeader();
}?>
</head>
<body>
Maybe a bit beyond the scope of your original question, but it is useful to allow a bit more flexibility with the include.
You just need to add a jquery selector after the url.
See: http://api.jquery.com/load/
Example straight from the API:
$('#result').load('ajax/test.html #container');
So what that does is it loads the #container element from the specified url.
<RatingBar
android:id="@+id/rating"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="?android:attr/ratingBarStyleSmall"
android:numStars="5"
android:stepSize="0.1"
android:isIndicator="true" />
in code
mRatingBar.setRating(int)
SELECT *
FROM
(First_query) AS ONE
LEFT OUTER JOIN
(Second_query ) AS TWO ON ONE.First_query_ID = TWO.Second_Query_ID;
You can take a look here for a longer list of screen sizes and respective media queries.
Or go for Bootstrap media queries:
/* Large desktop */
@media (min-width: 1200px) { ... }
/* Portrait tablet to landscape and desktop */
@media (min-width: 768px) and (max-width: 979px) { ... }
/* Landscape phone to portrait tablet */
@media (max-width: 767px) { ... }
/* Landscape phones and down */
@media (max-width: 480px) { ... }
Additionally you might wanty to take a look at Foundation's media queries with the following default settings:
// Media Queries
$screenSmall: 768px !default;
$screenMedium: 1279px !default;
$screenXlarge: 1441px !default;
On a fresh Debian image, cloning https://github.com/python/cpython and running:
sudo apt-get update
sudo apt-get upgrade
sudo apt-get dist-upgrade
sudo apt-get install build-essential python-dev python-setuptools python-pip python-smbus
sudo apt-get install libncursesw5-dev libgdbm-dev libc6-dev
sudo apt-get install zlib1g-dev libsqlite3-dev tk-dev
sudo apt-get install libssl-dev openssl
sudo apt-get install libffi-dev
Now execute the configure
file cloned above:
./configure
make # alternatively `make -j 4` will utilize 4 threads
sudo make altinstall
Got 3.7 installed and working for me.
Looks like I said I would update this answer with some more explanation and two years later I don't have much to add.
python-dev
might be necessary.altinstall
as opposed to install
argument in the make command.Aside from that I guess the choice would be to either read through the cpython codebase looking for #include
directives that need to be met, but what I usually do is keep trying to install the package and just keep reading through the output installing the required packages until it succeeds.
Reminds me of the story of the Engineer, the Manager and the Programmer whose car rolls down a hill.
Instead of doing all these.. cant you use a simpler approach as shown below.
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
Response.ContentType = "application/excel";
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
You can get the entire walkthrough here
Coming late to the party, but I found this fantastic step-by-step guide on getting control of your SQLExpress instance if you don't have your sa password. I used this process to not only reset my sa password, but I also added my domain account to all the available server roles. I can now create databases, alter logins, do bulk operations, backups/restores, etc using my normal login.
To summarize, you use SQL Server Configuration Manager to put your instance into single-user mode. This elevates you to sysadmin when you connect, allowing you the ability to set everything up.
Edit: I've copied the steps below - kudos to the original author of the link above.
If you did git push origin -u localBranchName:remoteBranchName
and on sequentially git push
commands, you get errors that then origin doesn't exist, then follow these steps:
git remote -v
Check if there is any remote that I don't care.
Delete them with git remote remove 'name'
git config --edit
Look for possible signs of a old/non-existent remote.
Look for pushdefault
:
[remote]
pushdefault = oldremote
Update oldremote
value and save.
git push
should work now.
Tarkus's answer works well. However, I would suggest replacing VIEWSTATE with SESSION.
The current page's VIEWSTATE only works while the current page posts back to itself and is gone once the user is redirected away to another page. SESSION persists the sort order on more than just the current page's post-back. It persists it across the entire duration of the session. This means that the user can surf around to other pages, and when he comes back to the given page, the sort order he last used still remains. This is usually more convenient.
There are other methods, too, such as persisting user profiles.
I recommend this article for a very good explanation of ViewState and how it works with a web page's life cycle: https://msdn.microsoft.com/en-us/library/ms972976.aspx
To understand the difference between VIEWSTATE, SESSION and other ways of persisting variables, I recommend this article: https://msdn.microsoft.com/en-us/library/75x4ha6s.aspx
I know you wanted "free", but I'd seriously consider getting the data from csidata.com for about $300/year, if I were you.
It's what yahoo uses to supply their data.
It comes with a decent API, and the data is (as far as I can tell) very clean.
You get 10 years of history when you subscribe, and then nightly updates afterward.
They also take care of all sorts of nasty things like splits and dividends for you. If you haven't yet discovered the joy that is data-cleaning, you won't realize how much you need this, until the first time your ATS (Automated Trading System) thinks some stock is really really cheap, only because it split 2:1 and you didn't notice.
When the C# 5 CTP was introduced, you certainly could mark Main with async
... although it was generally not a good idea to do so. I believe this was changed by the release of VS 2013 to become an error.
Unless you've started any other foreground threads, your program will exit when Main
completes, even if it's started some background work.
What are you really trying to do? Note that your GetList()
method really doesn't need to be async at the moment - it's adding an extra layer for no real reason. It's logically equivalent to (but more complicated than):
public Task<List<TvChannel>> GetList()
{
return new GetPrograms().DownloadTvChannels();
}
You need to import the module datetime
first:
>>> import datetime
After that it works:
>>> import datetime
>>> date = datetime.date.today()
>>> date
datetime.date(2013, 11, 12)
Try this on your TA:
# Simulate multiplying two N-bit two's-complement numbers
# into a 2N-bit accumulator
# Use shift-add so that it's O(base_2_log(N)) not O(N)
for numa, numb in ((3, 5), (-3, 5), (3, -5), (-3, -5), (-127, -127)):
print numa, numb,
accum = 0
negate = False
if numa < 0:
negate = True
numa = -numa
while numa:
if numa & 1:
accum += numb
numa >>= 1
numb <<= 1
if negate:
accum = -accum
print accum
output:
3 5 15
-3 5 -15
3 -5 -15
-3 -5 15
-127 -127 16129
Just as Oded has answered. You need to have this sort of detection functionality in javascript.
I've struggled with this myself and realized that the offset is not enough. It does not give you any information about daylight saving for example. I ended up writing some code to map to zoneinfo database keys.
By checking several dates around a year you can more accurately determine a timezone.
Try the script here: http://jsfiddle.net/pellepim/CsNcf/
Simply change your system timezone and click run to test it. If you are running chrome you need to do each test in a new tab though (and safar needs to be restarted to pick up timezone changes).
If you want more details of the code check out: https://bitbucket.org/pellepim/jstimezonedetect/
\
does the job. @Guillaume's answer and @George's comment clearly answer this question. Here I explains why The backslash has to be the very last character before the end of line character.
Consider this command:
mysql -uroot \ -hlocalhost
If there is a space after \
, the line continuation will not work. The reason is that \
removes the special meaning for the next character which is a space not the invisible line feed character. The line feed character is after the space not \
in this example.
import random
n=int(input("Enter size of table 1")); #size of list 1
m=int(input("Enter size of table 2")); # size of list 2
tb1=[random.randrange(1,101,1) for _ in range(n)] # filling the list with random
tb2=[random.randrange(1,101,1) for _ in range(m)] # numbers between 1 and 100
tb1.sort(); #sort the list 1
tb2.sort(); # sort the list 2
fus=[]; # creat an empty list
print(tb1); # print the list 1
print('------------------------------------');
print(tb2); # print the list 2
print('------------------------------------');
i=0;j=0; # varialbles to cross the list
while(i<n and j<m):
if(tb1[i]<tb2[j]):
fus.append(tb1[i]);
i+=1;
else:
fus.append(tb2[j]);
j+=1;
if(i<n):
fus+=tb1[i:n];
if(j<m):
fus+=tb2[j:m];
print(fus);
# this code is used to merge two sorted lists in one sorted list (FUS) without
#sorting the (FUS)
For Oracle, it is also LENGTH instead of LEN
SELECT MAX(LENGTH(Desc)) FROM table_name
Also, DESC is a reserved word. Although many reserved words will still work for column names in many circumstances it is bad practice to do so, and can cause issues in some circumstances. They are reserved for a reason.
If the word Desc was just being used as an example, it should be noted that not everyone will realize that, but many will realize that it is a reserved word for Descending. Personally, I started off by using this, and then trying to figure out where the column name went because all I had were reserved words. It didn't take long to figure it out, but keep that in mind when deciding on what to substitute for your actual column name.
Use JSON classes for parsing e.g
JSONObject mainObject = new JSONObject(Your_Sring_data);
JSONObject uniObject = mainObject.getJSONObject("university");
String uniName = uniObject.getString("name");
String uniURL = uniObject.getString("url");
JSONObject oneObject = mainObject.getJSONObject("1");
String id = oneObject.getString("id");
....
=$W$4<=TODAY()
Returns true for dates up to and including today, false otherwise.
I know this is an old question, but there's actually a new answer to it.
You're right that a hash map isn't really O(1)
, strictly speaking, because as the number of elements gets arbitrarily large, eventually you will not be able to search in constant time (and O-notation is defined in terms of numbers that can get arbitrarily large).
But it doesn't follow that the real time complexity is O(n)
--because there's no rule that says that the buckets have to be implemented as a linear list.
In fact, Java 8 implements the buckets as TreeMaps
once they exceed a threshold, which makes the actual time O(log n)
.
You can always use a properly formatted string. The trick is the formatting.
command.Parameters.Add("@array_parameter", string.Format("{{{0}}}", string.Join(",", array));
Note that if your array is an array of strings, then you'll need to use array.Select(value => string.Format("\"{0}\", value)) or the equivalent. I use this style for an array of an enumerated type in PostgreSQL, because there's no automatic conversion from the array.
In my case, my enumerated type has some values like 'value1', 'value2', 'value3', and my C# enumeration has matching values. In my case, the final SQL query ends up looking something like (E'{"value1","value2"}'), and this works.
It's basic step notation, consider the functionality of:
a[2:4:2]
What happens is the index is sliced between position 2 and 4, what the third variable does is it sets the step size starting from the first value. In this case it would return a[2], since a[4] is an upper bounds only two values are return and no second step takes place. The (-) minus operator simply reverses the step output.
<xs:element name="price" type="decimal">
<xs:attribute name="currency" type="xs:string" value="(euros|pounds|dollars)" />
</element>
This would eliminate the need for enumeration completely. You could change type to double if required.
For completeness sake, also a solution with Joda-Time version 2.5 and its DateTime
class:
new Timestamp(new DateTime(2007, 9, 23, 0, 0, DateTimeZone.forID( "America/Montreal" )).getMillis())
I was getting this error in websphere 8.5:
java.lang.UnsupportedClassVersionError: JVMCFRE003 bad major version; class=com/xxx/Whatever, offset=6
I had my project JDK level set at 1.7 in eclipse and was8 by default runs on JDK 1.6 so there was a clash. I had to install the optional SDK 1.7 to my websphere server and then the problem went away. I guess I could have also set my project level down to 1.6 in eclipse but I wanted to code to 1.7.
I had this problem and it turned out I was trying to restore to the wrong version of SQL. If you want more information on what's going on, try restoring the database using the following SQL:
RESTORE DATABASE <YourDatabase>
FROM DISK='<the path to your backup file>\<YourDatabase>.bak'
That should give you the error message that you need to debug this.
You are correct that this is currently not natively supported in Android, although Google has been saying it will be coming ever since Android was officially launched.
While not natively supported, the hardware on every android device released to date do support it. It is just disabled in software, and you would need to enable it in order to use these features.
It is however, fairly easy to do this, but you need to be root, and the specifics may be slightly different between different devices. Your best source for more informationa about this, would be XDA developers: http://forum.xda-developers.com/forumdisplay.php?f=564. Most of the existing solutions are based on replacing wpa_supplicant, and is the method I would recommend if possible on your device. For more details, see http://szym.net/2010/12/adhoc-wifi-in-android/.
Update: Its been a few years now, and whenever I need an ad hoc network connection on my phone I use CyanogenMod. It gives you both programmatic and scripted access to these functions, and the ability to create ad hoc (ibss) networks in the WiFi settings menu.
Datatable.Clone
is slow for large tables. I'm currently using this:
Dim target As DataTable =
New DataView(source, "1=2", Nothing, DataViewRowState.CurrentRows)
.ToTable()
Note that this only copies the structure of source table, not the data.
Probably your code works but it is rebound somewhere after you clear it. Make sure that this it not the case. It will be more helpful if you provide some code. Where are you setting your data source? Where are you data binding? Where are you clearing the list?
I also tried this style for ionic hybrid app background. this is also having style for background blur effect.
.bg-image {
position: absolute;
background: url(../img/bglogin.jpg) no-repeat;
height: 100%;
width: 100%;
background-size: cover;
bottom: 0px;
margin: 0 auto;
background-position: 50%;
-webkit-filter: blur(5px);
-moz-filter: blur(5px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(5px);
}
Please make your life easier (don't use join into group):
var query = from ug in UserGroups
from ugp in UserGroupPrices.Where(x => x.UserGroupId == ug.Id).DefaultIfEmpty()
select new
{
UserGroupID = ug.UserGroupID,
UserGroupName = ug.UserGroupName,
Price = ugp != null ? ugp.Price : 0 //this is to handle nulls as even when Price is non-nullable prop it may come as null from SQL (result of Left Outer Join)
};
I have a lot of issues with most of the answers posted - they either use deprecated libraries that have been ported over with limited features, or provide a solution with too much magic on the execution of the request, making it difficult to error handle. If they do not fall into one of the above categories, they're 3rd party libraries or deprecated.
Some of the solutions works alright purely in http requests, but the solutions fall short for any other kind of request, which is ludicrous. A highly customized solution is not necessary here.
Simply using the python built-in library asyncio
is sufficient enough to perform asynchronous requests of any type, as well as providing enough fluidity for complex and usecase specific error handling.
import asyncio
loop = asyncio.get_event_loop()
def do_thing(params):
async def get_rpc_info_and_do_chores(id):
# do things
response = perform_grpc_call(id)
do_chores(response)
async def get_httpapi_info_and_do_chores(id):
# do things
response = requests.get(URL)
do_chores(response)
async_tasks = []
for element in list(params.list_of_things):
async_tasks.append(loop.create_task(get_chan_info_and_do_chores(id)))
async_tasks.append(loop.create_task(get_httpapi_info_and_do_chores(ch_id)))
loop.run_until_complete(asyncio.gather(*async_tasks))
How it works is simple. You're creating a series of tasks you'd like to occur asynchronously, and then asking a loop to execute those tasks and exit upon completion. No extra libraries subject to lack of maintenance, no lack of functionality required.
Apparently, Chrome addresses a key in Windows registry when it looks for a Java Environment. Since the plugin installs the JRE, this key is set to a JRE path and therefore needs to be edited if you want Chrome to work with the JDK.
regedit
to edit the registry.Edit "Path" so that it matches the corresponding dll inside your JDK installation:
REGEDIT 4
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin]
"Description"="Oracle® Next Generation Java™ Plug-In"
"GeckoVersion"="1.9"
"Path"="C:\Program Files (x86)\Java\jdk1.6.0_29\jre\bin\new_plugin\npjp2.dll"
"ProductName"="Oracle® Java™ Plug-In"
"Vendor"="Oracle Corp."
"Version"="160_29"
Save file.
The REGEDIT 4
prefix at the top of the file might only be required for Windows 7 64-bit.
In Bootstrap 3 I've added a table-no-border class
.table-no-border>thead>tr>th,
.table-no-border>tbody>tr>th,
.table-no-border>tfoot>tr>th,
.table-no-border>thead>tr>td,
.table-no-border>tbody>tr>td,
.table-no-border>tfoot>tr>td {
border-top: none;
}
You can use RelativeLayout. Let's say you wanted a 30x40 ImageView at position (50,60) inside your layout. Somewhere in your activity:
// Some existing RelativeLayout from your layout xml
RelativeLayout rl = (RelativeLayout) findViewById(R.id.my_relative_layout);
ImageView iv = new ImageView(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = 50;
params.topMargin = 60;
rl.addView(iv, params);
More examples:
Places two 30x40 ImageViews (one yellow, one red) at (50,60) and (80,90), respectively:
RelativeLayout rl = (RelativeLayout) findViewById(R.id.my_relative_layout);
ImageView iv;
RelativeLayout.LayoutParams params;
iv = new ImageView(this);
iv.setBackgroundColor(Color.YELLOW);
params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = 50;
params.topMargin = 60;
rl.addView(iv, params);
iv = new ImageView(this);
iv.setBackgroundColor(Color.RED);
params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = 80;
params.topMargin = 90;
rl.addView(iv, params);
Places one 30x40 yellow ImageView at (50,60) and another 30x40 red ImageView <80,90> relative to the yellow ImageView:
RelativeLayout rl = (RelativeLayout) findViewById(R.id.my_relative_layout);
ImageView iv;
RelativeLayout.LayoutParams params;
int yellow_iv_id = 123; // Some arbitrary ID value.
iv = new ImageView(this);
iv.setId(yellow_iv_id);
iv.setBackgroundColor(Color.YELLOW);
params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = 50;
params.topMargin = 60;
rl.addView(iv, params);
iv = new ImageView(this);
iv.setBackgroundColor(Color.RED);
params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = 80;
params.topMargin = 90;
// This line defines how params.leftMargin and params.topMargin are interpreted.
// In this case, "<80,90>" means <80,90> to the right of the yellow ImageView.
params.addRule(RelativeLayout.RIGHT_OF, yellow_iv_id);
rl.addView(iv, params);
For Google i'm using this method.
function is_google() {
$ip = $_SERVER['REMOTE_ADDR'];
$host = gethostbyaddr( $ip );
if ( strpos( $host, '.google.com' ) !== false || strpos( $host, '.googlebot.com' ) !== false ) {
$forward_lookup = gethostbyname( $host );
if ( $forward_lookup == $ip ) {
return true;
}
return false;
} else {
return false;
}
}
var_dump( is_google() );
Let's say we need to use the class Classname
that is contained in the jar file org.example.jar
And your source is in the file mysource.java
Like this:
import org.example.Classname;
public class mysource {
public static void main(String[] argv) {
......
}
}
First, as you see, in your code you have to import the classes. To do that you need import org.example.Classname;
Second, when you compile the source, you have to reference the jar file.
Please note the difference in using :
and ;
while compiling
If you are under a unix like operating system:
javac -cp '.:org.example.jar' mysource.java
If you are under windows:
javac -cp .;org.example.jar mysource.java
After this, you obtain the bytecode file mysource.class
Now you can run this :
If you are under a unix like operating system:
java -cp '.:org.example.jar' mysource
If you are under windows:
java -cp .;org.example.jar mysource
Just define an empty navbar prior to the fixed one, it will create the space needed.
<nav class="navbar navbar-default ">
</nav>
<nav class="navbar navbar-default navbar-fixed-top ">
<div class="container-fluid">
// Your menu code
</div>
</nav>
And if you want to run a second function after the first one finishes, see this stackoverflow answer.
I don't understand why other answers are about relative coordinates change, not absolute like OP asked in title.
$("#Friends").animate( {top:
"-=" + (parseInt($("#Friends").css("top")) - 100) + "px"
} );
window.location
sets the URL of your current window. To open a new window, you need to use window.open
. This should work:
function ToKey(){
var key = document.tokey.key.value.toLowerCase();
if (key == "smk") {
window.open('http://www.smkproduction.eu5.org', '_blank');
} else {
alert("Kodi nuk është valid!");
}
}
DateTime d1 = ...;
DateTime d2 = ...;
Period period = new Period(d1, d2, PeriodType.minutes());
int differenceMinutes = period.getMinutes();
In practice I think this will always give the same result as the answer based on Duration
. For a different time unit than minutes, though, it might be more correct. For example there are 365 days from 2016/2/2 to 2017/2/1, but actually it's less than 1 year and should truncate to 0 years if you use PeriodType.years()
.
In theory the same could happen for minutes because of leap seconds, but Joda doesn't support leap seconds.
GET (multiple parameters):
curl -X GET "http://localhost:3000/action?result1=gh&result2=ghk"
or
curl --request GET "http://localhost:3000/action?result1=gh&result2=ghk"
or
curl "http://localhost:3000/action?result1=gh&result2=ghk"
or
curl -i -H "Application/json" -H "Content-type: application/json" "http://localhost:3000/action?result1=gh&result2=ghk"
if you run something like this in a thread and save the ffmpeg_time property in a property of a method so you can access it, it would work very nice I get outputs like this: output be like if you use threading in tkinter
input = 'path/input_file.mp4'
output = 'path/input_file.mp4'
command = "ffmpeg -y -v quiet -stats -i \"" + str(input) + "\" -metadata title=\"@alaa_sanatisharif\" -preset ultrafast -vcodec copy -r 50 -vsync 1 -async 1 \"" + output + "\""
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, shell=True)
for line in self.process.stdout:
reg = re.search('\d\d:\d\d:\d\d', line)
ffmpeg_time = reg.group(0) if reg else ''
print(ffmpeg_time)
I found that the following worked for me. These steps come from BTD's YouTube video, Managing Zipfile's in R:
zip.url <- "url_address.zip"
dir <- getwd()
zip.file <- "file_name.zip"
zip.combine <- as.character(paste(dir, zip.file, sep = "/"))
download.file(zip.url, destfile = zip.combine)
unzip(zip.file)
<input type="number" string-to-number ng-model="num1">
<input type="number" string-to-number ng-model="num2">
Total: {{num1 + num2}}
and in js :
parseInt($scope.num1) + parseInt($scope.num2)
Use numpy.dot
or a.dot(b)
. See the documentation here.
>>> a = np.array([[ 5, 1 ,3],
[ 1, 1 ,1],
[ 1, 2 ,1]])
>>> b = np.array([1, 2, 3])
>>> print a.dot(b)
array([16, 6, 8])
This occurs because numpy arrays are not matrices, and the standard operations *, +, -, /
work element-wise on arrays. Instead, you could try using numpy.matrix
, and *
will be treated like matrix multiplication.
Also know there are other options:
As noted below, if using python3.5+ the @
operator works as you'd expect:
>>> print(a @ b)
array([16, 6, 8])
If you want overkill, you can use numpy.einsum
. The documentation will give you a flavor for how it works, but honestly, I didn't fully understand how to use it until reading this answer and just playing around with it on my own.
>>> np.einsum('ji,i->j', a, b)
array([16, 6, 8])
As of mid 2016 (numpy 1.10.1), you can try the experimental numpy.matmul
, which works like numpy.dot
with two major exceptions: no scalar multiplication but it works with stacks of matrices.
>>> np.matmul(a, b)
array([16, 6, 8])
numpy.inner
functions the same way as numpy.dot
for matrix-vector multiplication but behaves differently for matrix-matrix and tensor multiplication (see Wikipedia regarding the differences between the inner product and dot product in general or see this SO answer regarding numpy's implementations).
>>> np.inner(a, b)
array([16, 6, 8])
# Beware using for matrix-matrix multiplication though!
>>> b = a.T
>>> np.dot(a, b)
array([[35, 9, 10],
[ 9, 3, 4],
[10, 4, 6]])
>>> np.inner(a, b)
array([[29, 12, 19],
[ 7, 4, 5],
[ 8, 5, 6]])
If you have tensors (arrays of dimension greater than or equal to one), you can use numpy.tensordot
with the optional argument axes=1
:
>>> np.tensordot(a, b, axes=1)
array([16, 6, 8])
Don't use numpy.vdot
if you have a matrix of complex numbers, as the matrix will be flattened to a 1D array, then it will try to find the complex conjugate dot product between your flattened matrix and vector (which will fail due to a size mismatch n*m
vs n
).
1) This works without imports in Python 2:
>>>
>>> 'Some text'.encode('base64')
'U29tZSB0ZXh0\n'
>>>
>>> 'U29tZSB0ZXh0\n'.decode('base64')
'Some text'
>>>
>>> 'U29tZSB0ZXh0'.decode('base64')
'Some text'
>>>
(although this doesn't work in Python3 )
2) In Python 3 you'd have to import base64 and do base64.b64decode('...') - will work in Python 2 too.
In addition to @csgillespie's answer, segments
is also vectorised to help with this sort of thing:
plot (x, y, ylim=c(0,6))
segments(x,y-sd,x,y+sd)
epsilon <- 0.02
segments(x-epsilon,y-sd,x+epsilon,y-sd)
segments(x-epsilon,y+sd,x+epsilon,y+sd)
Only Files
Get-ChildItem D:\ -Recurse -File | Measure-Object | %{$_.Count}
Only Folders
Get-ChildItem D:\ -Recurse -Directory | Measure-Object | %{$_.Count}
Both
Get-ChildItem D:\ -Recurse | Measure-Object | %{$_.Count}
If you want to get request path (more info):
echo parse_url($_SERVER["REQUEST_URI"])['path']
If you want to remove the query and (and maybe fragment also):
function strposa($haystack, $needles=array(), $offset=0) {
$chr = array();
foreach($needles as $needle) {
$res = strpos($haystack, $needle, $offset);
if ($res !== false) $chr[$needle] = $res;
}
if(empty($chr)) return false;
return min($chr);
}
$i = strposa($_SERVER["REQUEST_URI"], ['#', '?']);
echo strrpos($_SERVER["REQUEST_URI"], 0, $i);
Download from Instant Client for Microsoft Windows (x64) and extract the files below to "c:\oracle":
instantclient-basic-windows.x64-12.1.0.2.0.zip
instantclient-sqlplus-windows.x64-12.1.0.2.0.zip
instantclient-sdk-windows.x64-12.1.0.2.0.zip This will create the following folder "C:\Oracle\instantclient_12_1".
Finally, add the "C:\Oracle\instantclient_12_1" folder to the PATH enviroment variable, placing it on the leftmost place.
Then Restart your server.
Give a class .border-lb
and give this CSS
.border-lb {border: 1px solid #ccc; border-width: 0 0 1px 1px;}
And the HTML
<table width="770">
<tr>
<td class="border-lb">picture (border only to the left and bottom ) </td>
<td>text</td>
</tr>
<tr>
<td>text</td>
<td class="border-lb">picture (border only to the left and bottom) </td>
</tr>
</table>
If the application you are generating the scripts from is a .NET application, you may want to look into using SMO (Sql Management Objects). Reference this SQL Team link on how to use SMO to script objects.
It sounds like you want to place marks in the file.
mx places a mark named x under the cursor
y'x yanks everything between the cursor's current position and the line containing mark x.
You can use 'x to simply move the cursor to the line with your mark.
You can use `x (a back-tick) to move to the exact location of the mark.
One thing I do all the time is yank everything between the cursor and mark x into the clipboard.
You can do that like this:
"+y'x
NOTE: In some environments the clipboard buffer is represented by a *
in stead of a +
.
Similar questions with some good answers:
That is because you are not fully qualifying your cells object. Try this
With Worksheets("SheetName")
.Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With
Notice the DOT before Cells?
Addition for:
++ A mistake that’s often made when approaching REST is to think of it as “web services with URLs”—to think of REST as another remote procedure call (RPC) mechanism, like SOAP, but invoked through plain HTTP URLs and without SOAP’s hefty XML namespaces.
++ On the contrary, REST has little to do with RPC. Whereas RPC is service oriented and focused on actions and verbs, REST is resource oriented, emphasizing the things and nouns that comprise an application.
To detect endianness at run time, you have to be able to refer to memory. If you stick to standard C, declarating a variable in memory requires a statement, but returning a value requires an expression. I don't know how to do this in a single macro—this is why gcc has extensions :-)
If you're willing to have a .h file, you can define
static uint32_t endianness = 0xdeadbeef;
enum endianness { BIG, LITTLE };
#define ENDIANNESS ( *(const char *)&endianness == 0xef ? LITTLE \
: *(const char *)&endianness == 0xde ? BIG \
: assert(0))
and then you can use the ENDIANNESS
macro as you will.
You don't need to. Just slap it on there as many times as you want and as often as you want. MDN explains identical event listeners:
If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded. They do not cause the EventListener to be called twice, and they do not need to be removed manually with the
removeEventListener
method.
If you want to store these time in a database or send it over the server...best is to use Unix timestamps. Here's a little snippet to get that:
+ (NSTimeInterval)getUTCFormateDate{
NSDateComponents *comps = [[NSCalendar currentCalendar]
components:NSDayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit
fromDate:[NSDate date]];
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:[[NSTimeZone systemTimeZone] secondsFromGMT]];
return [[[NSCalendar currentCalendar] dateFromComponents:comps] timeIntervalSince1970];
}
That your billing is enabled
That your website has been added to Google Console
That your website is added to the referrers in your app.
(do a wildcard for both www and none www)
http://www.example.com/* and http://example.com/*
That Javascript Maps is enabled and you are using the correct credentials
That the website has been added to your DNS to enable your Google Console above.
Smile after it works!
No need for pipes, xargs, exec, or anything:
find . -name .svn -delete
Edit: Just kidding, evidently -delete
calls unlinkat()
under the hood, so it behaves like unlink
or rmdir
and will refuse to operate on directories containing files.
Or for fun you could use some LINQ extension goodness:
var dictionary = new Dictionary<string, int> { { "c", 3 }, { "a", 1 }, { "b", 2 } };
dictionary.OrderBy(x => x.Value)
.ForEach(x => Console.WriteLine("{0}={1}", x.Key,x.Value));
Imports Newtonsoft.Json.Linq
Dim json As JObject = JObject.Parse(Me.TextBox1.Text)
MsgBox(json.SelectToken("Venue").SelectToken("ID"))
Well, I guess if you need to remove an element you will make a copy of the array despising the element to be excluded.
// inserting some items
void* element_2_remove = getElement2BRemove();
for (int i = 0; i < vector->size; i++){
if(vector[i]!=element_2_remove) copy2TempVector(vector[i]);
}
free(vector->items);
free(vector);
fillFromTempVector(vector);
//
Assume that getElement2BRemove()
, copy2TempVector( void* ...)
and fillFromTempVector(...)
are auxiliary methods to handle the temp vector.
Use the S3FileSystem.rm
function in s3fs
.
You can delete a single file or several at once:
import s3fs
file_system = s3fs.S3FileSystem()
file_system.rm('s3://my-bucket/foo.txt') # single file
files = ['s3://my-bucket/bar.txt', 's3://my-bucket/baz.txt']
file_system.rm(files) # several files
As addition to the answers above:
If you would like to delete those files
find $dir -size 0 -type f -delete
I think it would be better if you use the method query from SQLiteDatabase class instead of the whole SQL string, which would be:
Cursor cursor = sqLiteDatabase.query(TABLE, allColluns, null, null, null, null, ID +" DESC", "1");
The last two parameters are ORDER BY and LIMIT.
You can see more at: http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
OK, so looking at Comparison of file systems if you only care about the main players file systems:
NUL
, \
, /
, :
, *
, "
, <
, >
, |
. Also, no space character at the start or end, and no period at the end.:
or /
NUL
or /
so any byte except NUL
, \
, /
, :
, *
, "
, <
, >
, |
and you can't have files/folders call .
or ..
and no control characters (of course).
I tried the steps here:
http://jyotirbhandari.blogspot.com/2011/09/java-error-invalidalgorithmparameterexc.html
And, that fixed the issue. I made some minor tweaks - I set the two parameters using System.getProperty...
Floating Point Exception happens because of an unexpected infinity or NaN. You can track that using gdb, which allows you to see what is going on inside your C program while it runs. For more details: https://www.cs.swarthmore.edu/~newhall/unixhelp/howto_gdb.php
In a nutshell, these commands might be useful...
gcc -g myprog.c
gdb a.out
gdb core a.out
ddd a.out
DECLARE @variable VARCHAR(100) = 'LD-23DSP-1430';
WITH Split
AS ( SELECT @variable AS list ,
charone = LEFT(@variable, 1) ,
R = RIGHT(@variable, LEN(@variable) - 1) ,
'A' AS MasterOne
UNION ALL
SELECT Split.list ,
LEFT(Split.R, 1) ,
R = RIGHT(split.R, LEN(Split.R) - 1) ,
'B' AS MasterOne
FROM Split
WHERE LEN(Split.R) > 0
)
SELECT *
FROM Split
OPTION ( MAXRECURSION 10000 );
>>> source_list = ('1','a'),('2','b'),('3','c'),('4','d')
>>> list1, list2 = zip(*source_list)
>>> list1
('1', '2', '3', '4')
>>> list2
('a', 'b', 'c', 'd')
Edit: Note that zip(*iterable)
is its own inverse:
>>> list(source_list) == zip(*zip(*source_list))
True
When unpacking into two lists, this becomes:
>>> list1, list2 = zip(*source_list)
>>> list(source_list) == zip(list1, list2)
True
Addition suggested by rocksportrocker.
If you are here because your emulator gives you that Exception, Go to Tools > AVD Manager in your android emulator and Cold boot your Emulator.
Well, you're on the right path, Benno!
There are some tips regarding VBA programming that might help you out.
Use always explicit references to the sheet you want to interact with. Otherwise, Excel may 'assume' your code applies to the active sheet and eventually you'll see it screws your spreadsheet up.
As lionz mentioned, get in touch with the native methods Excel offers. You might use them on most of your tricks.
Explicitly declare your variables... they'll show the list of methods each object offers in VBA. It might save your time digging on the internet.
Now, let's have a draft code...
Remember this code must be within the Excel Sheet object, as explained by lionz. It only applies to Sheet 2, is up to you to adapt it to both Sheet 2 and Sheet 3 in the way you prefer.
Hope it helps!
Private Sub Worksheet_Change(ByVal Target As Range)
Dim oSheet As Excel.Worksheet
'We only want to do something if the changed cell is B6, right?
If Target.Address = "$B$6" Then
'Checks if it's a number...
If IsNumeric(Target.Value) Then
'Let's avoid values out of your bonds, correct?
If Target.Value > 0 And Target.Value < 51 Then
'Let's assign the worksheet we'll show / hide rows to one variable and then
' use only the reference to the variable itself instead of the sheet name.
' It's safer.
'You can alternatively replace 'sheet 2' by 2 (without quotes) which will represent
' the sheet index within the workbook
Set oSheet = ActiveWorkbook.Sheets("Sheet 2")
'We'll unhide before hide, to ensure we hide the correct ones
oSheet.Range("A7:A56").EntireRow.Hidden = False
oSheet.Range("A" & Target.Value + 7 & ":A56").EntireRow.Hidden = True
End If
End If
End If
End Sub
Here is a sample XAML
that will allow TextBox
to accept multiline text and it uses its own scrollbars:
<TextBox
Height="200"
Width="500"
TextWrapping="Wrap"
AcceptsReturn="True"
HorizontalScrollBarVisibility="Disabled"
VerticalScrollBarVisibility="Auto"/>
This just removes the highlight
class from everything that has the edgetoedge
class:
$(".edgetoedge").removeClass("highlight");
I think you want this:
$(".edgetoedge .highlight").removeClass("highlight");
The .edgetoedge .highlight
selector will choose everything that is a child of something with the edgetoedge
class and has the highlight
class.
In case setting -Xmx4096m -XX:MaxHeapSize=256m
(and etc.. mentioned in above answers) doest work, then do this manually:
Step 1 : Start Android studio and close any open project (File > Close Project).
Step 2 : On Welcome window, Go to Configure > Settings.
Step 3 : Go to Build, Execution, Deployment > Compiler
Step 4 : Change Build process heap size (Mbytes) to 1024 and Additional build process to VM Options to -Xmx512m.
Step 5 : Close or Restart Android Studio.
C++11 standard on jumping over some initializations
JohannesD gave an explanation, now for the standards.
The C++11 N3337 standard draft 6.7 "Declaration statement" says:
3 It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps (87) from a point where a variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has scalar type, class type with a trivial default constructor and a trivial destructor, a cv-qualified version of one of these types, or an array of one of the preceding types and is declared without an initializer (8.5).
87) The transfer from the condition of a switch statement to a case label is considered a jump in this respect.
[ Example:
void f() { // ... goto lx; // ill-formed: jump into scope of a // ... ly: X a = 1; // ... lx: goto ly; // OK, jump implies destructor // call for a followed by construction // again immediately following label ly }
— end example ]
As of GCC 5.2, the error message now says:
crosses initialization of
C
C allows it: c99 goto past initialization
The C99 N1256 standard draft Annex I "Common warnings" says:
2 A block with initialization of an object that has automatic storage duration is jumped into
Update for mid 2016:
The things are changing so fast that if it's late 2017 this answer might not be up to date anymore!
Beginners can quickly get lost in choice of build tools and workflows, but what's most up to date in 2016 is not using Bower, Grunt or Gulp at all! With help of Webpack you can do everything directly in NPM!
Google "npm as build tool" result: https://medium.com/@dabit3/introduction-to-using-npm-as-a-build-tool-b41076f488b0#.c33e74tsa
Don't get me wrong people use other workflows and I still use GULP in my legacy project(but slowly moving out of it), but this is how it's done in the best companies and developers working in this workflow make a LOT of money!
Look at this template it's a very up-to-date setup consisting of a mixture of the best and the latest technologies: https://github.com/coryhouse/react-slingshot
Your questions:
When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json
Everything belongs in package.json now
Dependencies required for build are in "devDependencies" i.e. npm install require-dir --save-dev
(--save-dev updates your package.json by adding an entry to devDependencies)
npm install lodash --save
(--save updates your package.json by adding an entry to dependencies)If that is the case, when should I ever install packages explicitly like that without adding them to the file that manages dependencies (apart from installing command line tools globally)?
Always. Just because of comfort. When you add a flag (--save-dev
or --save
) the file that manages deps (package.json) gets updated automatically. Don't waste time by editing dependencies in it manually. Shortcut for npm install --save-dev package-name
is npm i -D package-name
and shortcut for npm install --save package-name
is npm i -S package-name
Note also that vertical-align:top;
is often necessary for correct table cell appearance.
There's an architecture mismatch. Your JDBC Driver and your JDK should be of the same architecture. If your using 32bit Driver and your JDK is 64bits, you would get that error.
See this
Fix : Depends on your architecture.
You will need 64-bit drivers if your Java is 64-bit.
Two of them always produce the same answer:
COUNT(*)
counts the number of rowsCOUNT(1)
also counts the number of rowsAssuming the pk
is a primary key and that no nulls are allowed in the values, then
COUNT(pk)
also counts the number of rowsHowever, if pk
is not constrained to be not null, then it produces a different answer:
COUNT(possibly_null)
counts the number of rows with non-null values in the column possibly_null
.
COUNT(DISTINCT pk)
also counts the number of rows (because a primary key does not allow duplicates).
COUNT(DISTINCT possibly_null_or_dup)
counts the number of distinct non-null values in the column possibly_null_or_dup
.
COUNT(DISTINCT possibly_duplicated)
counts the number of distinct (necessarily non-null) values in the column possibly_duplicated
when that has the NOT NULL
clause on it.
Normally, I write COUNT(*)
; it is the original recommended notation for SQL. Similarly, with the EXISTS
clause, I normally write WHERE EXISTS(SELECT * FROM ...)
because that was the original recommend notation. There should be no benefit to the alternatives; the optimizer should see through the more obscure notations.
For some further information on how to determine the processing time, and a comparison of a few methods (some mentioned already in the answers of this post) - specifically, the difference between:
start = time.time()
versus the now obsolete (as of 3.3, time.clock() is deprecated)
start = time.clock()
see this other article on Stackoverflow here:
Python - time.clock() vs. time.time() - accuracy?
If nothing else, this will work good:
start = time.time()
... do something
elapsed = (time.time() - start)
I achieved this with Swift by the following code:
class Dialog: UIView {
@IBOutlet var view:UIView!
override init(frame: CGRect) {
super.init(frame: frame)
self.frame = UIScreen.mainScreen().bounds
NSBundle.mainBundle().loadNibNamed("Dialog", owner: self, options: nil)
self.view.frame = UIScreen.mainScreen().bounds
self.addSubview(self.view)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
Don't forget to connect your XIB view outlet to view outlet defined in swift. You can also set First Responder to your custom class name to start connecting any additional outlets.
Hope this helps!
Slightly more condensed than gbn's:
Assuming CourseId
is non-zero
CAST (COALESCE(FC.CourseId, 0) AS Bit)
COALESCE
is like an ISNULL()
, but returns the first non-Null.
A Non-Zero CourseId
will get type-cast to a 1, while a null CourseId
will cause COALESCE to return the next value, 0
You don't have to use atan2 to calculate the angle between two vectors. If you just want the quickest way, you can use dot(v1, v2)=|v1|*|v2|*cos A
to get
A = Math.acos( dot(v1, v2)/(v1.length()*v2.length()) );
import pygame, sys
from pygame.locals import *
def main():
pygame.init()
DISPLAY=pygame.display.set_mode((500,400),0,32)
WHITE=(255,255,255)
BLUE=(0,0,255)
DISPLAY.fill(WHITE)
pygame.draw.rect(DISPLAY,BLUE,(200,150,100,50))
while True:
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
main()
This creates a simple window 500 pixels by 400 pixels that is white. Within the window will be a blue rectangle. You need to use the pygame.draw.rect
to go about this, and you add the DISPLAY
constant to add it to the screen, the variable blue to make it blue (blue is a tuple that values which equate to blue in the RGB values and it's coordinates.
Look up pygame.org for more info
Compared to the other parser libraries lxml
is extremely fast:
And with cssselect
it’s quite easy to use for scraping HTML pages too:
from lxml.html import parse
doc = parse('http://www.google.com').getroot()
for div in doc.cssselect('a'):
print '%s: %s' % (div.text_content(), div.get('href'))
Here is a way to handle duplicate tuple "keys":
# An example
l = [('A', 1), ('B', 2), ('C', 3), ('A', 5), ('D', 0), ('D', 9)]
# A solution
d = dict()
[d [t [0]].append(t [1]) if t [0] in list(d.keys())
else d.update({t [0]: [t [1]]}) for t in l]
d
OUTPUT: {'A': [1, 5], 'B': [2], 'C': [3], 'D': [0, 9]}
This is the solution I use. It has more lines but it will only create the datepicker once.
$('#txtSearch').datepicker({
constrainInput:false,
beforeShow: function(){
var t = $('#ddlSearchType').val();
if( ['Required Date', 'Submitted Date'].indexOf(t) ) {
$('#txtSearch').prop('readonly', false);
return false;
}
else $('#txtSearch').prop('readonly', true);
}
});
The datepicker will not show unless the value of ddlSearchType is either "Required Date" or "Submitted Date"
Best way to divide a div vertically --
#parent {
margin: 0;
width: 100%;
}
.left {
float: left;
width: 60%;
}
.right {
overflow: hidden;
width: 40%;
}
Corrupted cert and/or key files
For me it was just corrupted files. I copied the contents from GitHub PullRequest webpage and I guess I added an extra space somewhere or whatever... once I grabbed the raw thing and replaced the file, it worked.
As far as I can tell, this was caused by a conflict with the version of Python 3.7 that was recently added into the Windows Store. It looks like this added two "stubs" called python.exe and python3.exe into the %USERPROFILE%\AppData\Local\Microsoft\WindowsApps
folder, and in my case, this was inserted before my existing Python executable's entry in the PATH
.
Moving this entry below the correct Python folder (partially) corrected the issue.
The second part of correcting it is to type manage app execution aliases
into the Windows search prompt and disable the store versions of Python altogether.
It's possible that you'll only need to do the second part, but on my system I made both changes and everything is back to normal now.
A simple way without any libraries or sets
def mcount(l):
n = [] #To store count of each elements
for x in l:
count = 0
for i in range(len(l)):
if x == l[i]:
count+=1
n.append(count)
a = max(n) #largest in counts list
for i in range(len(n)):
if n[i] == a:
return(l[i],a) #element,frequency
return #if something goes wrong
You can dynamically add elements to an array using Collection Frameworks in JAVA. collection Framework doesn't work on primitive data types.
This Collection framework will be available in "java.util.*" package
For example if you use ArrayList,
Create an object to it and then add number of elements (any type like String, Integer ...etc)
ArrayList a = new ArrayList();
a.add("suman");
a.add(new Integer(3));
a.add("gurram");
Now you were added 3 elements to an array.
if you want to remove any of added elements
a.remove("suman");
again if you want to add any element
a.add("Gurram");
So the array size is incresing / decreasing dynamically..
Use subprocess.Popen:
import subprocess
process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate()
print(out)
Note that communicate blocks until the process terminates. You could use process.stdout.readline() if you need the output before it terminates. For more information see the documentation.
Through discourse it's clear that the problem lies in using VS2010 to write the query, as it uses the canonical CONCAT()
function which is limited to 2 parameters. There's probably a way to change that, but I'm not aware of it.
An alternative:
SELECT '1'+'2'+'3'
This approach requires non-string values to be cast/converted to strings, as well as NULL
handling via ISNULL()
or COALESCE()
:
SELECT ISNULL(CAST(Col1 AS VARCHAR(50)),'')
+ COALESCE(CONVERT(VARCHAR(50),Col2),'')