While I know the intent behind strncpy
, it is not really a good function. Avoid both. Raymond Chen explains.
Personally, my conclusion is simply to avoid
strncpy
and all its friends if you are dealing with null-terminated strings. Despite the "str" in the name, these functions do not produce null-terminated strings. They convert a null-terminated string into a raw character buffer. Using them where a null-terminated string is expected as the second buffer is plain wrong. Not only do you fail to get proper null termination if the source is too long, but if the source is short you get unnecessary null padding.
See also Why is strncpy insecure?
Will result always be the floor of the division? What is the defined behavior?
Not quite. It rounds toward 0, rather than flooring.
6.5.5 Multiplicative operators
6 When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded.88) If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.
and the corresponding footnote:
- This is often called ‘‘truncation toward zero’’.
Of course two points to note are:
3 The usual arithmetic conversions are performed on the operands.
and:
5 The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.
[Note: Emphasis mine]
float
and double
don't store decimal places. They store binary places: float
is (assuming IEEE 754) 24 significant bits (7.22 decimal digits) and double is 53 significant bits (15.95 significant digits).
Converting from double
to float
will give you the closest possible float
, so rounding won't help you. Goining the other way may give you "noise" digits in the decimal representation.
#include <stdio.h>
int main(void) {
double orig = 12345.67;
float f = (float) orig;
printf("%.17g\n", f); // prints 12345.669921875
return 0;
}
To get a double
approximation to the nice decimal value you intended, you can write something like:
double round_to_decimal(float f) {
char buf[42];
sprintf(buf, "%.7g", f); // round to 7 decimal digits
return atof(buf);
}
To update, you can install n
sudo npm install -g n
Then just :
sudo n latest
or a specific version
sudo n 8.9.0
Data table to List
#region "getobject filled object with property reconized"
public List<T> ConvertTo<T>(DataTable datatable) where T : new()
{
List<T> Temp = new List<T>();
try
{
List<string> columnsNames = new List<string>();
foreach (DataColumn DataColumn in datatable.Columns)
columnsNames.Add(DataColumn.ColumnName);
Temp = datatable.AsEnumerable().ToList().ConvertAll<T>(row => getObject<T>(row, columnsNames));
return Temp;
}
catch
{
return Temp;
}
}
public T getObject<T>(DataRow row, List<string> columnsName) where T : new()
{
T obj = new T();
try
{
string columnname = "";
string value = "";
PropertyInfo[] Properties;
Properties = typeof(T).GetProperties();
foreach (PropertyInfo objProperty in Properties)
{
columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower());
if (!string.IsNullOrEmpty(columnname))
{
value = row[columnname].ToString();
if (!string.IsNullOrEmpty(value))
{
if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null)
{
value = row[columnname].ToString().Replace("$", "").Replace(",", "");
objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null);
}
else
{
value = row[columnname].ToString().Replace("%", "");
objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);
}
}
}
}
return obj;
}
catch
{
return obj;
}
}
#endregion
IEnumerable collection To Datatable
#region "New DataTable"
public DataTable ToDataTable<T>(IEnumerable<T> collection)
{
DataTable newDataTable = new DataTable();
Type impliedType = typeof(T);
PropertyInfo[] _propInfo = impliedType.GetProperties();
foreach (PropertyInfo pi in _propInfo)
newDataTable.Columns.Add(pi.Name, pi.PropertyType);
foreach (T item in collection)
{
DataRow newDataRow = newDataTable.NewRow();
newDataRow.BeginEdit();
foreach (PropertyInfo pi in _propInfo)
newDataRow[pi.Name] = pi.GetValue(item, null);
newDataRow.EndEdit();
newDataTable.Rows.Add(newDataRow);
}
return newDataTable;
}
This works fine for me:
while True:
answer = input('Do you want to continue?:')
if answer.lower().startswith("y"):
print("ok, carry on then")
elif answer.lower().startswith("n"):
print("sayonara, Robocop")
exit()
edit: use input
in python 3.2 instead of raw_input
While all of the answers here are a really good explanation of what cors is but the direct answer to your question would be because of the following differences postman and browser.
Browser: Sends OPTIONS
call to check the server type and getting the headers before sending any new request to the API endpoint. Where it checks for Access-Control-Allow-Origin
. Taking this into account Access-Control-Allow-Origin
header just specifies which all CROSS ORIGINS are allowed, although by default browser will only allow the same origin.
Postman: Sends direct GET
, POST
, PUT
, DELETE
etc. request without checking what type of server is and getting the header Access-Control-Allow-Origin
by using OPTIONS
call to the server.
I was able to read a 4GB log file in about 50 seconds with the following. You may be able to make it faster by loading it as a C# assembly dynamically using PowerShell.
[System.IO.StreamReader]$sr = [System.IO.File]::Open($file, [System.IO.FileMode]::Open)
while (-not $sr.EndOfStream){
$line = $sr.ReadLine()
}
$sr.Close()
Besides what other said, a common problem is to declare the types of the same function that is overloaded. Typical case is EventEmitter on() method which will accept multiple kind of listeners. Similar could happen When working with redux actions - and there you use the action type as literal to mark the overloading, In case of EventEmitters, you use the event name literal type:
interface MyEmitter extends EventEmitter {
on(name:'click', l: ClickListener):void
on(name:'move', l: MoveListener):void
on(name:'die', l: DieListener):void
//and a generic one
on(name:string, l:(...a:any[])=>any):void
}
type ClickListener = (e:ClickEvent)=>void
type MoveListener = (e:MoveEvent)=>void
... etc
// will type check the correct listener when writing something like:
myEmitter.on('click', e=>...<--- autocompletion
@sdbrain's answer in Swift 3:
let url = URL.init(fileURLWithPath: Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "www")!)
webView.loadRequest(NSURLRequest.init(url: url) as URLRequest)
I've been using svg filters to achieve similar effects for sprites
<svg id="gray_calendar" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 48 48 48">
<filter id="greyscale">
<feColorMatrix type="saturate" values="0"/>
</filter>
<image width="48" height="10224" xlink:href="tango48i.png" filter="url(#greyscale)"/>
</svg>
<feGaussianBlur stdDeviation="10"/>
example.<image ...>
tag to apply it to any image or even use multiple images.For an excellent resource on how bash invocation works, what dotfiles do what, and how you should use/configure them, read this:
This error is really confusing. In my case I was missing a default empty parameter less constructor for my fragment. After adding empty constructor in my fragment the problem resolved.
you can use if statement like below
select CONCAT(if(affiliate_name is null ,'',affiliate_name),'- ',if(model is null ,'',affiliate_name)) as model from devices
By using pandas we can read excel easily.
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
DataF=pd.read_excel("Test.xlsx",sheet_name='Sheet1')
print("Column headings:")
print(DataF.columns)
Test at :https://repl.it Reference: https://pythonspot.com/read-excel-with-pandas/
Button click event only.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#btnext").click(function () {
window.open("HTMLPage.htm", "PopupWindow", "width=600,height=600,scrollbars=yes,resizable=no");
});
});
</script>
Here is the max value and the indexes it appears at:
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50, 35, 41, 49, 37, 19, 40, 41, 31]
>>> for i, x in enumerate(a):
... d[x].append(i)
...
>>> k = max(d.keys())
>>> print k, d[k]
55 [9, 12]
Later: for the satisfaction of @SilentGhost
>>> from itertools import takewhile
>>> import heapq
>>>
>>> def popper(heap):
... while heap:
... yield heapq.heappop(heap)
...
>>> a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50, 35, 41, 49, 37, 19, 40, 41, 31]
>>> h = [(-x, i) for i, x in enumerate(a)]
>>> heapq.heapify(h)
>>>
>>> largest = heapq.heappop(h)
>>> indexes = [largest[1]] + [x[1] for x in takewhile(lambda large: large[0] == largest[0], popper(h))]
>>> print -largest[0], indexes
55 [9, 12]
Try: http://www.mattweber.org/2007/03/04/python-script-renamepy/
I like to have my music, movie, and picture files named a certain way. When I download files from the internet, they usually don’t follow my naming convention. I found myself manually renaming each file to fit my style. This got old realy fast, so I decided to write a program to do it for me.
This program can convert the filename to all lowercase, replace strings in the filename with whatever you want, and trim any number of characters from the front or back of the filename.
The program's source code is also available.
Insert an item in the beginning of an associative array with string/custom key
<?php
$array = ['keyOne'=>'valueOne', 'keyTwo'=>'valueTwo'];
$array = array_reverse($array);
$array['newKey'] = 'newValue';
$array = array_reverse($array);
RESULT
[
'newKey' => 'newValue',
'keyOne' => 'valueOne',
'keyTwo' => 'valueTwo'
]
I open-sourced a C# Http form parser here.
This is slightly more flexible than the other one mentioned which is on CodePlex, since you can use it for both Multipart and non-Multipart form-data
, and also it gives you other form parameters formatted in a Dictionary
object.
This can be used as follows:
non-multipart
public void Login(Stream stream)
{
string username = null;
string password = null;
HttpContentParser parser = new HttpContentParser(stream);
if (parser.Success)
{
username = HttpUtility.UrlDecode(parser.Parameters["username"]);
password = HttpUtility.UrlDecode(parser.Parameters["password"]);
}
}
multipart
public void Upload(Stream stream)
{
HttpMultipartParser parser = new HttpMultipartParser(stream, "image");
if (parser.Success)
{
string user = HttpUtility.UrlDecode(parser.Parameters["user"]);
string title = HttpUtility.UrlDecode(parser.Parameters["title"]);
// Save the file somewhere
File.WriteAllBytes(FILE_PATH + title + FILE_EXT, parser.FileContents);
}
}
Put your JTable
inside a JScrollPane
. Try this:
add(new JScrollPane(scrTbl));
Shorter way and I think easier, without creating unnecessary strings.
const findNthOccurence = (string, nth, char) => {
let index = 0
for (let i = 0; i < nth; i += 1) {
if (index !== -1) index = string.indexOf(char, index + 1)
}
return index
}
You need to load your JNI library.
System.loadLibrary loads the DLL from the JVM path (JDK bin path).
If you want to load an explicit file with a path, use System.load()
See also: Difference between System.load() and System.loadLibrary in Java
var time = moment().toDate(); // This will return a copy of the Date that the moment uses
time.setHours(0);
time.setMinutes(0);
time.setSeconds(0);
time.setMilliseconds(0);
If you only send the parameters to a URL, you can do it this way:
downloadfile(runname: string, type: string): string {
return window.location.href = `${this.files_api + this.title +"/"+ runname + "/?file="+ type}`;
}
in the service that receives the parameters
You can use any of these two:
return redirect()->back()->withInput(Input::all())->with('message', 'Some message');
Or,
return redirect('url_goes_here')->withInput(Input::all())->with('message', 'Some message');
Unfortunately, ggplot2 does not offer a way to do this (easily) without transforming your data into long format. You can try to fight it but it will just be easier to do the data transformation. Here all the methods, including melt
from reshape2, gather
from tidyr, and pivot_longer
from tidyr: Reshaping data.frame from wide to long format
Here's a simple example using pivot_longer
:
> df <- data.frame(time = 1:5, a = 1:5, b = 3:7)
> df
time a b
1 1 1 3
2 2 2 4
3 3 3 5
4 4 4 6
5 5 5 7
> df_wide <- df %>% pivot_longer(c(a, b), names_to = "colname", values_to = "val")
> df_wide
# A tibble: 10 x 3
time colname val
<int> <chr> <int>
1 1 a 1
2 1 b 3
3 2 a 2
4 2 b 4
5 3 a 3
6 3 b 5
7 4 a 4
8 4 b 6
9 5 a 5
10 5 b 7
As you can see, pivot_longer
puts the selected column names in whatever is specified by names_to
(default "name"), and puts the long values into whatever is specified by values_to
(default "value"). If I'm ok with the default names, I can use use df %>% pivot_longer(c("a", "b"))
.
Now you can plot as normal, ex.
ggplot(df_wide, aes(x = time, y = val, color = colname)) + geom_line()
On the contrary, I do think working with list
makes it easy to automate such things.
Here is one solution (I stored your four dataframes in folder temp/
).
filenames <- list.files("temp", pattern="*.csv", full.names=TRUE)
ldf <- lapply(filenames, read.csv)
res <- lapply(ldf, summary)
names(res) <- substr(filenames, 6, 30)
It is important to store the full path for your files (as I did with full.names
), otherwise you have to paste the working directory, e.g.
filenames <- list.files("temp", pattern="*.csv")
paste("temp", filenames, sep="/")
will work too. Note that I used substr
to extract file names while discarding full path.
You can access your summary tables as follows:
> res$`df4.csv`
A B
Min. :0.00 Min. : 1.00
1st Qu.:1.25 1st Qu.: 2.25
Median :3.00 Median : 6.00
Mean :3.50 Mean : 7.00
3rd Qu.:5.50 3rd Qu.:10.50
Max. :8.00 Max. :16.00
If you really want to get individual summary tables, you can extract them afterwards. E.g.,
for (i in 1:length(res))
assign(paste(paste("df", i, sep=""), "summary", sep="."), res[[i]])
You're performing an integer division. Append a .0
to the number literals:
per=float(tota)*(100.0/500.0)
In Python 2.7 the division 100/500==0
.
As pointed out by @unwind, the float()
call is superfluous since a multiplication/division by a float returns a float:
per= tota*100.0 / 500
Check your remote with git remote -v Something like ssh:///gituser@myhost:/git/dev.git
is wrong because of the triple /// slash
try this:
split(das, cut(das$anim, 3))
if you want to split based on the value of wt
, then
library(Hmisc) # cut2
split(das, cut2(das$wt, g=3))
anyway, you can do that by combining cut
, cut2
and split
.
UPDATED
if you want a group index as an additional column, then
das$group <- cut(das$anim, 3)
if the column should be index like 1, 2, ..., then
das$group <- as.numeric(cut(das$anim, 3))
UPDATED AGAIN
try this:
> das$wt2 <- as.numeric(cut2(das$wt, g=3))
> das
anim wt wt2
1 1 181.0 1
2 2 179.0 1
3 3 180.5 1
4 4 201.0 2
5 5 201.5 2
6 6 245.0 2
7 7 246.4 3
8 8 189.3 1
9 9 301.0 3
10 10 354.0 3
11 11 369.0 3
12 12 205.0 2
13 13 199.0 1
14 14 394.0 3
15 15 231.3 2
From a lambda, you can't get a reference to anything that isn't final. You need to declare a final wrapper from outside the lamda to hold your variable.
I've added the final 'reference' object as this wrapper.
private TimeZone extractCalendarTimeZoneComponent(Calendar cal,TimeZone calTz) {
final AtomicReference<TimeZone> reference = new AtomicReference<>();
try {
cal.getComponents().getComponents("VTIMEZONE").forEach(component->{
VTimeZone v = (VTimeZone) component;
v.getTimeZoneId();
if(reference.get()==null) {
reference.set(TimeZone.getTimeZone(v.getTimeZoneId().getValue()));
}
});
} catch (Exception e) {
//log.warn("Unable to determine ical timezone", e);
}
return reference.get();
}
Need to login with respective github username
and password
To Clear the username and password in windows
Control Panel\User Accounts\Credential Manager
Edit the windows Credential
Remove the existing user and now go to command prompt write the push command it shows a github pop-up to enter the username
/email
and password
.
Now we able to push the code after switching the user.
If you want many inserts
from rope.base.codeanalyze import ChangeCollector
c = ChangeCollector(code)
c.add_change(5, 5, '<span style="background-color:#339999;">')
c.add_change(10, 10, '</span>')
rend_code = c.get_changed()
This is version problem, install the right dependant version
npm uninstall node-sass
npm install [email protected]
If you are using Kotlin in android then you can create Extension function.
Extension Functions are defined outside of any class - yet they reference the class name and can use this
. In our case we use applicationContext
.
So in Utility class you can define all extension functions.
Utility.kt
fun Context.loadJSONFromAssets(fileName: String): String {
return applicationContext.assets.open(fileName).bufferedReader().use { reader ->
reader.readText()
}
}
MainActivity.kt
You can define private function for load JSON data from assert like this:
lateinit var facilityModelList: ArrayList<FacilityModel>
private fun bindJSONDataInFacilityList() {
facilityModelList = ArrayList<FacilityModel>()
val facilityJsonArray = JSONArray(loadJSONFromAsserts("NDoH_facility_list.json")) // Extension Function call here
for (i in 0 until facilityJsonArray.length()){
val facilityModel = FacilityModel()
val facilityJSONObject = facilityJsonArray.getJSONObject(i)
facilityModel.Facility = facilityJSONObject.getString("Facility")
facilityModel.District = facilityJSONObject.getString("District")
facilityModel.Province = facilityJSONObject.getString("Province")
facilityModel.Subdistrict = facilityJSONObject.getString("Facility")
facilityModel.code = facilityJSONObject.getInt("code")
facilityModel.gps_latitude = facilityJSONObject.getDouble("gps_latitude")
facilityModel.gps_longitude = facilityJSONObject.getDouble("gps_longitude")
facilityModelList.add(facilityModel)
}
}
You have to pass facilityModelList
in your ListView
FacilityModel.kt
class FacilityModel: Serializable {
var District: String = ""
var Facility: String = ""
var Province: String = ""
var Subdistrict: String = ""
var code: Int = 0
var gps_latitude: Double= 0.0
var gps_longitude: Double= 0.0
}
In my case JSON response start with JSONArray
[
{
"code": 875933,
"Province": "Eastern Cape",
"District": "Amathole DM",
"Subdistrict": "Amahlathi LM",
"Facility": "Amabele Clinic",
"gps_latitude": -32.6634,
"gps_longitude": 27.5239
},
{
"code": 455242,
"Province": "Eastern Cape",
"District": "Amathole DM",
"Subdistrict": "Amahlathi LM",
"Facility": "Burnshill Clinic",
"gps_latitude": -32.7686,
"gps_longitude": 27.055
}
]
To find all files modified in the last 24 hours use the one below. The -1 here means changed 1 day or less ago.
find . -mtime -1 -ls
According to the docs, it's preferable to omit the closing tag if it's at the end of the file for the following reason:
If a file is pure PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.
As of May 2018, you can find the full list here: https://developers.facebook.com/docs/reference/opengraph#object-type
apps.saves
An action representing someone saving an app to try later.
article
This object represents an article on a website. It is the preferred type for blog posts and news stories.
book
This object type represents a book or publication. This is an appropriate type for ebooks, as well as traditional paperback or hardback books. Do not use this type to represent magazines
books.author
This object type represents a single author of a book.
books.book
This object type represents a book or publication. This is an appropriate type for ebooks, as well as traditional paperback or hardback books
books.genre
This object type represents the genre of a book or publication.
books.quotes
Returns no data as of April 4, 2018.
An action representing someone quoting from a book.
books.rates
Returns no data as of April 4, 2018.
An action representing someone rating a book.
books.reads
Returns no data as of April 4, 2018.
An action representing someone reading a book.
books.wants_to_read
Returns no data as of April 4, 2018.
An action representing someone wanting to read a book.
business.business
This object type represents a place of business that has a location, operating hours and contact information.
fitness.bikes
Returns no data as of April 4, 2018.
An action representing someone cycling a course.
fitness.course
This object type represents the user's activity contributing to a particular run, walk, or bike course.
fitness.runs
Returns no data as of April 4, 2018.
An action representing someone running a course.
fitness.walks
Returns no data as of April 4, 2018.
An action representing someone walking a course.
game.achievement
This object type represents a specific achievement in a game. An app must be in the 'Games' category in App Dashboard to be able to use this object type. Every achievement has agame:points
value associate with it. This is not related to the points the user has scored in the game, but is a way for the app to indicate the relative importance and scarcity of different achievements: * Each game gets a total of 1,000 points to distribute across its achievements * Each game gets a maximum of 1,000 achievements * Achievements which are scarcer and have higher point values will receive more distribution in Facebook's social channels. For example, achievements which have point values of less than 10 will get almost no distribution. Apps should aim for between 50-100 achievements consisting of a mix of 50 (difficult), 25 (medium), and 10 (easy) point value achievements Read more on how to use achievements in this guide.
games.achieves
An action representing someone reaching a game achievement.
games.celebrate
An action representing someone celebrating a victory in a game.
games.plays
An action representing someone playing a game. Stories for this action will only appear in the activity log.
games.saves
An action representing someone saving a game.
music.album
This object type represents a music album; in other words, an ordered collection of songs from an artist or a collection of artists. An album can comprise multiple discs.
music.listens
Returns no data as of April 4, 2018.
An action representing someone listening to a song, album, radio station, playlist or musician
music.playlist
This object type represents a music playlist, an ordered collection of songs from a collection of artists.
music.playlists
Returns no data as of April 4, 2018.
An action representing someone creating a playlist.
music.radio_station
This object type represents a 'radio' station of a stream of audio. The audio properties should be used to identify the location of the stream itself.
music.song
This object type represents a single song.
news.publishes
An action representing someone publishing a news article.
news.reads
Returns no data as of April 4, 2018.
An action representing someone reading a news article.
og.follows
An action representing someone following a Facebook user
og.likes
An action representing someone liking any object.
pages.saves
An action representing someone saving a place.
place
This object type represents a place - such as a venue, a business, a landmark, or any other location which can be identified by longitude and latitude.
product
This object type represents a product. This includes both virtual and physical products, but it typically represents items that are available in an online store.
product.group
This object type represents a group of product items.
product.item
This object type represents a product item.
profile
This object type represents a person. While appropriate for celebrities, artists, or musicians, this object type can be used for the profile of any individual. Thefb:profile_id
field associates the object with a Facebook user.
restaurant.menu
This object type represents a restaurant's menu. A restaurant can have multiple menus, and each menu has multiple sections.
restaurant.menu_item
This object type represents a single item on a restaurant's menu. Every item belongs within a menu section.
restaurant.menu_section
This object type represents a section in a restaurant's menu. A section contains multiple menu items.
restaurant.restaurant
This object type represents a restaurant at a specific location.
restaurant.visited
An action representing someone visiting a restaurant.
restaurant.wants_to_visit
An action representing someone wanting to visit a restaurant
sellers.rates
An action representing a commerce seller has been given a rating.
video.episode
This object type represents an episode of a TV show and contains references to the actors and other professionals involved in its production. An episode is defined by us as a full-length episode that is part of a series. This type must reference the series this it is part of.
video.movie
This object type represents a movie, and contains references to the actors and other professionals involved in its production. A movie is defined by us as a full-length feature or short film. Do not use this type to represent movie trailers, movie clips, user-generated video content, etc.
video.other
This object type represents a generic video, and contains references to the actors and other professionals involved in its production. For specific types of video content, use thevideo.movie
orvideo.tv_show
object types. This type is for any other type of video content not represented elsewhere (eg. trailers, music videos, clips, news segments etc.)
video.rates
Returns no data as of April 4, 2018.
An action representing someone rating a movie, TV show, episode or another piece of video content.
video.tv_show
This object type represents a TV show, and contains references to the actors and other professionals involved in its production. For individual episodes of a series, use thevideo.episode
object type. A TV show is defined by us as a series or set of episodes that are produced under the same title (eg. a television or online series)
video.wants_to_watch
Returns no data as of April 4, 2018.
An action representing someone wanting to watch video content.
video.watches
Returns no data as of April 4, 2018.
An action representing someone watching video content.
if var == 'stringone' or var == 'stringtwo':
do_something()
or more pythonic,
if var in ['string one', 'string two']:
do_something()
No, arrays/lists can't be passed to SQL Server directly.
The following options are available:
You can also add a polyfil to enable native opacity usage in IE6-8.
https://github.com/bladeSk/internet-explorer-opacity-polyfill
This is a stand alone polyfil that does not require jQuery or other libraries. There are several small caveats it does not operate on in-line styles and for any style sheets that need opacity polyfil'd they must adhere to the same-origin security policy.
Usage is dead simple
<!--[if lte IE 8]>
<script src="jquery.ie-opacity-polyfill.js"></script>
<![endif]-->
<style>
a.transparentLink { opacity: 0.5; }
</style>
<a class="transparentLink" href="#"> foo </a>
include_once('../../../wp-config.php');
global $wpdb;
$password = wp_hash_password("your password");
To update an entity with Entity Framework Core, this is the logical process:
DbContext
classUpdate()
method in DbContext
:
Begins tracking the given entity in the Modified state such that it will be updated in the database when
SaveChanges()
is called.
Update method doesn't save changes in database; instead, it sets states for entries in DbContext instance.
So, We can invoke Update()
method before to save changes in database.
I'll assume some object definitions to answer your question:
Database name is Store
Table name is Product
Product class definition:
public class Product
{
public int? ProductID { get; set; }
public string ProductName { get; set; }
public string Description { get; set; }
public decimal? UnitPrice { get; set; }
}
DbContext class definition:
public class StoreDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Your Connection String");
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>(entity =>
{
// Set key for entity
entity.HasKey(p => p.ProductID);
});
base.OnModelCreating(modelBuilder);
}
}
Logic to update entity:
using (var context = new StoreDbContext())
{
// Retrieve entity by id
// Answer for question #1
var entity = context.Products.FirstOrDefault(item => item.ProductID == id);
// Validate entity is not null
if (entity != null)
{
// Answer for question #2
// Make changes on entity
entity.UnitPrice = 49.99m;
entity.Description = "Collector's edition";
/* If the entry is being tracked, then invoking update API is not needed.
The API only needs to be invoked if the entry was not tracked.
https://www.learnentityframeworkcore.com/dbcontext/modifying-data */
// context.Products.Update(entity);
// Save changes in database
context.SaveChanges();
}
}
This is because you have added a library and given its dependency on a module more than once.
In my case, I had added a library as a module and as a gradle dependency both.
Removing one source of adding library (I removed gradle dependency) solved my problem.
For my console program the answers with tkinter above did not quite work for me because the .destroy() always gave an error,:
can't invoke "event" command: application has been destroyed while executing...
or when using .withdraw() the console window did not get the focus back.
To solve this you also have to call .update() before the .destroy(). Example:
# Python 3
import tkinter
r = tkinter.Tk()
text = r.clipboard_get()
r.withdraw()
r.update()
r.destroy()
The r.withdraw() prevents the frame from showing for a milisecond, and then it will be destroyed giving the focus back to the console.
Try this. It's working for me (Windows 10).
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
#fourcc = cv2.cv.CV_FOURCC(*'DIVX')
#out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
out = cv2.VideoWriter('output.avi', -1, 20.0, (640,480))
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,0)
# write the flipped frame
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
Try the library SimpleDraweeView
<com.facebook.drawee.view.SimpleDraweeView
android:id="@+id/badge_image"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
and now you can simply do:
final Uri uri = Uri.parse(post.getImageUrl());
When app-support wanted to answer ad-hock queries from the production-server using SSMS (that weren't catered for via reporting) I requested they use nolock. That way the 'main' business is not affected.
Position your <div>
absolutely at the bottom and don't forget to give div.A
a position: relative
- http://jsfiddle.net/TTaMx/
.A {
position: relative;
margin: 40px 0;
height: 40px;
width: 200px;
background: #eee;
}
.A:after {
content: " ";
display: block;
background: #c00;
height: 29px;
width: 100%;
position: absolute;
bottom: -29px;
}?
String WHERE_CONDITION = unreadOnly ? SMS_READ_COLUMN + " = 0" : null;
changed by:
String WHERE_CONDITION = unreadOnly ? SMS_READ_COLUMN + " = 0 " : SMS_READ_COLUMN + " = 1 ";
Node* InsertNth(int data, int position)
{
struct Node *n=new struct Node;
n->data=data;
if(position==0)
{// this will also cover insertion at head (if there is no problem with the input)
n->next=head;
head=n;
}
else
{
struct Node *c=new struct Node;
int count=1;
c=head;
while(count!=position)
{
c=c->next;
count++;
}
n->next=c->next;
c->next=n;
}
return ;
}
Since other questions are being redirected to this one which ask about asanyarray
or other array creation routines, it's probably worth having a brief summary of what each of them does.
The differences are mainly about when to return the input unchanged, as opposed to making a new array as a copy.
array
offers a wide variety of options (most of the other functions are thin wrappers around it), including flags to determine when to copy. A full explanation would take just as long as the docs (see Array Creation, but briefly, here are some examples:
Assume a
is an ndarray
, and m
is a matrix
, and they both have a dtype
of float32
:
np.array(a)
and np.array(m)
will copy both, because that's the default behavior.np.array(a, copy=False)
and np.array(m, copy=False)
will copy m
but not a
, because m
is not an ndarray
.np.array(a, copy=False, subok=True)
and np.array(m, copy=False, subok=True)
will copy neither, because m
is a matrix
, which is a subclass of ndarray
.np.array(a, dtype=int, copy=False, subok=True)
will copy both, because the dtype
is not compatible.Most of the other functions are thin wrappers around array
that control when copying happens:
asarray
: The input will be returned uncopied iff it's a compatible ndarray
(copy=False
).asanyarray
: The input will be returned uncopied iff it's a compatible ndarray
or subclass like matrix
(copy=False
, subok=True
).ascontiguousarray
: The input will be returned uncopied iff it's a compatible ndarray
in contiguous C order (copy=False
, order='C')
.asfortranarray
: The input will be returned uncopied iff it's a compatible ndarray
in contiguous Fortran order (copy=False
, order='F'
).require
: The input will be returned uncopied iff it's compatible with the specified requirements string.copy
: The input is always copied.fromiter
: The input is treated as an iterable (so, e.g., you can construct an array from an iterator's elements, instead of an object
array with the iterator); always copied.There are also convenience functions, like asarray_chkfinite
(same copying rules as asarray
, but raises ValueError
if there are any nan
or inf
values), and constructors for subclasses like matrix
or for special cases like record arrays, and of course the actual ndarray
constructor (which lets you create an array directly out of strides over a buffer).
In case you are wondering like I did where can we get the adapter position in the method getadapterposition(); its in viewholder object.so you have to put your code like this
mdataset.remove(holder.getadapterposition());
select substring(substring('B10000N0Z', patindex('%[0]%','B10000N0Z'), 20),
patindex('%[^0]%',substring('B10000N0Z', patindex('%[0]%','B10000N0Z'),
20)), 20)
returns N0Z
, that is, will get rid of leading zeroes and anything that comes before them.
Copied and pasted from here, the Using Advanced Properties section. This will allow you to always have the program run as an administrator when you open it.
Windows 7:
NOTE: If you are doing this is while logged in as standard user instead of an administrator, then you will need to provide the administrator's password before the program will run as administrator.
Update: (2015-07-05)
In Windows 8, you have to right-click devenv.exe and select "Troubleshoot compatibility".
Select "Troubleshoot program"
Check "The program requires additional permissions" click "Next", click "Test the program..."
Wait for the program to launch
Click "Next"
Select "Yes, save these settings for this program"
Click "Close"
Update reference original Link
In Windows 7 it is at the path
C:\Users\[username]\.android
debug.keystore
The ScriptIgnoreAttribute
class is in the System.Web.Extensions.dll assembly (Located under Assemblies > Framework in the VS Reference Manager). You have to add a reference to that assembly in your class library project.
You can find this information at top of the MSDN page for the ScriptIgnoreAttribute class.
-- First Truncate temporary table SQL> TRUNCATE TABLE test_temp1; -- Then Drop temporary table SQL> DROP TABLE test_temp1;
There are two ways to think about your phrase "application heap size available":
How much heap can my app use before a hard error is triggered? And
How much heap should my app use, given the constraints of the Android OS version and hardware of the user's device?
There is a different method for determining each of the above.
For item 1 above: maxMemory()
which can be invoked (e.g., in your main activity's onCreate()
method) as follows:
Runtime rt = Runtime.getRuntime();
long maxMemory = rt.maxMemory();
Log.v("onCreate", "maxMemory:" + Long.toString(maxMemory));
This method tells you how many total bytes of heap your app is allowed to use.
For item 2 above: getMemoryClass()
which can be invoked as follows:
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
int memoryClass = am.getMemoryClass();
Log.v("onCreate", "memoryClass:" + Integer.toString(memoryClass));
This method tells you approximately how many megabytes of heap your app should use if it wants to be properly respectful of the limits of the present device, and of the rights of other apps to run without being repeatedly forced into the onStop()
/ onResume()
cycle as they are rudely flushed out of memory while your elephantine app takes a bath in the Android jacuzzi.
This distinction is not clearly documented, so far as I know, but I have tested this hypothesis on five different Android devices (see below) and have confirmed to my own satisfaction that this is a correct interpretation.
For a stock version of Android, maxMemory()
will typically return about the same number of megabytes as are indicated in getMemoryClass()
(i.e., approximately a million times the latter value).
The only situation (of which I am aware) for which the two methods can diverge is on a rooted device running an Android version such as CyanogenMod, which allows the user to manually select how large a heap size should be allowed for each app. In CM, for example, this option appears under "CyanogenMod settings" / "Performance" / "VM heap size".
NOTE: BE AWARE THAT SETTING THIS VALUE MANUALLY CAN MESS UP YOUR SYSTEM, ESPECIALLY if you select a smaller value than is normal for your device.
Here are my test results showing the values returned by maxMemory()
and getMemoryClass()
for four different devices running CyanogenMod, using two different (manually-set) heap values for each:
In addition to the above, I tested on a Novo7 Paladin tablet running Ice Cream Sandwich. This was essentially a stock version of ICS, except that I've rooted the tablet through a simple process that does not replace the entire OS, and in particular does not provide an interface that would allow the heap size to be manually adjusted.
For that device, here are the results:
Also (per Kishore in a comment below):
And (per akauppi's comment):
Per a comment from cmcromance:
And (per tencent's comments):
Other Devices
I haven't tested these two methods using the special android:largeHeap="true" manifest option available since Honeycomb, but thanks to cmcromance and tencent we do have some sample largeHeap values, as reported above.
My expectation (which seems to be supported by the largeHeap numbers above) would be that this option would have an effect similar to setting the heap manually via a rooted OS - i.e., it would raise the value of maxMemory()
while leaving getMemoryClass()
alone. There is another method, getLargeMemoryClass(), that indicates how much memory is allowable for an app using the largeHeap setting. The documentation for getLargeMemoryClass() states, "most applications should not need this amount of memory, and should instead stay with the getMemoryClass() limit."
If I've guessed correctly, then using that option would have the same benefits (and perils) as would using the space made available by a user who has upped the heap via a rooted OS (i.e., if your app uses the additional memory, it probably will not play as nicely with whatever other apps the user is running at the same time).
Note that the memory class apparently need not be a multiple of 8MB.
We can see from the above that the getMemoryClass()
result is unchanging for a given device/OS configuration, while the maxMemory() value changes when the heap is set differently by the user.
My own practical experience is that on the G1 (which has a memory class of 16), if I manually select 24MB as the heap size, I can run without erroring even when my memory usage is allowed to drift up toward 20MB (presumably it could go as high as 24MB, although I haven't tried this). But other similarly large-ish apps may get flushed from memory as a result of my own app's pigginess. And, conversely, my app may get flushed from memory if these other high-maintenance apps are brought to the foreground by the user.
So, you cannot go over the amount of memory specified by maxMemory()
. And, you should try to stay within the limits specified by getMemoryClass()
. One way to do that, if all else fails, might be to limit functionality for such devices in a way that conserves memory.
Finally, if you do plan to go over the number of megabytes specified in getMemoryClass()
, my advice would be to work long and hard on the saving and restoring of your app's state, so that the user's experience is virtually uninterrupted if an onStop()
/ onResume()
cycle occurs.
In my case, for reasons of performance I'm limiting my app to devices running 2.2 and above, and that means that almost all devices running my app will have a memoryClass of 24 or higher. So I can design to occupy up to 20MB of heap and feel pretty confident that my app will play nice with the other apps the user may be running at the same time.
But there will always be a few rooted users who have loaded a 2.2 or above version of Android onto an older device (e.g., a G1). When you encounter such a configuration, ideally, you ought to pare down your memory use, even if maxMemory()
is telling you that you can go much higher than the 16MB that getMemoryClass()
is telling you that you should be targeting. And if you cannot reliably ensure that your app will live within that budget, then at least make sure that onStop()
/ onResume()
works seamlessly.
getMemoryClass()
, as indicated by Diane Hackborn (hackbod) above, is only available back to API level 5 (Android 2.0), and so, as she advises, you can assume that the physical hardware of any device running an earlier version of the OS is designed to optimally support apps occupying a heap space of no more than 16MB.
By contrast, maxMemory()
, according to the documentation, is available all the way back to API level 1. maxMemory()
, on a pre-2.0 version, will probably return a 16MB value, but I do see that in my (much later) CyanogenMod versions the user can select a heap value as low as 12MB, which would presumably result in a lower heap limit, and so I would suggest that you continue to test the maxMemory()
value, even for versions of the OS prior to 2.0. You might even have to refuse to run in the unlikely event that this value is set even lower than 16MB, if you need to have more than maxMemory()
indicates is allowed.
$.each(result, function(key, value) {
console.log(key+ ':' + value);
});
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws Exception {
ProcessBuilder pb = new ProcessBuilder("script.bat");
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader logReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String logLine = null;
while ( (logLine = logReader.readLine()) != null) {
System.out.println("Script output: " + logLine);
}
}
}
By using this line: pb.redirectErrorStream(true);
we can combine InputStream and ErrorStream
Cast the value so the compiler knows which function to call:
p.setval(static_cast<const char *>( 0 ));
Note, that you have a segmentation fault in your code after you get it to compile (depending on which function you really wanted to call).
SMS Push uses SMS as a carrier, WAP uses download via WAP.
Undoubtedly, for your purposes (which I assume is just a programming exercise), the best thing is to check your results against any of the listings of the digits of pi on the web.
And how do we know that those values are correct? Well, I could say that there are computer-science-y ways to prove that an implementation of an algorithm is correct.
More pragmatically, if different people use different algorithms, and they all agree to (pick a number) a thousand (million, whatever) decimal places, that should give you a warm fuzzy feeling that they got it right.
Historically, William Shanks published pi to 707 decimal places in 1873. Poor guy, he made a mistake starting at the 528th decimal place.
Very interestingly, in 1995 an algorithm was published that had the property that would directly calculate the nth digit (base 16) of pi without having to calculate all the previous digits!
Finally, I hope your initial algorithm wasn't pi/4 = 1 - 1/3 + 1/5 - 1/7 + ...
That may be the simplest to program, but it's also one of the slowest ways to do so. Check out the pi article on Wikipedia for faster approaches.
In Mac OS -moz-appearance: window;
will remove the arrow accrding to the MDN docs here: https://developer.mozilla.org/en-US/docs/CSS/-moz-appearance. Tested on Firefox 13 on Mac OS X 10.8.2. Also see: https://bugzilla.mozilla.org/show_bug.cgi?id=649849#c21.
this will do the job easily to get the last part of the required URL
$url="http://domain.com/artist/song/music-videos/song-title/9393903";
$requred_string= substr(strrchr($url, "/"), 1);
this will get you the string after first "/" from the right.
Depending on the resolution you need, you can use a different URL:
Default Thumbnail
http://img.youtube.com/vi/<insert-youtube-video-id-here>/default.jpg
High Quality Thumbnail
http://img.youtube.com/vi/<insert-youtube-video-id-here>/hqdefault.jpg
Medium Quality
http://img.youtube.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg
Standard Definition
http://img.youtube.com/vi/<insert-youtube-video-id-here>/sddefault.jpg
Maximum Resolution
http://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg
Note: it's a work-around if you don't want to use the YouTube Data API. Furthermore not all videos have the thumbnail images set, so the above method doesn’t work.
class Rectangle : public Area<int> {
};
book = load_workbook(xlsFilename)
writer = pd.ExcelWriter(self.xlsFilename)
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
df.to_excel(writer, sheet_name=sheetName, index=False)
writer.save()
I don't know if this will help with your current predicament as this is a recent feature, but you can specify the visibility of symbols in a global manner. Passing -fvisibility=hidden -fvisibility-inlines-hidden
at compilation can help the linker to later get rid of unneeded symbols. If you're producing an executable (as opposed to a shared library) there's nothing more to do.
More information (and a fine-grained approach for e.g. libraries) is available on the GCC wiki.
From: http://www.sql-server-helper.com/error-messages/msg-536.aspx
To use function LEFT if not all data is in the form '1/12' you need this in the second line above:
Set Col2 = LEFT(Col1, ISNULL(NULLIF(CHARINDEX('/', Col1) - 1, -1), LEN(Col1)))
function callServlet()
{
document.getElementById("adminForm").action="./Administrator";
document.getElementById("adminForm").method = "GET";
document.getElementById("adminForm").submit();
}
<button type="submit" onclick="callServlet()" align="center"> Register</button>
In the link you provided, thats not a loop in sql...
thats a loop in programming language
they are first getting list of all distinct districts, and then for each district executing query again.
df = pd.DataFrame({'Year': ['2014', '2015'], 'quarter': ['q1', 'q2']})
df['period'] = df[['Year', 'quarter']].apply(lambda x: ''.join(x), axis=1)
Yields this dataframe
Year quarter period
0 2014 q1 2014q1
1 2015 q2 2015q2
This method generalizes to an arbitrary number of string columns by replacing df[['Year', 'quarter']]
with any column slice of your dataframe, e.g. df.iloc[:,0:2].apply(lambda x: ''.join(x), axis=1)
.
You can check more information about apply() method here
Yes I know it is over half a year later and a tad late, BUT
row.names(df) <- NULL
does work. For me at least :-)
And if you have important information in row.names like dates for example, what I do is just :
df$Dates <- as.Date(row.names(df))
This will add a new column on the end but if you want it at the beginning of your data frame
df <- df[,c(7,1,2,3,4,5,6,...)]
Hope this helps those from Google :)
Considering the answer:
HttpWebRequest webRequest;
void StartWebRequest()
{
webRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), null);
}
void FinishWebRequest(IAsyncResult result)
{
webRequest.EndGetResponse(result);
}
You could send the request pointer or any other object like this:
void StartWebRequest()
{
HttpWebRequest webRequest = ...;
webRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), webRequest);
}
void FinishWebRequest(IAsyncResult result)
{
HttpWebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse;
}
Greetings
A couple of weeks ago, I suggested a solution on SO using genetic algorithms to solve a problem of graph layout. It is an example of a constrained optimization problem.
Also in the area of machine learning, I implemented a GA-based classification rules framework in c/c++ from scratch.
I've also used GA in a sample project for training artificial neural networks (ANN) as opposed to using the famous backpropagation algorithm.
In addition, and as part of my graduate research, I've used GA in training Hidden Markov Models as an additional approach to the EM-based Baum-Welch algorithm (in c/c++ again).
const response = await fetch('http://localhost/foo.txt');
const data = await response.text();
console.log(data);
Note that await
can only be used in an async
function. A longer example might be
async function loadFileAndPrintToConsole(url) {_x000D_
try {_x000D_
const response = await fetch(url);_x000D_
const data = await response.text();_x000D_
console.log(data);_x000D_
} catch (err) {_x000D_
console.error(err);_x000D_
}_x000D_
}_x000D_
_x000D_
loadFileAndPrintToConsole('https://threejsfundamentals.org/LICENSE');
_x000D_
I added this to Espuz and JCC's answer. It uses the y position of the subviews and doesn't include the scroll bars. Edit Uses the bottom of the lowest sub view that is visible.
+ (CGFloat) bottomOfLowestContent:(UIView*) view
{
CGFloat lowestPoint = 0.0;
BOOL restoreHorizontal = NO;
BOOL restoreVertical = NO;
if ([view respondsToSelector:@selector(setShowsHorizontalScrollIndicator:)] && [view respondsToSelector:@selector(setShowsVerticalScrollIndicator:)])
{
if ([(UIScrollView*)view showsHorizontalScrollIndicator])
{
restoreHorizontal = YES;
[(UIScrollView*)view setShowsHorizontalScrollIndicator:NO];
}
if ([(UIScrollView*)view showsVerticalScrollIndicator])
{
restoreVertical = YES;
[(UIScrollView*)view setShowsVerticalScrollIndicator:NO];
}
}
for (UIView *subView in view.subviews)
{
if (!subView.hidden)
{
CGFloat maxY = CGRectGetMaxY(subView.frame);
if (maxY > lowestPoint)
{
lowestPoint = maxY;
}
}
}
if ([view respondsToSelector:@selector(setShowsHorizontalScrollIndicator:)] && [view respondsToSelector:@selector(setShowsVerticalScrollIndicator:)])
{
if (restoreHorizontal)
{
[(UIScrollView*)view setShowsHorizontalScrollIndicator:YES];
}
if (restoreVertical)
{
[(UIScrollView*)view setShowsVerticalScrollIndicator:YES];
}
}
return lowestPoint;
}
That is because imgButton is null. Try this instead:
findViewById(R.id.imgButton).setBackgroundResource(R.drawable.ic_action_search);
or much easier to read:
imgButton = (Button) findViewById(R.id.imgButton);
imgButton.setOnClickListener(imgButtonHandler);
then in onClick: imgButton.setBackgroundResource(R.drawable.ic_action_search);
I had the same issue and believe that it has to do with the size of the repo (edited- or the size of a particular file) you are trying to push.
Basically I was able to create new repos and push them to github. But an existing one would not work.
The HTTP error code seems to back me up it is a 'Length Required' error. So maybe it is too large to calc or greated that the max. Who knows.
EDIT
I found that the problem may be files that are large. I had one update that would not push even though I had successful pushes up to that point. There was only one file in the commit but it happened to be 1.6M
So I added the following config change
git config http.postBuffer 524288000
To allow up to the file size 500M and then my push worked. It may have been that this was the problem initially with pushing a big repo over the http protocol.
END EDIT
the way I could get it to work (EDIT before I modified postBuffer) was to tar up my repo, copy it to a machine that can do git over ssh, and push it to github. Then when you try to do a push/pull from the original server it should work over https. (since it is a much smaller amount of data than an original push).
You can update with MERGE
Command with much more control over MATCHED
and NOT MATCHED
:(I slightly changed the source code to demonstrate my point)
USE tempdb;
GO
IF(OBJECT_ID('target') > 0)DROP TABLE dbo.target
IF(OBJECT_ID('source') > 0)DROP TABLE dbo.source
CREATE TABLE dbo.Target
(
EmployeeID INT ,
EmployeeName VARCHAR(100) ,
CONSTRAINT Target_PK PRIMARY KEY ( EmployeeID )
);
CREATE TABLE dbo.Source
(
EmployeeID INT ,
EmployeeName VARCHAR(100) ,
CONSTRAINT Source_PK PRIMARY KEY ( EmployeeID )
);
GO
INSERT dbo.Target
( EmployeeID, EmployeeName )
VALUES ( 100, 'Mary' );
INSERT dbo.Target
( EmployeeID, EmployeeName )
VALUES ( 101, 'Sara' );
INSERT dbo.Target
( EmployeeID, EmployeeName )
VALUES ( 102, 'Stefano' );
GO
INSERT dbo.Source
( EmployeeID, EmployeeName )
VALUES ( 100, 'Bob' );
INSERT dbo.Source
( EmployeeID, EmployeeName )
VALUES ( 104, 'Steve' );
GO
SELECT * FROM dbo.Source
SELECT * FROM dbo.Target
MERGE Target AS T
USING Source AS S
ON ( T.EmployeeID = S.EmployeeID )
WHEN MATCHED THEN
UPDATE SET T.EmployeeName = S.EmployeeName + '[Updated]';
GO
SELECT '-------After Merge----------'
SELECT * FROM dbo.Source
SELECT * FROM dbo.Target
My idea is to get max of rows count of all data.frames and next append empty matrix to every data.frame if need. This method doesn't require additional packages, only base is used. Code looks following:
list.df <- list(data.frame(a = 1:10), data.frame(a = 1:5), data.frame(a = 1:3))
max.rows <- max(unlist(lapply(list.df, nrow), use.names = F))
list.df <- lapply(list.df, function(x) {
na.count <- max.rows - nrow(x)
if (na.count > 0L) {
na.dm <- matrix(NA, na.count, ncol(x))
colnames(na.dm) <- colnames(x)
rbind(x, na.dm)
} else {
x
}
})
do.call(cbind, list.df)
# a a a
# 1 1 1 1
# 2 2 2 2
# 3 3 3 3
# 4 4 4 NA
# 5 5 5 NA
# 6 6 NA NA
# 7 7 NA NA
# 8 8 NA NA
# 9 9 NA NA
# 10 10 NA NA
Very Simple We can do that in the xml file
<TextView
android:justificationMode="inter_word"
/>
In my case the problem was that I had outdated django-stronghold
installed (0.2.9). And even though in the code I had:
from django.urls import reverse
I still encountered the error. After I upgraded the version to django-stronghold==0.4.0
the problem disappeard.
As indicated a standard ipv6 address is at most 45 chars, but an ipv6 address can also include an ending % followed by a "scope" or "zone" string, which has no fixed length but is generally a small positive integer or a network interface name, so in reality it can be bigger than 45 characters. Network interface names are typically "eth0", "eth1", "wlan0", so choosing 50 as the limit is likely good enough.
You delete first from the database and then you update your datagridview
:
//let's suppose delete(id) is a method which will delete a row from the database and
// returns true when it is done
int id = 0;
//we suppose that the first column in the datagridview is the ID of the ROW :
foreach (DataGridViewRow row in this.dataGridView1.SelectedRows)
id = Convert.ToInt32(row.Cells[0].Value.ToString());
if(delete(id))
this.dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
//else show message error!
With CSS: table {float:left;}?
?
I will suggest some questions focus on understanding of the programming concepts using dotnet like
What is the difference between managed and unmanaged enviroment? GC pros and cons JIT pros and cons If we need to develop application X can we use dotnet?why? (this will identify how he see the dotnet)
I suggest also to write small methods and ask him to rewrite them with better performance using better dotnet classes or standard ways. Also write inccorrect methods (in terms of any) logical or whatever and ask him to correct them.
Move all of your state and your handleClick
function from Header
to your MainWrapper
component.
Then pass values as props to all components that need to share this functionality.
class MainWrapper extends React.Component {
constructor() {
super();
this.state = {
sidbarPushCollapsed: false,
profileCollapsed: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
profileCollapsed: !this.state.profileCollapsed
});
}
render() {
return (
//...
<Header
handleClick={this.handleClick}
sidbarPushCollapsed={this.state.sidbarPushCollapsed}
profileCollapsed={this.state.profileCollapsed} />
);
Then in your Header's render() method, you'd use this.props
:
<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>
You could also use INDEX MATCH
, which is more "powerful" than vlookup. This would give you exactly what you are looking for:
The critical step is getting the merge itself to be in-place. It's not as difficult as those sources make out, but you lose something when you try.
Looking at one step of the merge:
[...list-sorted...|x...list-A...|y...list-B...]
We know that the sorted sequence is less than everything else, that x is less than everything else in A, and that y is less than everything else in B. In the case where x is less than or equal to y, you just move your pointer to the start of A on one. In the case where y is less than x, you've got to shuffle y past the whole of A to sorted. That last step is what makes this expensive (except in degenerate cases).
It's generally cheaper (especially when the arrays only actually contain single words per element, e.g., a pointer to a string or structure) to trade off some space for time and have a separate temporary array that you sort back and forth between.
Yes you can do it yourself. It is just a matter of grabbing the sources of the page and parsing them the way you want.
There are various possibilities. A good combo is using python-requests (built on top of urllib2, it is urllib.request
in Python3) and BeautifulSoup4, which has its methods to select elements and also permits CSS selectors:
import requests
from BeautifulSoup4 import BeautifulSoup as bs
request = requests.get("http://foo.bar")
soup = bs(request.text)
some_elements = soup.find_all("div", class_="myCssClass")
Some will prefer xpath parsing or jquery-like pyquery, lxml or something else.
When the data you want is produced by some JavaScript, the above won't work. You either need python-ghost or Selenium. I prefer the latter combined with PhantomJS, much lighter and simpler to install, and easy to use:
from selenium import webdriver
client = webdriver.PhantomJS()
client.get("http://foo")
soup = bs(client.page_source)
I would advice to start your own solution. You'll understand Scrapy's benefits doing so.
ps: take a look at scrapely: https://github.com/scrapy/scrapely
pps: take a look at Portia, to start extracting information visually, without programming knowledge: https://github.com/scrapinghub/portia
If you also want it to be a command you can reference without remembering the arguments, you could simply alias it:
alias df-gb='df -BG'
So if you type:
df-gb
into a terminal, you'll get your intended output of the disk usage in GB.
EDIT: or even use just df -h
to get it in a standard, human readable format.
It's also worth checking that you've got "Enable 32-bit Applications" set to True in the advanced settings of the DefaultAppPool within IIS.
Edit /etc/paths
. Then close the terminal and reopen it.
$ sudo vi /etc/paths
Note: each entry is seperated by line breaks.
/usr/local/bin
/usr/bin
/bin
/usr/sbin
/sbin
You may also insert the element using the slice indexing in the list. For example:
>>> a = [1, 2, 4]
>>> insert_at = 2 # Index at which you want to insert item
>>> b = a[:] # Created copy of list "a" as "b".
# Skip this step if you are ok with modifying the original list
>>> b[insert_at:insert_at] = [3] # Insert "3" within "b"
>>> b
[1, 2, 3, 4]
For inserting multiple elements together at a given index, all you need to do is to use a list
of multiple elements that you want to insert. For example:
>>> a = [1, 2, 4]
>>> insert_at = 2 # Index starting from which multiple elements will be inserted
# List of elements that you want to insert together at "index_at" (above) position
>>> insert_elements = [3, 5, 6]
>>> a[insert_at:insert_at] = insert_elements
>>> a # [3, 5, 6] are inserted together in `a` starting at index "2"
[1, 2, 3, 5, 6, 4]
To know more about slice indexing, you can refer: Understanding slice notation.
Note: In Python 3.x, difference of performance between slice indexing and list.index(...)
is significantly reduced and both are almost equivalent. However, in Python 2.x, this difference is quite noticeable. I have shared performance comparisons later in this answer.
Alternative using list comprehension (but very slow in terms of performance):
As an alternative, it can be achieved using list comprehension with enumerate
too. (But please don't do it this way. It is just for illustration):
>>> a = [1, 2, 4]
>>> insert_at = 2
>>> b = [y for i, x in enumerate(a) for y in ((3, x) if i == insert_at else (x, ))]
>>> b
[1, 2, 3, 4]
Here's the timeit
comparison of all the answers with list of 1000 elements on Python 3.9.1 and Python 2.7.16. Answers are listed in the order of performance for both the Python versions.
My answer using sliced insertion - Fastest ( 2.25 µsec per loop)
python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
100000 loops, best of 5: 2.25 µsec per loop
Rushy Panchal's answer with most votes using list.insert(...)
- Second (2.33 µsec per loop)
python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
100000 loops, best of 5: 2.33 µsec per loop
ATOzTOA's accepted answer based on merge of sliced lists - Third (5.01 µsec per loop)
python3 -m timeit -s "a = list(range(1000))" "b = a[:500] + [3] + a[500:]"
50000 loops, best of 5: 5.01 µsec per loop
My answer with List Comprehension and enumerate
- Fourth (very slow with 135 µsec per loop)
python3 -m timeit -s "a = list(range(1000))" "[y for i, x in enumerate(a) for y in ((3, x) if i == 500 else (x, )) ]"
2000 loops, best of 5: 135 µsec per loop
My answer using sliced insertion - Fastest (2.09 µsec per loop)
python -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
100000 loops, best of 3: 2.09 µsec per loop
Rushy Panchal's answer with most votes using list.insert(...)
- Second (2.36 µsec per loop)
python -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
100000 loops, best of 3: 2.36 µsec per loop
ATOzTOA's accepted answer based on merge of sliced lists - Third (4.44 µsec per loop)
python -m timeit -s "a = list(range(1000))" "b = a[:500] + [3] + a[500:]"
100000 loops, best of 3: 4.44 µsec per loop
My answer with List Comprehension and enumerate
- Fourth (very slow with 103 µsec per loop)
python -m timeit -s "a = list(range(1000))" "[y for i, x in enumerate(a) for y in ((3, x) if i == 500 else (x, )) ]"
10000 loops, best of 3: 103 µsec per loop
Your conversion data is response[25] and follow the below steps.
var i = parseFloat(response[25]).toFixed(2)
console.log(i)//-6527.34
You also could allocate using new
and initialize all fields by hand
package main
type Configuration struct {
Val string
Proxy struct {
Address string
Port string
}
}
func main() {
c := new(Configuration)
c.Val = "test"
c.Proxy.Address = "addr"
c.Proxy.Port = "80"
}
See in playground: https://play.golang.org/p/sFH_-HawO_M
Actually, it's quite easy: instead of the number of bins you can give a list with the bin boundaries. They can be unequally distributed, too:
plt.hist(data, bins=[0, 10, 20, 30, 40, 50, 100])
If you just want them equally distributed, you can simply use range:
plt.hist(data, bins=range(min(data), max(data) + binwidth, binwidth))
Added to original answer
The above line works for data
filled with integers only. As macrocosme points out, for floats you can use:
import numpy as np
plt.hist(data, bins=np.arange(min(data), max(data) + binwidth, binwidth))
Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.
Do you have this:
use Cartalyst\Sentry\Sentry;
In your code?
Ok, but if this line is working for you:
$user = $this->sentry->register(array( 'username' => e($data['username']), 'email' => e($data['email']), 'password' => e($data['password']) ));
So you already have it instantiated and you can surely do:
$adminGroup = $this->sentry->findGroupById(5);
There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.
Similarity::Similarity()
or Similarity::~Similarity()
are just missing and you have defined the others incorrectly,
void Similarity::readData(Scanner& inStream){
}
not
void readData(Scanner& inStream){
}
etc. etc.
The second one is a function called readData, only the first is the readData method of the Similarity class.
To be clear about this, in Similarity.h
void readData(Scanner& inStream);
but in Similarity.cpp
void Similarity::readData(Scanner& inStream){
}
you need check packagesToScan.
<bean id="entityManagerFactoryDB" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
<property name="dataSource" ref="dataSourceDB" />
<property name="persistenceUnitName" value="persistenceUnitDB" />
<property name="packagesToScan" value="at.naviclean.domain" />
//here
.....
Update: JavaFX 8u40 includes simple Dialogs and Alerts!, check out this blog post which explains how to use the official JavaFX Dialogs!
It may help to use a different constructor for Uri.
If you have the server name
string server = "http://www.myserver.com";
and have a relative Uri path to append to it, e.g.
string relativePath = "sites/files/images/picture.png"
When creating a Uri from these two I get the "format could not be determined" exception unless I use the constructor with the UriKind argument, i.e.
// this works, because the protocol is included in the string
Uri serverUri = new Uri(server);
// needs UriKind arg, or UriFormatException is thrown
Uri relativeUri = new Uri(relativePath, UriKind.Relative);
// Uri(Uri, Uri) is the preferred constructor in this case
Uri fullUri = new Uri(serverUri, relativeUri);
I think you haven't messed up yet. Try:
git reset HEAD^
This will bring the dir to state before you've made the commit, HEAD^
means the parent of the current commit (the one you don't want anymore), while keeping changes from it (unstaged).
You didn't select post_id
in the subquery. You have to select it in the subquery like this:
SELECT wp_woocommerce_order_items.order_id As No_Commande
FROM wp_woocommerce_order_items
LEFT JOIN
(
SELECT meta_value As Prenom, post_id -- <----- this
FROM wp_postmeta
WHERE meta_key = '_shipping_first_name'
) AS a
ON wp_woocommerce_order_items.order_id = a.post_id
WHERE wp_woocommerce_order_items.order_id =2198
GNU cp
has an option to create symlinks instead of copying.
cp -rs /mnt/usr/lib /usr/
Note this is a GNU extension not found in POSIX cp
.
i realize it works after adding a slash behind like so
mysite/Controller/Action/21-9-2009 10:20/
Stroke length depends on stroke width. You can increase length by increasing width and hide part of border by inner element.
EDIT: added pointer-events: none;
thanks to benJ.
.thin {
background: #F4FFF3;
border: 2px dashed #3FA535;
position: relative;
}
.thin:after {
content: '';
position: absolute;
left: -1px;
top: -1px;
right: -1px;
bottom: -1px;
border: 1px solid #F4FFF3;
pointer-events: none;
}
I change upload method with images[]
according to @Denmark.
private function upload_files($path, $title, $files)
{
$config = array(
'upload_path' => $path,
'allowed_types' => 'jpg|gif|png',
'overwrite' => 1,
);
$this->load->library('upload', $config);
$images = array();
foreach ($files['name'] as $key => $image) {
$_FILES['images[]']['name']= $files['name'][$key];
$_FILES['images[]']['type']= $files['type'][$key];
$_FILES['images[]']['tmp_name']= $files['tmp_name'][$key];
$_FILES['images[]']['error']= $files['error'][$key];
$_FILES['images[]']['size']= $files['size'][$key];
$fileName = $title .'_'. $image;
$images[] = $fileName;
$config['file_name'] = $fileName;
$this->upload->initialize($config);
if ($this->upload->do_upload('images[]')) {
$this->upload->data();
} else {
return false;
}
}
return $images;
}
If you have some given list, and want to iterate over its items and indices, you can use enumerate()
:
for index, item in enumerate(my_list):
print index, item
If you only need the indices, you can use range()
:
for i in range(len(my_list)):
print i
(from Ways to sort lists of objects in Java based on multiple fields)
Working code in this gist
Java 8 solves this nicely by lambda's (though Guava and Apache Commons might still offer more flexibility):
Collections.sort(reportList, Comparator.comparing(Report::getReportKey)
.thenComparing(Report::getStudentNumber)
.thenComparing(Report::getSchool));
Thanks to @gaoagong's answer below.
Collections.sort(pizzas, new Comparator<Pizza>() {
@Override
public int compare(Pizza p1, Pizza p2) {
int sizeCmp = p1.size.compareTo(p2.size);
if (sizeCmp != 0) {
return sizeCmp;
}
int nrOfToppingsCmp = p1.nrOfToppings.compareTo(p2.nrOfToppings);
if (nrOfToppingsCmp != 0) {
return nrOfToppingsCmp;
}
return p1.name.compareTo(p2.name);
}
});
This requires a lot of typing, maintenance and is error prone.
ComparatorChain chain = new ComparatorChain(Arrays.asList(
new BeanComparator("size"),
new BeanComparator("nrOfToppings"),
new BeanComparator("name")));
Collections.sort(pizzas, chain);
Obviously this is more concise, but even more error prone as you lose your direct reference to the fields by using Strings instead (no typesafety, auto-refactorings). Now if a field is renamed, the compiler won’t even report a problem. Moreover, because this solution uses reflection, the sorting is much slower.
Collections.sort(pizzas, new Comparator<Pizza>() {
@Override
public int compare(Pizza p1, Pizza p2) {
return ComparisonChain.start().compare(p1.size, p2.size).compare(p1.nrOfToppings, p2.nrOfToppings).compare(p1.name, p2.name).result();
// or in case the fields can be null:
/*
return ComparisonChain.start()
.compare(p1.size, p2.size, Ordering.natural().nullsLast())
.compare(p1.nrOfToppings, p2.nrOfToppings, Ordering.natural().nullsLast())
.compare(p1.name, p2.name, Ordering.natural().nullsLast())
.result();
*/
}
});
This is much better, but requires some boiler plate code for the most common use case: null-values should be valued less by default. For null-fields, you have to provide an extra directive to Guava what to do in that case. This is a flexible mechanism if you want to do something specific, but often you want the default case (ie. 1, a, b, z, null).
Collections.sort(pizzas, new Comparator<Pizza>() {
@Override
public int compare(Pizza p1, Pizza p2) {
return new CompareToBuilder().append(p1.size, p2.size).append(p1.nrOfToppings, p2.nrOfToppings).append(p1.name, p2.name).toComparison();
}
});
Like Guava’s ComparisonChain, this library class sorts easily on multiple fields, but also defines default behavior for null values (ie. 1, a, b, z, null). However, you can’t specify anything else either, unless you provide your own Comparator.
Ultimately it comes down to flavor and the need for flexibility (Guava’s ComparisonChain) vs. concise code (Apache’s CompareToBuilder).
I found a nice solution that combines multiple comparators in order of priority on CodeReview in a MultiComparator
:
class MultiComparator<T> implements Comparator<T> {
private final List<Comparator<T>> comparators;
public MultiComparator(List<Comparator<? super T>> comparators) {
this.comparators = comparators;
}
public MultiComparator(Comparator<? super T>... comparators) {
this(Arrays.asList(comparators));
}
public int compare(T o1, T o2) {
for (Comparator<T> c : comparators) {
int result = c.compare(o1, o2);
if (result != 0) {
return result;
}
}
return 0;
}
public static <T> void sort(List<T> list, Comparator<? super T>... comparators) {
Collections.sort(list, new MultiComparator<T>(comparators));
}
}
Ofcourse Apache Commons Collections has a util for this already:
ComparatorUtils.chainedComparator(comparatorCollection)
Collections.sort(list, ComparatorUtils.chainedComparator(comparators));
For Python 3.3 and later time.process_time()
is very nice:
import time
t = time.process_time()
#do some stuff
elapsed_time = time.process_time() - t
You use attach
without detach
- every time you do it new call to attach masks objects attached before (they contain the same names). Either use detach
or do not use attach
at all.
Nice discussion and tips are here.
For example :
<div style="height:100px; width:100px; background:#000000"></div>
_x000D_
here.
you give css to div of height and width having 100px and background as black.
PS : try to avoid inline-css you can make external CSS and import in your html file.
you can refer here for CSS
hope this helps.
I think this need to be run from the Management Shell rather than the console, it sounds like the module isn't being imported into the Powershell console. You can add the module by running:
Add-PSSnapin Microsoft.Sharepoint.Powershell
in the Powershell console.
I think you can try
<a href="JavaScript:void(0)">link</a>
The only catch I see over here is high level browser security may prompt on executing javascript.
Though this is one of the easier way than
<a href="#" onclick="return false;">Link</a>
this should be used sparingly
Read this article for some pointers https://web.archive.org/web/20090301044015/http://blog.reindel.com/2006/08/11/a-hrefjavascriptvoid0-avoid-the-void
If you must, this is how you can do it in a for loop:
mylist = ['first', 'second', 'other']
endstring = ''
for s in mylist:
endstring += s
but you should consider using join()
:
''.join(mylist)
Sorting html table column on page load
var table = $('table#all_items_table');
var rows = table.find('tr:gt(0)').toArray().sort(comparer(3));
for (var i = 0; i < rows.length; i++) {
table.append(rows[i])
}
function comparer(index) {
return function (a, b) {
var v1= getCellValue(a, index),
v2= getCellValue(b, index);
return $.isNumeric(v2) && $.isNumeric(v1) ? v2 - v1: v2.localeCompare(v1)
}
}
function getCellValue(row, index) {
return parseFloat($(row).children('td').eq(index).html().replace(/,/g,'')); //1234234.45645->1234234
}
The following code is a modified example from React.js website.
Original code is available here: https://reactjs.org/#a-simple-component
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = {
seconds: parseInt(props.startTimeInSeconds, 10) || 0
};
}
tick() {
this.setState(state => ({
seconds: state.seconds + 1
}));
}
componentDidMount() {
this.interval = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
formatTime(secs) {
let hours = Math.floor(secs / 3600);
let minutes = Math.floor(secs / 60) % 60;
let seconds = secs % 60;
return [hours, minutes, seconds]
.map(v => ('' + v).padStart(2, '0'))
.filter((v,i) => v !== '00' || i > 0)
.join(':');
}
render() {
return (
<div>
Timer: {this.formatTime(this.state.seconds)}
</div>
);
}
}
ReactDOM.render(
<Timer startTimeInSeconds="300" />,
document.getElementById('timer-example')
);
I ran into the same issue. I simply updated my command to begin with python3
instead of python
and it worked perfectly.
It's simple:
from django.http import HttpResponseRedirect
def myview(request):
...
return HttpResponseRedirect("/path/")
More info in the official Django docs
Update: Django 1.0
There is apparently a better way of doing this in Django now using generic views
.
Example -
from django.views.generic.simple import redirect_to
urlpatterns = patterns('',
(r'^one/$', redirect_to, {'url': '/another/'}),
#etc...
)
There is more in the generic views documentation. Credit - Carles Barrobés.
Update #2: Django 1.3+
In Django 1.5 redirect_to no longer exists and has been replaced by RedirectView. Credit to Yonatan
from django.views.generic import RedirectView
urlpatterns = patterns('',
(r'^one/$', RedirectView.as_view(url='/another/')),
)
Brought my answer over from other thread that may close as a duplicate...
From GIT documentation: Git Docs
Below gives the full information. In short, simple
will only push the current working branch
and even then only if it also has the same name on the remote. This is a very good setting for beginners and will become the default in GIT 2.0
Whereas matching
will push all branches locally that have the same name on the remote. (Without regard to your current working branch ). This means potentially many different branches will be pushed, including those that you might not even want to share.
In my personal usage, I generally use a different option: current
which pushes the current working branch, (because I always branch for any changes). But for a beginner I'd suggest simple
push.default
Defines the action git push should take if no refspec is explicitly given. Different values are well-suited for specific workflows; for instance, in a purely central workflow (i.e. the fetch source is equal to the push destination), upstream is probably what you want. Possible values are:nothing - do not push anything (error out) unless a refspec is explicitly given. This is primarily meant for people who want to avoid mistakes by always being explicit.
current - push the current branch to update a branch with the same name on the receiving end. Works in both central and non-central workflows.
upstream - push the current branch back to the branch whose changes are usually integrated into the current branch (which is called @{upstream}). This mode only makes sense if you are pushing to the same repository you would normally pull from (i.e. central workflow).
simple - in centralized workflow, work like upstream with an added safety to refuse to push if the upstream branch's name is different from the local one.
When pushing to a remote that is different from the remote you normally pull from, work as current. This is the safest option and is suited for beginners.
This mode will become the default in Git 2.0.
matching - push all branches having the same name on both ends. This makes the repository you are pushing to remember the set of branches that will be pushed out (e.g. if you always push maint and master there and no other branches, the repository you push to will have these two branches, and your local maint and master will be pushed there).
To use this mode effectively, you have to make sure all the branches you would push out are ready to be pushed out before running git push, as the whole point of this mode is to allow you to push all of the branches in one go. If you usually finish work on only one branch and push out the result, while other branches are unfinished, this mode is not for you. Also this mode is not suitable for pushing into a shared central repository, as other people may add new branches there, or update the tip of existing branches outside your control.
This is currently the default, but Git 2.0 will change the default to simple.
It can be done now with HTML5
See this post here HTML select form with option to enter custom value
<input type="text" list="cars" />
<datalist id="cars">
<option>Volvo</option>
<option>Saab</option>
<option>Mercedes</option>
<option>Audi</option>
</datalist>
install Android 7 - Platform 24 Full in android sdk manager
just it
Had the same problem. I apparently wrote the Main wrong:
public static void main(String[] args){
I missed the []
and that was the whole problem.
Check and recheck the Main function!
another way, will also work on MySQL and PostgreSQL
select TABLE_NAME from INFORMATION_SCHEMA.TABLES
where TABLE_TYPE = 'BASE TABLE'
The issue is that you're not saving the mysqli connection. Change your connect to:
$aVar = mysqli_connect('localhost','tdoylex1_dork','dorkk','tdoylex1_dork');
And then include it in your query:
$query1 = mysqli_query($aVar, "SELECT name1 FROM users
ORDER BY RAND()
LIMIT 1");
$aName1 = mysqli_fetch_assoc($query1);
$name1 = $aName1['name1'];
Also don't forget to enclose your connections variables as strings as I have above. This is what's causing the error but you're using the function wrong, mysqli_query returns a query object but to get the data out of this you need to use something like mysqli_fetch_assoc http://php.net/manual/en/mysqli-result.fetch-assoc.php to actually get the data out into a variable as I have above.
I want to add a point that you can also (and should if what you are writing is complex) add a test variable to rollback if you are in test mode. Then you can execute the whole thing at once. Often I also add code to see the before and after results of various operations especially if it is a complex script.
Example below:
USE AdventureWorks;
GO
DECLARE @TEST INT = 1--1 is test mode, use zero when you are ready to execute
BEGIN TRANSACTION;
BEGIN TRY
IF @TEST= 1
BEGIN
SELECT *FROM Production.Product
WHERE ProductID = 980;
END
-- Generate a constraint violation error.
DELETE FROM Production.Product
WHERE ProductID = 980;
IF @TEST= 1
BEGIN
SELECT *FROM Production.Product
WHERE ProductID = 980;
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END CATCH;
IF @@TRANCOUNT > 0 AND @TEST = 0
COMMIT TRANSACTION;
GO
Use
var jsDate = $('#your_datepicker_id').datepicker('getDate');
if (jsDate !== null) { // if any date selected in datepicker
jsDate instanceof Date; // -> true
jsDate.getDate();
jsDate.getMonth();
jsDate.getFullYear();
}
select case
when exists (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Tags' AND COLUMN_NAME = 'ModifiedByUser')
then 0
else 1
end
Be careful with the select()
function, because it's used both in the dplyr and MASS packages, so if MASS is loaded, select() may not work properly. To find out what packages are loaded, type sessionInfo()
and look for it in the "other attached packages:" section. If it is loaded, type detach( "package:MASS", unload = TRUE )
, and your select()
function should work again.
I have combine two different answers:
Complete HTML missing tags
$string = strip_tags($strHTML);
$yourText = $strHTML;
if (strlen($string) > 350) {
$stringCut = substr($post->body, 0, 350);
$doc = new DOMDocument();
$doc->loadHTML($stringCut);
$yourText = $doc->saveHTML();
}
$yourText."...<a href=''>View More</a>"
It's probably a firewall issue. Make sure you port forward the port you want to connect to on the server side. localhost maps directly to an ip and also moves through your network stack. You're changing some text in your code but the way your program is working is fundamentally the same.
Change the checkboxes so that the name includes the index inside the brackets:
<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>">
The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.
you are using onclick
which is javascript event.
there is two ways
Javascript
<input type="button" value="Home" class="homebutton" id="btnHome"
onClick="window.location = 'http://google.com'" />
Or PHP
create another page as redirect.php and put
<?php header('location : google.com') ?>
and insert this link on any page within the same directory
<a href="redirect.php">google<a/>
hope this helps its simplest!!
What is the difference between left join and left outer join?
Nothing. LEFT JOIN
and LEFT OUTER JOIN
are equivalent.
As far as I know, the best way to achieve that without extensions and complex coding is like this:
date.toLocaleString([], { hour12: true});
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
<p>Click the button to display the date and time as a string.</p>_x000D_
_x000D_
<button onclick="myFunction()">Try it</button>_x000D_
<button onclick="fullDateTime()">Try it2</button>_x000D_
<p id="demo"></p>_x000D_
<p id="demo2"></p>_x000D_
<script>_x000D_
function myFunction() {_x000D_
var d = new Date();_x000D_
var n = d.toLocaleString([], { hour: '2-digit', minute: '2-digit' });_x000D_
document.getElementById("demo").innerHTML = n;_x000D_
}_x000D_
function fullDateTime() {_x000D_
var d = new Date(); _x000D_
var n = d.toLocaleString([], { hour12: true});_x000D_
document.getElementById("demo2").innerHTML = n;_x000D_
}_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
I found this checking this question out.
How do I use .toLocaleTimeString() without displaying seconds?
I had the same issue with VS2017. Following solved the issue.
reg add HKLM\Software\WOW6432Node\Microsoft\InetStp /v MajorVersion /t REG_DWORD /d 10 /f
reg add HKLM\Software\Microsoft\InetStp /v MajorVersion /t REG_DWORD /d 10 /f
This should solve your problem. Refer to this link for more details.
No, you can't in Firefox, Safari, etc. You can in Internet Explorer. There are several scripts out there that will allow you to make a scroll bar.
SELECT table_name, owner FROM all_tables where owner='schema_name' order by table_name
filenames = '000'.upto('100').map { |index| "file_#{index}" }
Outputs
[file_000, file_001, file_002, file_003, ..., file_098, file_099, file_100]
Linux Mint 19.3
I installed Java Oracle manually, like this:
$ sudo ln -s /usr/lib/jvm/java-1.8.0_211/bin/javac /usr/bin/javac
There could be security issues with common methods for auto-login. One of the most easiest ways is documented below:
And as for the part the executes the command In putty UI, Connection>SSH> there's a field for remote command.
4.17 The SSH panel
The SSH panel allows you to configure options that only apply to SSH sessions.
4.17.1 Executing a specific command on the server
In SSH, you don't have to run a general shell session on the server. Instead, you can choose to run a single specific command (such as a mail user agent, for example). If you want to do this, enter the command in the "Remote command" box. http://the.earth.li/~sgtatham/putty/0.53/htmldoc/Chapter4.html
in short, your answers might just as well be similar to the text below:
Use explode() or preg_split() function to split the string in php with given delimiter
// Use preg_split() function
$string = "123,456,78,000";
$str_arr = preg_split ("/\,/", $string);
print_r($str_arr);
// use of explode
$string = "123,46,78,000";
$str_arr = explode (",", $string);
print_r($str_arr);
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import String
Base = declarative_base()
metadata = Base.metadata
class UserTable(Base):
__tablename__ = 'UserTable'
Id = Column("ID", Integer, primary_key=True)
Name = Column("Name", String(100))
class UserTableDTO:
def __init__(self, ob):
self.Id = ob.Id
self.Name = ob.Name
rows = dbsession.query(Table).all()
json_string = [json.loads(json.dumps(UserTableDTO(ob).__dict__, default=lambda x: str(x)))for ob in rows]
print(json_string)
The pack
method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize
or setBounds
(which also sets the frame location). In general, using pack is preferable to calling setSize
, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.
From Java tutorial
You should also refer to Javadocs any time you need additional information on any Java API
?+K
Command+K for newer keyboards
/usr/bin/osascript -e 'tell application "System Events" to tell process "Terminal" to keystroke "k" using command down'
set WRAP OFF
set PAGESIZE 0
Try using those settings.
JSON in any HTML tag except <script>
tag would be a mere text. Thus it's like you add a story to your HTML page.
However, about formatting, that's another matter. I guess you should change the title of your question.
You have to loop over the input array and add rules for each input as described here: Loop Over Rules
Here is a some code for ya:
$input = Request::all();
$rules = [];
foreach($input['name'] as $key => $val)
{
$rules['name.'.$key] = 'required|distinct|min:3';
}
$rules['amount'] = 'required|integer|min:1';
$rules['description'] = 'required|string';
$validator = Validator::make($input, $rules);
//Now check validation:
if ($validator->fails())
{
/* do something */
}
If your cost is a polynomial, just keep the highest-order term, without its multiplier. E.g.:
O((n/2 + 1)*(n/2)) = O(n2/4 + n/2) = O(n2/4) = O(n2)
This doesn't work for infinite series, mind you. There is no single recipe for the general case, though for some common cases, the following inequalities apply:
O(log N) < O(N) < O(N log N) < O(N2) < O(Nk) < O(en) < O(n!)
At the right upper corner second last icon (encircled red in attached image) is for activate/deactivate debugging. Click it to toggle debugging anytime.
If you create the object of SoapParam, This will resolve your problem. Create a class and map it with object type given by WebService, Initialize the values and send in the request. See the sample below.
struct Contact {
function Contact ($pid, $pname)
{
id = $pid;
name = $pname;
}
}
$struct = new Contact(100,"John");
$soapstruct = new SoapVar($struct, SOAP_ENC_OBJECT, "Contact","http://soapinterop.org/xsd");
$ContactParam = new SoapParam($soapstruct, "Contact")
$response = $client->Function1($ContactParam);
If something has double linespaced your text then this command will remove the double spacing and merge pre-existing repeating blank lines into a single blank line. It uses a temporary delimiter of ^^^ at the start of a line so if this clashes with your content choose something else. Lines containing only whitespace are treated as blank.
%s/^\s*\n\n\+/^^^\r/g | g/^\s*$/d | %s/^^^^.*
Here is the example macro to convert the Excel worksheet to XML file.
#'vba code to convert excel to xml
Sub vba_code_to_convert_excel_to_xml()
Set wb = Workbooks.Open("C:\temp\testwb.xlsx")
wb.SaveAs fileName:="C:\temp\testX.xml", FileFormat:= _
xlXMLSpreadsheet, ReadOnlyRecommended:=False, CreateBackup:=False
End Sub
This macro will open an existing Excel workbook from the C drive and Convert the file into XML and Save the file with .xml extension in the specified Folder. We are using Workbook Open method to open a file. SaveAs method to Save the file into destination folder. This example will be help full, if you wan to convert all excel files in a directory into XML (xlXMLSpreadsheet format) file.
Add a delegate method of UITextField
like this:
@interface MyController : UIViewController <UITextFieldDelegate>
And set your textField.delegate = self;
then also add two delegate methods of UITextField
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
return YES;
}
// It is important for you to hide the keyboard
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
From any class you can't set its value to null. This is not allowed and doesn't make sense also -
public void Delete()
{
this = null; <-- NOT ALLOWED
}
You need an instance of class to call Delete()
method so why not set that instance to null itself once you are done with it.
Car car = new Car();
// Use car objects and once done set back to null
car = null;
Anyhow what you are trying to achieve is not possible in C#. I suspect from your question that you want this because there are memory leaks present in your current design which doesn't let the Car instance to go away. I would suggest you better profile your application and identify the areas which is stopping GC to collect car instance and work on improving that area.
Swift 3:
let minutes: TimeInterval = 1 * 60
let nowPlusOne = Date() + minutes
You can just create an object like this:
public class SomeQuery
{
public string SomeParameter { get; set; }
public int? SomeParameter2 { get; set; }
}
And then in controller just make something like that:
[HttpGet]
public IActionResult FindSomething([FromQuery] SomeQuery query)
{
// Your implementation goes here..
}
Even better, you can create API model from:
[HttpGet]
public IActionResult GetSomething([FromRoute] int someId, [FromQuery] SomeQuery query)
to:
[HttpGet]
public IActionResult GetSomething(ApiModel model)
public class ApiModel
{
[FromRoute]
public int SomeId { get; set; }
[FromQuery]
public string SomeParameter { get; set; }
[FromQuery]
public int? SomeParameter2 { get; set; }
}
In IIS set the App Pool Identity As Service Account user or Administrator Account or ant account which has permission to do the operation on that DataBase.
On my website, to check if registering people is 18 years old, I simply used the following :
$legalAge = date('Y-m-d', strtotime('-18 year'));
After, only compare the the two dates.
Hope it could help someone.
cmd -> right click -> Run as administrator
C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i
If you are working in asp.net with razor, and you want to control multiple submit button event.then this answer will guide you. Lets for example we have two button, one button will redirect us to "PageA.cshtml" and other will redirect us to "PageB.cshtml".
@{
if (IsPost)
{
if(Request["btn"].Equals("button_A"))
{
Response.Redirect("PageA.cshtml");
}
if(Request["btn"].Equals("button_B"))
{
Response.Redirect("PageB.cshtml");
}
}
}
<form method="post">
<input type="submit" value="button_A" name="btn"/>;
<input type="submit" value="button_B" name="btn"/>;
</form>
For now you can write an invite link to bot @username_to_id_bot and you will get the id:
also works with public chats, channels and even users
I wrote a program with wpf
and used Database for showing images and this is my code:
SqlConnection con = new SqlConnection(@"Data Source=HITMAN-PC\MYSQL;
Initial Catalog=Payam;
Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter("select * from news", con);
DataTable dt = new DataTable();
da.Fill(dt);
string adress = dt.Rows[i]["ImgLink"].ToString();
ImageSource imgsr = new BitmapImage(new Uri(adress));
PnlImg.Source = imgsr;
On the Button:
CommandArgument='<%# Eval("myKey")%>'
On the Server Event
e.CommandArgument
You can just do something like this and pass in the whole number and then the cents after.
String.format("$%,d.%02d",wholeNum,change);
What I did is first check what are the running processes by
SELECT * FROM pg_stat_activity WHERE state = 'active';
Find the process you want to kill, then type:
SELECT pg_cancel_backend(<pid of the process>)
This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.
If the process cannot be killed, try:
SELECT pg_terminate_backend(<pid of the process>)
You can also plot to a png file using gnuplot (which is free):
terminal commands
gnuplot> set title '<title>'
gnuplot> set ylabel '<yLabel>'
gnuplot> set xlabel '<xLabel>'
gnuplot> set grid
gnuplot> set term png
gnuplot> set output '<Output file name>.png'
gnuplot> plot '<fromfile.csv>'
note: you always need to give the right extension (.png here) at set output
Then it is also possible that the ouput is not lines, because your data is not continues. To fix this simply change the 'plot' line to:
plot '<Fromfile.csv>' with line lt -1 lw 2
More line editing options (dashes and line color ect.) at: http://gnuplot.sourceforge.net/demo_canvas/dashcolor.html
apt-get install gnuplot
)brew install gnuplot
)In Eclipse Neon.3, as well as in the new Eclipse Photon (4.8.0), I can resize the font easily with Ctrl + Shift + + and -, without any plugin or special key binding.
At least in Editor Windows (this does not work in other Views like Console, Project Explorer etc).
I googled a bit, and found this code here:
File file = getJarFileToLoadFrom();
String lcStr = getNameOfClassToLoad();
URL jarfile = new URL("jar", "","file:" + file.getAbsolutePath()+"!/");
URLClassLoader cl = URLClassLoader.newInstance(new URL[] {jarfile });
Class loadedClass = cl.loadClass(lcStr);
Can anyone share opinions/comments/answers regarding this approach?
enter the android terminal and then you can type the following commands :dumpsys cpuinfo
shell@android:/ $ dumpsys cpuinfo
Load: 0.8 / 0.75 / 1.15
CPU usage from 69286ms to 9283ms ago with 99% awake:
47% 1118/com.wxg.sodproject: 12% user + 35% kernel
1.6% 1225/android.process.media: 1% user + 0.6% kernel
1.3% 263/mpdecision: 0.1% user + 1.2% kernel
0.1% 32747/kworker/u:1: 0% user + 0.1% kernel
0.1% 883/com.android.systemui: 0.1% user + 0% kernel
0.1% 521/system_server: 0.1% user + 0% kernel / faults: 14 minor
0.1% 1826/com.quicinc.trepn: 0.1% user + 0% kernel
0.1% 2462/kworker/0:2: 0.1% user + 0% kernel
0.1% 32649/kworker/0:0: 0% user + 0.1% kernel
0% 118/mmcqd/0: 0% user + 0% kernel
0% 179/surfaceflinger: 0% user + 0% kernel
0% 46/kinteractiveup: 0% user + 0% kernel
0% 141/jbd2/mmcblk0p26: 0% user + 0% kernel
0% 239/sdcard: 0% user + 0% kernel
0% 1171/com.xiaomi.channel:pushservice: 0% user + 0% kernel / faults: 1 minor
0% 1207/com.xiaomi.channel: 0% user + 0% kernel / faults: 1 minor
0% 32705/kworker/0:1: 0% user + 0% kernel
12% TOTAL: 3.2% user + 9.4% kernel + 0% iowait
Latitudes range from -90 to +90 (degrees), so DECIMAL(10, 8) is ok for that
longitudes range from -180 to +180 (degrees) so you need DECIMAL(11, 8).
Note: The first number is the total number of digits stored, and the second is the number after the decimal point.
In short: lat DECIMAL(10, 8) NOT NULL, lng DECIMAL(11, 8) NOT NULL
Below are the working steps without the need for any external modules:
Step 1: Create a module in your app.
E.g, lets assume we have an app called user_registration_app. Explore user_registration_app and create a new file.
Lets call this as custom_cors_middleware.py
Paste the below Class definition:
class CustomCorsMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
response = self.get_response(request)
response["Access-Control-Allow-Origin"] = "*"
response["Access-Control-Allow-Headers"] = "*"
# Code to be executed for each request/response after
# the view is called.
return response
Step 2: Register a middleware
In your projects settings.py file, add this line
'user_registration_app.custom_cors_middleware.CustomCorsMiddleware'
E.g:
MIDDLEWARE = [
'user_registration_app.custom_cors_middleware.CustomCorsMiddleware', # ADD THIS LINE BEFORE CommonMiddleware
...
'django.middleware.common.CommonMiddleware',
]
Remember to replace user_registration_app with the name of your app where you have created your custom_cors_middleware.py module.
You can now verify it will add the required response headers to all the views in the project!
Sticking to the method you are using to insert it, use
list[:0] = ['foo']
http://docs.python.org/release/2.6.6/library/stdtypes.html#mutable-sequence-types
If you use Mercurial, you can use the built in HTTP server. In the folder you wish to serve up:
hg serve
From the docs:
export the repository via HTTP
Start a local HTTP repository browser and pull server.
By default, the server logs accesses to stdout and errors to
stderr. Use the "-A" and "-E" options to log to files.
options:
-A --accesslog name of access log file to write to
-d --daemon run server in background
--daemon-pipefds used internally by daemon mode
-E --errorlog name of error log file to write to
-p --port port to listen on (default: 8000)
-a --address address to listen on (default: all interfaces)
--prefix prefix path to serve from (default: server root)
-n --name name to show in web pages (default: working dir)
--webdir-conf name of the webdir config file (serve more than one repo)
--pid-file name of file to write process ID to
--stdio for remote clients
-t --templates web templates to use
--style template style to use
-6 --ipv6 use IPv6 in addition to IPv4
--certificate SSL certificate file
use "hg -v help serve" to show global options
try this too
pd.set_option("max_columns", None) # show all cols
pd.set_option('max_colwidth', None) # show full width of showing cols
pd.set_option("expand_frame_repr", False) # print cols side by side as it's supposed to be
If you've opened a table and you want to clear an existing value to NULL, click on the value, and press Ctrl
+0
.
I would recommend creating a TNSNAMES.ORA file. From your Oracle Client install directory, navigate to NETWORK\ADMIN. You may already have a file called TNSNAMES.ORA, if so edit it, else create it using your favorite text editor.
Next, simply add an entry like this:
MYDB =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = 123.45.67.89)(PORT = 1521))
(CONNECT_DATA = (SID = TEST)(SERVER = DEDICATED))
)
You can change MYDB to whatever you like, this is the identifier that applications will will use to find the database using the info from TNSNAMES.
Finally, login with MYDB as your database in PL/SQL Developer. It should automatically find the connection string in the TNSNAMES.ORA.
If that does not work, hit Help->About then click the icon with an "i" in it in the upper-lefthand corner. The fourth tab is the "TNS Names" tab, check it to confirm that it is loading the proper TNSNAMES.ORA file. If it is not, you may have multiple Oracle installations on your computer, and you will need to find the one that is in use.
By using
$_SERVER['REQUEST_METHOD']
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// The request is using the POST method
}
For more details please see the documentation for the $_SERVER variable.
mysql client can detect the output fd, if the fd is S_IFIFO(pipe) then don't output ASCII TABLES, if the fd is character device(S_IFCHR) then output ASCII TABLES.
you can use --table to force output the ASCII TABLES like:
$mysql -t -N -h127.0.0.1 -e "select id from sbtest1 limit 1" | cat
+--------+
| 100024 |
+--------+
-t, --table Output in table format.
For those who are still unable to get it working, try the following in addition to the method provided by @CallMeBob.
Remove the semicolon for this line:
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"
Add a semicolon for this line:
sendmail_path="C:\xampp\mailtodisk\mailtodisk.exe"
Note:
** smtp_port must tally with your those written in your php code.
** Remember to change your-gmail-username and your-gmail-password to whichever account you are using.
**
Hope this helps! :)
You may use str.isdigit()
and str.isalpha()
to check whether given string is positive integer and alphabet respectively.
Sample Results:
# For alphabet
>>> 'A'.isdigit()
False
>>> 'A'.isalpha()
True
# For digit
>>> '1'.isdigit()
True
>>> '1'.isalpha()
False
str.isdigit()
returns False
if the string is a negative number or a float number. For example:
# returns `False` for float
>>> '123.3'.isdigit()
False
# returns `False` for negative number
>>> '-123'.isdigit()
False
If you want to also check for the negative integers and float
, then you may write a custom function to check for it as:
def is_number(n):
try:
float(n) # Type-casting the string to `float`.
# If string is not a valid `float`,
# it'll raise `ValueError` exception
except ValueError:
return False
return True
Sample Run:
>>> is_number('123') # positive integer number
True
>>> is_number('123.4') # positive float number
True
>>> is_number('-123') # negative integer number
True
>>> is_number('-123.4') # negative `float` number
True
>>> is_number('abc') # `False` for "some random" string
False
The above functions will return True
for the "NAN" (Not a number) string because for Python it is valid float representing it is not a number. For example:
>>> is_number('NaN')
True
In order to check whether the number is "NaN", you may use math.isnan()
as:
>>> import math
>>> nan_num = float('nan')
>>> math.isnan(nan_num)
True
Or if you don't want to import additional library to check this, then you may simply check it via comparing it with itself using ==
. Python returns False
when nan
float is compared with itself. For example:
# `nan_num` variable is taken from above example
>>> nan_num == nan_num
False
Hence, above function is_number
can be updated to return False
for "NaN"
as:
def is_number(n):
is_number = True
try:
num = float(n)
# check for "nan" floats
is_number = num == num # or use `math.isnan(num)`
except ValueError:
is_number = False
return is_number
Sample Run:
>>> is_number('Nan') # not a number "Nan" string
False
>>> is_number('nan') # not a number string "nan" with all lower cased
False
>>> is_number('123') # positive integer
True
>>> is_number('-123') # negative integer
True
>>> is_number('-1.12') # negative `float`
True
>>> is_number('abc') # "some random" string
False
The above function will still return you False
for the complex numbers. If you want your is_number
function to treat complex numbers as valid number, then you need to type cast your passed string to complex()
instead of float()
. Then your is_number
function will look like:
def is_number(n):
is_number = True
try:
# v type-casting the number here as `complex`, instead of `float`
num = complex(n)
is_number = num == num
except ValueError:
is_number = False
return is_number
Sample Run:
>>> is_number('1+2j') # Valid
True # : complex number
>>> is_number('1+ 2j') # Invalid
False # : string with space in complex number represetantion
# is treated as invalid complex number
>>> is_number('123') # Valid
True # : positive integer
>>> is_number('-123') # Valid
True # : negative integer
>>> is_number('abc') # Invalid
False # : some random string, not a valid number
>>> is_number('nan') # Invalid
False # : not a number "nan" string
PS: Each operation for each check depending on the type of number comes with additional overhead. Choose the version of is_number
function which fits your requirement.
There might be something wrong with your formula if you are looking from another sheet maybe you have to change Sheet1 to Sheet2 ---> =VLOOKUP(M3,Sheet2!$A$2:$Q$47,13,FALSE) --- Where Sheet2 is your table array
simply include parsley.js file in your document and in input element of mobile number enter this
data-parsley-type= "number" data-parsley-length="[10,10]" data-parsley-length-message= "Enter a Mobile Number"
you can change the message according to your requirement you also need to initialize parsley.js file in your document by writing
<script type="text/javascript">
$(document).ready(function() {
$('form').parsley();
});
</script>
---above code in your document.***
You seem to have used some [Authorize]
attribute on your Web API controller action and I don't see how this is relevant to your question.
So, let's get into practice. Here's a how a trivial Web API controller might look like:
public class TestController : ApiController
{
public string Post([FromBody] string value)
{
return value;
}
}
and a consumer for that matter:
class Program
{
static void Main()
{
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
var data = "=Short test...";
var result = client.UploadString("http://localhost:52996/api/test", "POST", data);
Console.WriteLine(result);
}
}
}
You will undoubtedly notice the [FromBody]
decoration of the Web API controller attribute as well as the =
prefix of the POST data om the client side. I would recommend you reading about how does the Web API does parameter binding to better understand the concepts.
As far as the [Authorize]
attribute is concerned, this could be used to protect some actions on your server from being accessible only to authenticated users. Actually it is pretty unclear what you are trying to achieve here.You should have made this more clear in your question by the way. Are you are trying to understand how parameter bind works in ASP.NET Web API (please read the article I've linked to if this is your goal) or are attempting to do some authentication and/or authorization? If the second is your case you might find the following post
that I wrote on this topic interesting to get you started.
And if after reading the materials I've linked to, you are like me and say to yourself, WTF man, all I need to do is POST a string to a server side endpoint and I need to do all of this? No way. Then checkout ServiceStack. You will have a good base for comparison with Web API. I don't know what the dudes at Microsoft were thinking about when designing the Web API, but come on, seriously, we should have separate base controllers for our HTML (think Razor) and REST stuff? This cannot be serious.
I prefer the Task completedTask = Task.CompletedTask;
solution of .Net 4.6, but another approach is to mark the method async and return void:
public async Task WillBeLongRunningAsyncInTheMajorityOfImplementations()
{
}
You'll get a warning (CS1998 - Async function without await expression), but this is safe to ignore in this context.
I do it like this:
.hidden-text {
left: 100%;
display: inline-block;
position: fixed;
}
Nope. Once the event has been canceled, it is canceled.
You can re-fire the event later on though, using a flag to determine whether your custom code has already run or not - such as this (please ignore the blatant namespace pollution):
var lots_of_stuff_already_done = false;
$('.button').on('click', function(e) {
if (lots_of_stuff_already_done) {
lots_of_stuff_already_done = false; // reset flag
return; // let the event bubble away
}
e.preventDefault();
// do lots of stuff
lots_of_stuff_already_done = true; // set flag
$(this).trigger('click');
});
A more generalized variant (with the added benefit of avoiding the global namespace pollution) could be:
function onWithPrecondition(callback) {
var isDone = false;
return function(e) {
if (isDone === true)
{
isDone = false;
return;
}
e.preventDefault();
callback.apply(this, arguments);
isDone = true;
$(this).trigger(e.type);
}
}
Usage:
var someThingsThatNeedToBeDoneFirst = function() { /* ... */ } // do whatever you need
$('.button').on('click', onWithPrecondition(someThingsThatNeedToBeDoneFirst));
Bonus super-minimalistic jQuery plugin with Promise
support:
(function( $ ) {
$.fn.onButFirst = function(eventName, /* the name of the event to bind to, e.g. 'click' */
workToBeDoneFirst, /* callback that must complete before the event is re-fired */
workDoneCallback /* optional callback to execute before the event is left to bubble away */) {
var isDone = false;
this.on(eventName, function(e) {
if (isDone === true) {
isDone = false;
workDoneCallback && workDoneCallback.apply(this, arguments);
return;
}
e.preventDefault();
// capture target to re-fire event at
var $target = $(this);
// set up callback for when workToBeDoneFirst has completed
var successfullyCompleted = function() {
isDone = true;
$target.trigger(e.type);
};
// execute workToBeDoneFirst callback
var workResult = workToBeDoneFirst.apply(this, arguments);
// check if workToBeDoneFirst returned a promise
if (workResult && $.isFunction(workResult.then))
{
workResult.then(successfullyCompleted);
}
else
{
successfullyCompleted();
}
});
return this;
};
}(jQuery));
Usage:
$('.button').onButFirst('click',
function(){
console.log('doing lots of work!');
},
function(){
console.log('done lots of work!');
});
Make sure you image is a relative path such as:
@Url.Content("~/Content/images/myimage.png")
MVC4
<img src="~/Content/images/myimage.png" />
You could convert the byte[]
into a Base64
string
on the fly.
string base64String = Convert.ToBase64String(imageBytes);
<img src="@String.Format("data:image/png;base64,{0}", base64string)" />
@Egemen Hamutçu s answer in kotlin B-)
private fun isAppInstalled(context: Context, uri: String): Boolean {
val packageInfoList = context.packageManager.getInstalledPackages(PackageManager.GET_ACTIVITIES)
return packageInfoList.asSequence().filter { it?.packageName == uri }.any()
}
Recently I had same issue for an error in the flex slider. The first image's height was set smaller due to the loading delay. I tried the following method for resolving that issue and it's worked.
// create image with a reference id. Id shall be used for removing it from the dom later.
var tempImg = $('<img id="testImage" />');
//If you want to get the height with respect to any specific width you set.
//I used window width here.
tempImg.css('width', window.innerWidth);
tempImg[0].onload = function () {
$(this).css('height', 'auto').css('display', 'none');
var imgHeight = $(this).height();
// Remove it if you don't want this image anymore.
$('#testImage').remove();
}
//append to body
$('body').append(tempImg);
//Set an image url. I am using an image which I got from google.
tempImg[0].src ='http://aspo.org/wp-content/uploads/strips.jpg';
This will give you the height with respect to the width you set rather than original width or Zero.
Can be done with a simple Perl one liner.
my @in=qw(1 3 4 6 2 4 3 2 6 3 2 3 4 4 3 2 5 5 32 3); #Sample data
my @out=keys %{{ map{$_=>1}@in}}; # Perform PFM
print join ' ', sort{$a<=>$b} @out;# Print data back out sorted and in order.
The PFM block does this:
Data in @in is fed into MAP. MAP builds an anonymous hash. Keys are extracted from the hash and feed into @out
e.preventDefault();
with jquery ui
For me this problem occured with the click method override on a jquery ui button, causing a page reload on click by default.
You could create a unique index with a coalesce on the MenuId:
CREATE UNIQUE INDEX
Favorites_UniqueFavorite ON Favorites
(UserId, COALESCE(MenuId, '00000000-0000-0000-0000-000000000000'), RecipeId);
You'd just need to pick a UUID for the COALESCE that will never occur in "real life". You'd probably never see a zero UUID in real life but you could add a CHECK constraint if you are paranoid (and since they really are out to get you...):
alter table Favorites
add constraint check
(MenuId <> '00000000-0000-0000-0000-000000000000')
Yes you can use the for-each loop,
To do that you have to maintain a separate list to hold removing items and then remove that list from names list using removeAll()
method,
List<String> names = ....
// introduce a separate list to hold removing items
List<String> toRemove= new ArrayList<String>();
for (String name : names) {
// Do something: perform conditional checks
toRemove.add(name);
}
names.removeAll(toRemove);
// now names list holds expected values
I use Spring Boot, my solution to the problem was
"src/main/resources/myfile.extension"
Hope it helps someone.
The query below will result in dd/mm/yy
format.
select LEFT(convert(varchar(10), @date, 103),6) + Right(Year(@date)+ 1,2)
You can add a launch screen file that appears to work for multiple screen sizes. I just added the MainStoryboard as a launch screen file and that stopped the app from scaling. I think I will need to add a permanent launch screen later, but that got the native resolution up and working quickly. In Xcode, go to your target, general and add the launch screen file there.
Check this out:
XAML:
<DataGrid Name="DataGrid1">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Click="ChangeText">Show/Hide</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Method:
private void ChangeText(object sender, RoutedEventArgs e)
{
DemoModel model = (sender as Button).DataContext as DemoModel;
model.DynamicText = (new Random().Next(0, 100).ToString());
}
Class:
class DemoModel : INotifyPropertyChanged
{
protected String _text;
public String Text
{
get { return _text; }
set { _text = value; RaisePropertyChanged("Text"); }
}
protected String _dynamicText;
public String DynamicText
{
get { return _dynamicText; }
set { _dynamicText = value; RaisePropertyChanged("DynamicText"); }
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(String propertyName)
{
PropertyChangedEventHandler temp = PropertyChanged;
if (temp != null)
{
temp(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Initialization Code:
ObservableCollection<DemoModel> models = new ObservableCollection<DemoModel>();
models.Add(new DemoModel() { Text = "Some Text #1." });
models.Add(new DemoModel() { Text = "Some Text #2." });
models.Add(new DemoModel() { Text = "Some Text #3." });
models.Add(new DemoModel() { Text = "Some Text #4." });
models.Add(new DemoModel() { Text = "Some Text #5." });
DataGrid1.ItemsSource = models;