Assuming you really mean easiest and are not necessarily looking for a way to do this programmatically, you can do this:
Add, if not already there, a row of "column Musicians" to the spreadsheet. That is, if you have data in columns such as:
Rory Gallagher Guitar
Gerry McAvoy Bass
Rod de'Ath Drums
Lou Martin Keyboards
Donkey Kong Sioux Self-Appointed Semi-official Stomper
Note: you might want to add "Musician" and "Instrument" in row 0 (you might have to insert a row there)
Save the file as a CSV file.
Copy the contents of the CSV file to the clipboard
Verify that the "First row is column names" checkbox is checked
Paste the CSV data into the content area
Mash the "Convert CSV to JSON" button
With the data shown above, you will now have:
[
{
"MUSICIAN":"Rory Gallagher",
"INSTRUMENT":"Guitar"
},
{
"MUSICIAN":"Gerry McAvoy",
"INSTRUMENT":"Bass"
},
{
"MUSICIAN":"Rod D'Ath",
"INSTRUMENT":"Drums"
},
{
"MUSICIAN":"Lou Martin",
"INSTRUMENT":"Keyboards"
}
{
"MUSICIAN":"Donkey Kong Sioux",
"INSTRUMENT":"Self-Appointed Semi-Official Stomper"
}
]
With this simple/minimalistic data, it's probably not required, but with large sets of data, it can save you time and headache in the proverbial long run by checking this data for aberrations and abnormalcy.
Go here: http://jsonlint.com/
Paste the JSON into the content area
Pres the "Validate" button.
If the JSON is good, you will see a "Valid JSON" remark in the Results section below; if not, it will tell you where the problem[s] lie so that you can fix it/them.
SPSS can also read .dta files and export them to .csv, but that costs money. PSPP, an open source version of SPSS, which is rough, might also be able to read/export .dta files.
Make sure you read SilverlightFox's answer. It highlights a more important reason.
The reason is mostly that if you know the source of a request you may want to customize it a little bit.
For instance lets say you have a website which has many recipes. And you use a custom jQuery framework to slide recipes into a container based on a link they click.
The link may be www.example.com/recipe/apple_pie
Now normally that returns a full page, header, footer, recipe content and ads. But if someone is browsing your website some of those parts are already loaded. So you can use an AJAX to get the recipe the user has selected but to save time and bandwidth don't load the header/footer/ads.
Now you can just write a secondary endpoint for the data like www.example.com/recipe_only/apple_pie
but that's harder to maintain and share to other people.
But it's easier to just detect that it is an ajax request making the request and then returning only a part of the data. That way the user wastes less bandwidth and the site appears more responsive.
The frameworks just add the header because some may find it useful to keep track of which requests are ajax and which are not. But it's entirely dependent on the developer to use such techniques.
It's actually kind of similar to the Accept-Language
header. A browser can request a website please show me a Russian version of this website without having to insert /ru/ or similar in the URL.
You could do this on the ASPX HTML front end to make the button go to a new tab to show page in your ASP.NET site dynamically:
<asp:Button ID="btnNewEntry" CssClass="button" OnClientClick="window.open('https://website','_blank'); return false;" text="WebsiteName" runat="server" />
r = list(qs[:1])
if r:
return r[0]
return None
See an example here: http://www.cplusplus.com/reference/stl/vector/insert/ eg.:
...
vector::iterator iterator1;
iterator1= vec1.begin();
vec1.insert ( iterator1+i , vec2[i] );
// This means that at position "i" from the beginning it will insert the value from vec2 from position i
Your first approach was replacing the values from vec1[i] with the values from vec2[i]
Default Activity name changed (like SplashActivity -> SplashActivity1) and work for me
How about this one? The idea was to use only one loop. And, who knows, maybe you're using only IList implementations thorough your code and you don't want to cast to List.
private IEnumerable<IList<T>> SplitList<T>(IList<T> list, int totalChunks)
{
IList<T> auxList = new List<T>();
int totalItems = list.Count();
if (totalChunks <= 0)
{
yield return auxList;
}
else
{
for (int i = 0; i < totalItems; i++)
{
auxList.Add(list[i]);
if ((i + 1) % totalChunks == 0)
{
yield return auxList;
auxList = new List<T>();
}
else if (i == totalItems - 1)
{
yield return auxList;
}
}
}
}
Assuming you are using this plugin, you are misusing the .set
method. .set
must be passed the name of the key as a string as well as the value. I suppose you meant to write:
$.session.set("userName", $("#uname").val());
This sets the userName
key in session storage to the value of the input, and allows you to retrieve it using:
$.session.get('userName');
CSS Gallery has variety of Time Pickers. Have a look.
Perifer Design's time picker is similar to google one
You need to add a vertical-align
property to your two child div's.
If .small
is always shorter, you need only apply the property to .small
.
However, if either could be tallest then you should apply the property to both .small
and .big
.
.container{
border: 1px black solid;
width: 320px;
height: 120px;
}
.small{
display: inline-block;
width: 40%;
height: 30%;
border: 1px black solid;
background: aliceblue;
vertical-align: top;
}
.big {
display: inline-block;
border: 1px black solid;
width: 40%;
height: 50%;
background: beige;
vertical-align: top;
}
Vertical align affects inline or table-cell box's, and there are a large nubmer of different values for this property. Please see https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align for more details.
Mirko Froehlich's answer worked for me, except when i wanted to use custom colors. The trick is to specify UI color with Hue, saturation and brightness instead of RGB.
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = myView.bounds;
UIColor *startColour = [UIColor colorWithHue:.580555 saturation:0.31 brightness:0.90 alpha:1.0];
UIColor *endColour = [UIColor colorWithHue:.58333 saturation:0.50 brightness:0.62 alpha:1.0];
gradient.colors = [NSArray arrayWithObjects:(id)[startColour CGColor], (id)[endColour CGColor], nil];
[myView.layer insertSublayer:gradient atIndex:0];
To get the Hue, Saturation and Brightness of a color, use the in built xcode color picker and go to the HSB tab. Hue is measured in degrees in this view, so divide the value by 360 to get the value you will want to enter in code.
Thanks Aakash for recommending JIDE MultilineLabel. JIDE's StyledLabel is also enhanced recently to support multiple line. I would recommend it over the MultilineLabel as it has many other great features. You can check out an article on StyledLabel below. It is still free and open source.
Use the open function to open the file. The open function returns a file object, which you can use the read and write to files:
file_input = open('input.txt') #opens a file in reading mode
file_output = open('output.txt') #opens a file in writing mode
data = file_input.read(1024) #read 1024 bytes from the input file
file_output.write(data) #write the data to the output file
If you are using SQL Server, Use the LEN
(Length) function:
SELECT EmployeeName FROM EmployeeTable WHERE LEN(EmployeeName) > 4
MSDN for it states:
Returns the number of characters of the specified string expression,
excluding trailing blanks.
For oracle/plsql you can use Length()
, mysql also uses Length.
Here is the Oracle documentation:
http://www.techonthenet.com/oracle/functions/length.php
And here is the mySQL Documentation of Length(string)
:
http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_length
For PostgreSQL, you can use length(string)
or char_length(string)
. Here is the PostgreSQL documentation:
http://www.postgresql.org/docs/current/static/functions-string.html#FUNCTIONS-STRING-SQL
You cannot directly see the query result using mysql_query its only fires the query in mysql nothing else.
For getting the result you have to add a lil things in your script like
require_once('db.php');
$sql="SELECT * FROM modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) ) FROM modul1open) ORDER BY idM1O LIMIT 1";
$result = mysql_query($sql);
//echo [$result];
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
print_r($row);
}
This will give you result;
I am doing the below for page redirection(from login to home page). I have to pass the user object also to the home page. so, i am using windows localstorage.
$http({
url:'/login/user',
method : 'POST',
headers: {
'Content-Type': 'application/json'
},
data: userData
}).success(function(loginDetails){
$scope.updLoginDetails = loginDetails;
if($scope.updLoginDetails.successful == true)
{
loginDetails.custId = $scope.updLoginDetails.customerDetails.cust_ID;
loginDetails.userName = $scope.updLoginDetails.customerDetails.cust_NM;
window.localStorage.setItem("loginDetails", JSON.stringify(loginDetails));
$window.location='/login/homepage';
}
else
alert('No access available.');
}).error(function(err,status){
alert('No access available.');
});
And it worked for me.
If you want a variable to be accessible across the entire page, it works well to define it at the top of the file. (You can use either an implicit or explicit type.)
@{
// implicit type
var something1 = "something";
// explicit type
string something2 = "something";
}
<div>@something1</div> @*display first variable*@
<div>@something2</div> @*display second variable*@
Every recovery model lets you back up a whole or partial SQL Server database or individual files or filegroups of the database. Table-level backups cannot be created.
Updated for Swift :
Used below code for Email, Name, Mobile and Password Validation;
// Name validation
func isValidName(_ nameString: String) -> Bool {
var returnValue = true
let mobileRegEx = "[A-Za-z]{2}" // "^[A-Z0-9a-z.-_]{5}$"
do {
let regex = try NSRegularExpression(pattern: mobileRegEx)
let nsString = nameString as NSString
let results = regex.matches(in: nameString, range: NSRange(location: 0, length: nsString.length))
if results.count == 0
{
returnValue = false
}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
returnValue = false
}
return returnValue
}
// password validation
func isValidPassword(_ PasswordString: String) -> Bool {
var returnValue = true
let mobileRegEx = "[A-Za-z0-9.-_@#$!%&*]{5,15}$" // "^[A-Z0-9a-z.-_]{5}$"
do {
let regex = try NSRegularExpression(pattern: mobileRegEx)
let nsString = PasswordString as NSString
let results = regex.matches(in: PasswordString, range: NSRange(location: 0, length: nsString.length))
if results.count == 0
{
returnValue = false
}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
returnValue = false
}
return returnValue
}
// email validaton
func isValidEmailAddress(_ emailAddressString: String) -> Bool {
var returnValue = true
let emailRegEx = "[A-Z0-9a-z.-_]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,3}"
do {
let regex = try NSRegularExpression(pattern: emailRegEx)
let nsString = emailAddressString as NSString
let results = regex.matches(in: emailAddressString, range: NSRange(location: 0, length: nsString.length))
if results.count == 0
{
returnValue = false
}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
returnValue = false
}
return returnValue
}
// mobile no. validation
func isValidPhoneNumber(_ phoneNumberString: String) -> Bool {
var returnValue = true
// let mobileRegEx = "^[789][0-9]{9,11}$"
let mobileRegEx = "^[0-9]{10}$"
do {
let regex = try NSRegularExpression(pattern: mobileRegEx)
let nsString = phoneNumberString as NSString
let results = regex.matches(in: phoneNumberString, range: NSRange(location: 0, length: nsString.length))
if results.count == 0
{
returnValue = false
}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
returnValue = false
}
return returnValue
}
//How to use?
let isFullNameValid = isValidName("ray")
if isFullNameValid{
print("Valid name...")
}else{
print("Invalid name...")
}
Execute this on the file:
awk 'ORS=NR%3?" ":"\n"' filename
and you'll get what you're looking for.
For some picky web services, the request needs to have the content type set to JSON and the body to be a JSON string. For example:
Invoke-WebRequest -UseBasicParsing http://example.com/service -ContentType "application/json" -Method POST -Body "{ 'ItemID':3661515, 'Name':'test'}"
or the equivalent for XML, etc.
By default, docker uses AF_INET6 sockets which can be used for both IPv4 and IPv6 connections. This causes netstat to report an IPv6 address for the listening address.
From RedHat https://access.redhat.com/solutions/3114021
If you need one tick every N=3 ticks :
N = 3 # 1 tick every 3
xticks_pos, xticks_labels = plt.xticks() # get all axis ticks
myticks = [i for i,j in enumerate(xticks_pos) if not i%N] # index of selected ticks
(obviously you can adjust the offset with (i+offset)%N
).
Note that you can get uneven ticks if you wish, e.g. myticks = [1, 3, 8]
.
Then you can use
plt.gca().set_xticks(myticks) # set new X axis ticks
or if you want to replace labels as well
plt.xticks(myticks, newlabels) # set new X axis ticks and labels
Beware that axis limits must be set after the axis ticks.
Finally, you may wish to draw only a given set of ticks :
mylabels = ['03/2018', '09/2019', '10/2020']
plt.draw() # needed to populate xticks with actual labels
xticks_pos, xticks_labels = plt.xticks() # get all axis ticks
myticks = [i for i,j in enumerate(b) if j.get_text() in mylabels]
plt.xticks(myticks, mylabels)
(assuming mylabels
is ordered ; if it is not, then sort myticks
and reorder it).
This version is based on the initially proposed by bryanmac function which uses promises, better error handling, and is rewritten in ES6.
let http = require("http"),
https = require("https");
/**
* getJSON: REST get request returning JSON object(s)
* @param options: http options object
*/
exports.getJSON = function (options) {
console.log('rest::getJSON');
let reqHandler = +options.port === 443 ? https : http;
return new Promise((resolve, reject) => {
let req = reqHandler.request(options, (res) => {
let output = '';
console.log('rest::', options.host + ':' + res.statusCode);
res.setEncoding('utf8');
res.on('data', function (chunk) {
output += chunk;
});
res.on('end', () => {
try {
let obj = JSON.parse(output);
// console.log('rest::', obj);
resolve({
statusCode: res.statusCode,
data: obj
});
}
catch (err) {
console.error('rest::end', err);
reject(err);
}
});
});
req.on('error', (err) => {
console.error('rest::request', err);
reject(err);
});
req.end();
});
};
As a result you don't have to pass in a callback function, instead getJSON() returns a promise. In the following example the function is used inside of an ExpressJS route handler
router.get('/:id', (req, res, next) => {
rest.getJSON({
host: host,
path: `/posts/${req.params.id}`,
method: 'GET'
}).then(({ statusCode, data }) => {
res.json(data);
}, (error) => {
next(error);
});
});
On error it delegates the error to the server error handling middleware.
In my case, setting url: ''
in ajax settings would result in a status code 0 in ie8.. It seems ie just doesn't tolerate such a setting.
None of the replies so far deal with filenames with newlines properly (except for ChristopheD's, which just came in as I was typing this). The following is not a shell one-liner, but works, and is reasonably fast.
import os, sys
def names(roots):
for root in roots:
for a, b, basenames in os.walk(root):
for basename in basenames:
yield basename
sufs = set(os.path.splitext(x)[1] for x in names(sys.argv[1:]))
for suf in sufs:
if suf:
print suf
Firstly generate getter and setter using below parsing site
http://www.jsonschema2pojo.org/
Now use Gson
GettetSetterClass object=new Gson().fromjson(jsonLine, GettetSetterClass.class);
Now use object to get values such as data,translationText
It seems that this may be the answer you're looking for, I haven't tried this personally yet, but it seems like it may do the trick. With this command GIT will try to apply the changes as they were before, without trying to add all of them for commit.
git stash apply --index
here is the full explanation:
Is this what you meant to do ?
In [7]: x = pd.DataFrame({'one' : ['one', 'two', 'This is very long string very long string very long string veryvery long string']})
In [8]: x
Out[8]:
one
0 one
1 two
2 This is very long string very long string very...
In [9]: x['one'][2]
Out[9]: 'This is very long string very long string very long string veryvery long string'
if let index = self.navigationController?.viewControllers.index(where: { $0 is MyViewController }) {
let vc = self.navigationController?.viewControllers[vcIndex] as! MyViewController
self.navigationController?.popToViewController(vc, animated: true)
} else {
self.navigationController?.popToRootViewController(animated: true)
}
Without moment.js:
var time_to_show = 1509968436; // unix timestamp in seconds_x000D_
_x000D_
var t = new Date(time_to_show * 1000);_x000D_
var formatted = ('0' + t.getHours()).slice(-2) + ':' + ('0' + t.getMinutes()).slice(-2);_x000D_
_x000D_
document.write(formatted);
_x000D_
forEach() :
return value : undefined
originalArray : not modified after the method call
newArray is not created after the end of method call.
map() :
return value : new Array populated with the results of calling a provided function on every element in the calling array
originalArray : not modified after the method call
newArray is created after the end of method call.
Since map builds a new array, using it when you aren't using the
returned array is an anti-pattern; use forEach or for-of instead.
import cv2
img=cv2.imread('my_test.jpg')
img_info = img.shape
print("Image height :",img_info[0])
print("Image Width :", img_info[1])
print("Image channels :", img_info[2])
My_test.jpg link ---> https://i.pinimg.com/originals/8b/ca/f5/8bcaf5e60433070b3210431e9d2a9cd9.jpg
Always use the printf
family of functions for this. Even if you want to get the value as a float, you're best off using snprintf
to get the rounded value as a string and then parsing it back with atof
:
#include <math.h>
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
double dround(double val, int dp) {
int charsNeeded = 1 + snprintf(NULL, 0, "%.*f", dp, val);
char *buffer = malloc(charsNeeded);
snprintf(buffer, charsNeeded, "%.*f", dp, val);
double result = atof(buffer);
free(buffer);
return result;
}
I say this because the approach shown by the currently top-voted answer and several others here - multiplying by 100, rounding to the nearest integer, and then dividing by 100 again - is flawed in two ways:
To illustrate the first kind of error - the rounding direction sometimes being wrong - try running this program:
int main(void) {
// This number is EXACTLY representable as a double
double x = 0.01499999999999999944488848768742172978818416595458984375;
printf("x: %.50f\n", x);
double res1 = dround(x, 2);
double res2 = round(100 * x) / 100;
printf("Rounded with snprintf: %.50f\n", res1);
printf("Rounded with round, then divided: %.50f\n", res2);
}
You'll see this output:
x: 0.01499999999999999944488848768742172978818416595459
Rounded with snprintf: 0.01000000000000000020816681711721685132943093776703
Rounded with round, then divided: 0.02000000000000000041633363423443370265886187553406
Note that the value we started with was less than 0.015, and so the mathematically correct answer when rounding it to 2 decimal places is 0.01. Of course, 0.01 is not exactly representable as a double, but we expect our result to be the double nearest to 0.01. Using snprintf
gives us that result, but using round(100 * x) / 100
gives us 0.02, which is wrong. Why? Because 100 * x
gives us exactly 1.5 as the result. Multiplying by 100 thus changes the correct direction to round in.
To illustrate the second kind of error - the result sometimes being wrong due to * 100
and / 100
not truly being inverses of each other - we can do a similar exercise with a very big number:
int main(void) {
double x = 8631192423766613.0;
printf("x: %.1f\n", x);
double res1 = dround(x, 2);
double res2 = round(100 * x) / 100;
printf("Rounded with snprintf: %.1f\n", res1);
printf("Rounded with round, then divided: %.1f\n", res2);
}
Our number now doesn't even have a fractional part; it's an integer value, just stored with type double
. So the result after rounding it should be the same number we started with, right?
If you run the program above, you'll see:
x: 8631192423766613.0
Rounded with snprintf: 8631192423766613.0
Rounded with round, then divided: 8631192423766612.0
Oops. Our snprintf
method returns the right result again, but the multiply-then-round-then-divide approach fails. That's because the mathematically correct value of 8631192423766613.0 * 100
, 863119242376661300.0
, is not exactly representable as a double; the closest value is 863119242376661248.0
. When you divide that back by 100, you get 8631192423766612.0
- a different number to the one you started with.
Hopefully that's a sufficient demonstration that using roundf
for rounding to a number of decimal places is broken, and that you should use snprintf
instead. If that feels like a horrible hack to you, perhaps you'll be reassured by the knowledge that it's basically what CPython does.
what about simply constructing your frame from a standard list ?
frame = bytes([0xA2,0x01,0x02,0x03,0x04])
the bytes()
constructor can build a byte frame from an iterable containing int
values. an iterable is anything which implements the iterator protocol: an list, an iterator, an iterable object like what is returned by range()
...
In case if you have an autoconfig URL -
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("network.proxy.type", 2);
firefoxProfile.setPreference("network.proxy.autoconfig_url", "http://www.etc.com/wpad.dat");
firefoxProfile.setPreference("network.proxy.no_proxies_on", "localhost");
WebDriver driver = new FirefoxDriver(firefoxProfile);
You can use the LocalForward
directive in your host yam
section of ~/.ssh/config
:
LocalForward 5901 computer.myHost.edu:5901
ALL_SOURCE describes the text source of the stored objects accessible to the current user.
Here is one of the solution
select * from ALL_SOURCE where text like '%some string%';
You need to add the URL to your app:
That's all and you are done. Make sure that the app's URL is the same from where you're logging in.
#!/bin/bash
word=$(echo 'Your Message' |fold -w 1)
for letter in ${word} ; do echo "${letter} is a letter"; done
Here is the output:
Y is a letter o is a letter u is a letter r is a letter M is a letter e is a letter s is a letter s is a letter a is a letter g is a letter e is a letter
SELECT object_definition (OBJECT_ID(N'dbo.vEmployee'))
In case of Spring Boot and @EnableResourceServer
, it is relatively easy and convenient to extend ResourceServerConfigurerAdapter
instead of WebSecurityConfigurerAdapter
in the Java configuration and register a custom AuthenticationEntryPoint
by overriding configure(ResourceServerSecurityConfigurer resources)
and using resources.authenticationEntryPoint(customAuthEntryPoint())
inside the method.
Something like this:
@Configuration
@EnableResourceServer
public class CommonSecurityConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.authenticationEntryPoint(customAuthEntryPoint());
}
@Bean
public AuthenticationEntryPoint customAuthEntryPoint(){
return new AuthFailureHandler();
}
}
There's also a nice OAuth2AuthenticationEntryPoint
that can be extended (since it's not final) and partially re-used while implementing a custom AuthenticationEntryPoint
. In particular, it adds "WWW-Authenticate" headers with error-related details.
Hope this will help someone.
I Set variables in onCreate(), save scroll position in onPause() and set scroll position in onResume()
public static int index = -1;
public static int top = -1;
LinearLayoutManager mLayoutManager;
@Override
public void onCreate(Bundle savedInstanceState)
{
//Set Variables
super.onCreate(savedInstanceState);
cRecyclerView = ( RecyclerView )findViewById(R.id.conv_recycler);
mLayoutManager = new LinearLayoutManager(this);
cRecyclerView.setHasFixedSize(true);
cRecyclerView.setLayoutManager(mLayoutManager);
}
@Override
public void onPause()
{
super.onPause();
//read current recyclerview position
index = mLayoutManager.findFirstVisibleItemPosition();
View v = cRecyclerView.getChildAt(0);
top = (v == null) ? 0 : (v.getTop() - cRecyclerView.getPaddingTop());
}
@Override
public void onResume()
{
super.onResume();
//set recyclerview position
if(index != -1)
{
mLayoutManager.scrollToPositionWithOffset( index, top);
}
}
I went through all the other solutions mentioned on this thread and didn't find anything that was working so I dinked around a little. The Google version of the API was failing on me for some reason. I changed it back to the vanilla and no more crashes.
I must have some other issue but maybe this will help somebody...
For non-servers this requires Remote Server Administration Tools for Windows __
Void is used as a keyword. The void pointer, also known as the generic pointer, is a special type of pointer that can be pointed at objects of any data type! A void pointer is declared like a normal pointer, using the void keyword as the pointer’s type:
General Syntax:
void* pointer_variable;
void *pVoid; // pVoid is a void pointer
A void pointer can point to objects of any data type:
int nValue;
float fValue;
struct Something
{
int nValue;
float fValue;
};
Something sValue;
void *pVoid;
pVoid = &nValue; // valid
pVoid = &fValue; // valid
pVoid = &sValue; // valid
However, because the void pointer does not know what type of object it is pointing to, it can not be dereferenced! Rather, the void pointer must first be explicitly cast to another pointer type before it is dereferenced.
int nValue = 5;
void *pVoid = &nValue;
// can not dereference pVoid because it is a void pointer
int *pInt = static_cast<int*>(pVoid); // cast from void* to int*
cout << *pInt << endl; // can dereference pInt
Source: link
There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml
. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml
mediatype.
I was not able to resolve this after several hours. Eventually I just did a select with the two tables joined, created an extract and created individual SQL update statements for the 500 rows in the table. Ugly but beats spending hours trying to get a query to work.
In Html5, you can now use
<form>
<input type="number" min="1" max="100">
</form>
None/Null is a data type of the class NoneType in pyspark/python so, Below will not work as you are trying to compare NoneType object with string object
Wrong way of filretingdf[df.dt_mvmt == None].count() 0 df[df.dt_mvmt != None].count() 0
df=df.where(col("dt_mvmt").isNotNull()) returns all records with dt_mvmt as None/Null
I have a Samsung Galaxy and I had the same issue as you. Here's how to fix it:
In device manager on your Windows PC, even though it might say the USB drivers are installed correctly, there may exist corruption.
I went into device manager and uninstalled SAMSUNG Android USB Composite Device and made sure to check the box 'delete driver software'. Now the device will have an exclamation mark etc. I right clicked and installed the driver again (refresh copy). This finally made adb acknowledge my phone as an emulator.
As others noted, for Nexus 4, you can also try this fix.
This self calling function will iterate over replacerItems using an index, and change replacerItems[index] globally on the string with each pass.
const replacerItems = ["a", "b", "c"];
function replacer(str, index){
const item = replacerItems[index];
const regex = new RegExp(`[${item}]`, "g");
const newStr = str.replace(regex, "z");
if (index < replacerItems.length - 1) {
return replacer(newStr, index + 1);
}
return newStr;
}
// console.log(replacer('abcdefg', 0)) will output 'zzzdefg'
<script>
//$(document).ready(function () {
function showcontent() {
document.getElementById("demo22").innerHTML = "Hello World";
}
//});// end of ready function
</script>
I had the same problem where onclick function calls would not work. I had included the function inside the usual "$(document).ready(function(){});" block used to wrap jquery scripts. Commenting this block out solved the problem.
if ( typeof query !== 'undefined' && query )
{
//do stuff if query is defined and not null
}
else
{
}
I suggest not using an array unless you have multiple objects to consider. There isn't anything wrong this statement:
var myMappings = {
"Name": 0.1,
"Phone": 0.1,
"Address": 0.5,
"Zip": 0.1,
"Comments": 0.2
};
for (var col in myMappings) {
alert((myMappings[col] * 100) + "%");
}
Within your component, you can define an array of number (ES6) as described below:
export class SampleComponent {
constructor() {
this.numbers = Array(5).fill(0).map((x,i)=>i);
}
}
See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.
You can then iterate over this array with ngFor
:
@View({
template: `
<ul>
<li *ngFor="let number of numbers">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
Or shortly:
@View({
template: `
<ul>
<li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
Hope it helps you, Thierry
Edit: Fixed the fill statement and template syntax.
For some odd reason, the "Game development with Unity" tool can become disabled in Visual Studio.
To fix this..
Credit to Yuli Levtov's answer on another Thread
https://github.com/cscott/jsshaper implements a translator from JavaScript 1.8 to ECMAScript 5.1, which would allow you to use 'for each' in code running on webkit or node.
You can set multiple background image in every view using custom method as below.
make plist for every theam with background image name and other color
#import <Foundation/Foundation.h>
@interface ThemeManager : NSObject
@property (nonatomic,strong) NSDictionary*styles;
+ (ThemeManager *)sharedManager;
-(void)selectTheme;
@end
#import "ThemeManager.h"
@implementation ThemeManager
@synthesize styles;
+ (ThemeManager *)sharedManager
{
static ThemeManager *sharedManager = nil;
if (sharedManager == nil)
{
sharedManager = [[ThemeManager alloc] init];
}
[sharedManager selectTheme];
return sharedManager;
}
- (id)init
{
if ((self = [super init]))
{
}
return self;
}
-(void)selectTheme{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *themeName = [defaults objectForKey:@"AppTheme"] ?: @"DefaultTheam";
NSString *path = [[NSBundle mainBundle] pathForResource:themeName ofType:@"plist"];
self.styles = [NSDictionary dictionaryWithContentsOfFile:path];
}
@end
Can use this via
NSDictionary *styles = [ThemeManager sharedManager].styles;
NSString *imageName = [styles objectForKey:@"backgroundImage"];
[imgViewBackGround setImage:[UIImage imageNamed:imageName]];
$('element[name="element_name"]').click(function(){
//do stuff
});
in your case:
$('input[name="btnName"]').click(function(){
//do stuff
});
if you are looking to change the colour of the cell in case of vlookup error then go for conditional formatting . To do this go the "CONDITIONAL FORMATTING" > "NEW RULE". In this choose the "Select the rule type" = "Format only cells that contains" . After this the window below changes , in which choose "Error" in the first drop-down .After this proceed accordingly.
Or if your exception is thrown from the constructor of a class:
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void myTest() {
exception.expect(MyException.class);
CustomClass myClass= mock(CustomClass.class);
doThrow(new MyException("constructor failed")).when(myClass);
}
I encountered this when using scrapy and fetching a zipped csvfile without having a correct middleware to unzip the response body before handing it to the csvreader. Hence the file was not really a csv file and threw the line contains NULL byte
error accordingly.
Step 1:
CREATE TABLE [DBO].T_EMPLOYEES_DETAILS ( Id int, Name nvarchar(50), Gender nvarchar(10), Salary int )
Step 2:
CREATE TYPE EmpInsertType AS TABLE ( Id int, Name nvarchar(50), Gender nvarchar(10), Salary int )
Step 3:
/* Must add READONLY keyword at end of the variable */
CREATE PROC PRC_EmpInsertType @EmployeeInsertType EmpInsertType READONLY AS BEGIN INSERT INTO [DBO].T_EMPLOYEES_DETAILS SELECT * FROM @EmployeeInsertType END
Step 4:
DECLARE @EmployeeInsertType EmpInsertType
INSERT INTO @EmployeeInsertType VALUES(1,'John','Male',50000) INSERT INTO @EmployeeInsertType VALUES(2,'Praveen','Male',60000) INSERT INTO @EmployeeInsertType VALUES(3,'Chitra','Female',45000) INSERT INTO @EmployeeInsertType VALUES(4,'Mathy','Female',6600) INSERT INTO @EmployeeInsertType VALUES(5,'Sam','Male',50000)
EXEC PRC_EmpInsertType @EmployeeInsertType
=======================================
SELECT * FROM T_EMPLOYEES_DETAILS
OUTPUT
1 John Male 50000
2 Praveen Male 60000
3 Chitra Female 45000
4 Mathy Female 6600
5 Sam Male 50000
For use in a /etc/hosts
file as a simple ad blocking technique to cause a domain to fail to resolve, the 0.0.0.0 address has been widely used because it causes the request to immediately fail without even trying, because it's not a valid or routable address. This is in comparison to using 127.0.0.1 in that place, where it will at least check to see if your own computer is listening on the requested port 80 before failing with 'connection refused.' Either of those addresses being used in the hosts file for the domain will stop any requests from being attempted over the actual network, but 0.0.0.0 has gained favor because it's more 'optimal' for the above reason. "127" IPs will attempt to hit your own computer, and any other IP will cause a request to be sent to the router to try to route it, but for 0.0.0.0 there's nowhere to even send a request to.
All that being said, having any IP listed in your hosts file for the domain to be blocked is sufficient, and you wouldn't need or want to also put an ipv6 address in your hosts file unless -- possibly -- you don't have ipv4 enabled at all. I'd be really surprised if that was the case, though. And still though, I think having the host appear in /etc/hosts with a bad ipv4 address when you don't have ipv4 enabled would still give you the result you are looking for which is for it to fail, instead of looking up the real DNS of say, adserver-example.com and getting back either a v4 or v6 IP.
Here a code that works with windows office 2010. This script will ask you for input filtered range of cells and then the paste range.
Please, both ranges should have the same number of cells.
Sub Copy_Filtered_Cells()
Dim from As Variant
Dim too As Variant
Dim thing As Variant
Dim cell As Range
'Selection.SpecialCells(xlCellTypeVisible).Select
'Set from = Selection.SpecialCells(xlCellTypeVisible)
Set temp = Application.InputBox("Copy Range :", Type:=8)
Set from = temp.SpecialCells(xlCellTypeVisible)
Set too = Application.InputBox("Select Paste range selected cells ( Visible cells only)", Type:=8)
For Each cell In from
cell.Copy
For Each thing In too
If thing.EntireRow.RowHeight > 0 Then
thing.PasteSpecial
Set too = thing.Offset(1).Resize(too.Rows.Count)
Exit For
End If
Next
Next
End Sub
Enjoy!
It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.
I've always used phpMailer's SMTP feature:
$mail->IsSMTP();
$mail->Host = "localhost";
And if you need debug info:
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
A random value?
If you want a random value, try
<?php
$value = mt_rand($min, $max);
mt_rand() will run a bit more random if you are using many random numbers in a row, or if you might ever execute the script more than once a second. In general, you should use mt_rand() over rand() if there is any doubt.
This worked for me.
Single-clicking a row triggers the code-behind.
XAML:
<ListView x:Name="MyListView" MouseLeftButtonUp="MyListView_MouseLeftButtonUp">
<GridView>
<!-- Declare GridViewColumns. -->
</GridView>
</ListView.View>
Code-behind:
private void MyListView_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
System.Windows.Controls.ListView list = (System.Windows.Controls.ListView)sender;
MyClass selectedObject = (MyClass)list.SelectedItem;
// Do stuff with the selectedObject.
}
Just re-posting answer by oleynikd because it's simple and neat
Bundle bundle = ActivityOptionsCompat.makeCustomAnimation(getContext(),
android.R.anim.fade_in, android.R.anim.fade_out).toBundle();
startActivity(intent, bundle);
There is confusing when you are using data picker, for bootstrap datepicker you have to use following code:-
$( ".datepicker" ).datepicker({
format: 'yyyy-mm-dd'
});
and for jquery datepicker following code must be used:-
$( ".datepicker" ).datepicker({
dateFormat: 'dd-mm-yy'
});
So you must be aware which date picker you are using, that is ultimately solve your issue, Hope this hepls you.
For the 1st part count NaN
we have multiple way.
Method 1 count
, due to the count
will ignore the NaN
which is different from size
print(len(df) - df.count())
Method 2 isnull
/ isna
chain with sum
print(df.isnull().sum())
#print(df.isna().sum())
Method 3 describe
/ info
: notice this will output the 'notnull' value count
print(df.describe())
#print(df.info())
Method from numpy
print(np.count_nonzero(np.isnan(df.values),axis=0))
For the 2nd part of the question, If we would like drop the column by the thresh,we can try with dropna
thresh, optional Require that many non-NA values.
Thresh = n # no null value require, you can also get the by int(x% * len(df))
df = df.dropna(thresh = Thresh, axis = 1)
To answer the question that is asked in the beginning:
Why can't the container component call the async API, and then dispatch the actions?
Keep in mind that those docs are for Redux, not Redux plus React. Redux stores hooked up to React components can do exactly what you say, but a Plain Jane Redux store with no middleware doesn't accept arguments to dispatch
except plain ol' objects.
Without middleware you could of course still do
const store = createStore(reducer);
MyAPI.doThing().then(resp => store.dispatch(...));
But it's a similar case where the asynchrony is wrapped around Redux rather than handled by Redux. So, middleware allows for asynchrony by modifying what can be passed directly to dispatch
.
That said, the spirit of your suggestion is, I think, valid. There are certainly other ways you could handle asynchrony in a Redux + React application.
One benefit of using middleware is that you can continue to use action creators as normal without worrying about exactly how they're hooked up. For example, using redux-thunk
, the code you wrote would look a lot like
function updateThing() {
return dispatch => {
dispatch({
type: ActionTypes.STARTED_UPDATING
});
AsyncApi.getFieldValue()
.then(result => dispatch({
type: ActionTypes.UPDATED,
payload: result
}));
}
}
const ConnectedApp = connect(
(state) => { ...state },
{ update: updateThing }
)(App);
which doesn't look all that different from the original — it's just shuffled a bit — and connect
doesn't know that updateThing
is (or needs to be) asynchronous.
If you also wanted to support promises, observables, sagas, or crazy custom and highly declarative action creators, then Redux can do it just by changing what you pass to dispatch
(aka, what you return from action creators). No mucking with the React components (or connect
calls) necessary.
For anyone else that comes across this post and might find it useful... There is actually nothing wrong with my code. I made the mistake of requesting client_credentials type access code instead of password access code (#facepalms). FYI I am using urlencoded post hence the use of querystring.. So for those that may be looking for some example code.. here is my full request
Big thanks to @swapnil for trying to help me debug this.
const data = {
grant_type: USER_GRANT_TYPE,
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
scope: SCOPE_INT,
username: DEMO_EMAIL,
password: DEMO_PASSWORD
};
axios.post(TOKEN_URL, Querystring.stringify(data))
.then(response => {
console.log(response.data);
USER_TOKEN = response.data.access_token;
console.log('userresponse ' + response.data.access_token);
})
.catch((error) => {
console.log('error ' + error);
});
const AuthStr = 'Bearer '.concat(USER_TOKEN);
axios.get(URL, { headers: { Authorization: AuthStr } })
.then(response => {
// If request is good...
console.log(response.data);
})
.catch((error) => {
console.log('error ' + error);
});
Any method based on background
or background-image
is likely to fail when user prints the document with "print background colors and images" disabled.
Which is unfortunately typical browser's default.
The only print-friendly and cross-browser compatible method here is the one proposed by Bronx.
Android Drawable Importer
, see answers above. Because it is abandoned, install forks. See Why does Android Drawable Importer ignore selection in AS 3.5 onwards or https://github.com/Vincent-Loi/android-drawable-importer-intellij-plugin.Your connection string is wrong
<connectionStrings>
<add name="ConnStringDb1" connectionString="Data Source=localhost\SQLSERVER;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
There's a great example in the AngularJS docs.
It's very well commented and should get you pointed in the right direction.
A simple example, maybe more so what you're looking for is below:
HTML
<div ng-app="myDirective" ng-controller="x">
<input type="text" ng-model="test" my-directive>
</div>
JavaScript
angular.module('myDirective', [])
.directive('myDirective', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch(attrs.ngModel, function (v) {
console.log('value changed, new value is: ' + v);
});
}
};
});
function x($scope) {
$scope.test = 'value here';
}
Edit: Same thing, doesn't require ngModel
jsfiddle:
JavaScript
angular.module('myDirective', [])
.directive('myDirective', function () {
return {
restrict: 'A',
scope: {
myDirective: '='
},
link: function (scope, element, attrs) {
// set the initial value of the textbox
element.val(scope.myDirective);
element.data('old-value', scope.myDirective);
// detect outside changes and update our input
scope.$watch('myDirective', function (val) {
element.val(scope.myDirective);
});
// on blur, update the value in scope
element.bind('propertychange keyup paste', function (blurEvent) {
if (element.data('old-value') != element.val()) {
console.log('value changed, new value is: ' + element.val());
scope.$apply(function () {
scope.myDirective = element.val();
element.data('old-value', element.val());
});
}
});
}
};
});
function x($scope) {
$scope.test = 'value here';
}
I had a similar issue when using ASP.NET Core 2.1:
SaoBiz
for pointing out this solution.So, the obvious solution is to allow the request to be rewindable, but make sure that after reading the body, the binding still works.
public class EnableRequestRewindMiddleware
{
private readonly RequestDelegate _next;
///<inheritdoc/>
public EnableRequestRewindMiddleware(RequestDelegate next)
{
_next = next;
}
/// <summary>
///
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public async Task Invoke(HttpContext context)
{
context.Request.EnableRewind();
await _next(context);
}
}
(place this at the beginning of Configure method)
app.UseMiddleware<EnableRequestRewindMiddleware>();
This is part of the middleware that requires unpacking of the POSTed information for checking stuff.
using (var stream = new MemoryStream())
{
// make sure that body is read from the beginning
context.Request.Body.Seek(0, SeekOrigin.Begin);
context.Request.Body.CopyTo(stream);
string requestBody = Encoding.UTF8.GetString(stream.ToArray());
// this is required, otherwise model binding will return null
context.Request.Body.Seek(0, SeekOrigin.Begin);
}
if ([statusString isEqualToString:@"Wrong"]) {
// do something
}
Just use it like it was an object you defined. i.e.
$trends = $json_output->trends;
I could care less about IE6, as long as it works in IE8, Firefox 4, and Safari 5
This makes me happy.
Try this: Live Demo
display: table
is surprisingly good. Once you don't care about IE7, you're free to use it. It doesn't really have any of the usual downsides of <table>
.
CSS:
#container {
background: #ccc;
display: table
}
#left, #right {
display: table-cell
}
#left {
width: 150px;
background: #f0f;
border: 5px dotted blue;
}
#right {
background: #aaa;
border: 3px solid #000
}
This worked for me:
dt.DefaultView.Sort = "Town ASC, Cutomer ASC";
dt = dt.DefaultView.ToTable();
i've been with this issue using elementary OS loki. For like one day and i solved it restarting the adb using this command:
./adb kill-server
and
./adb start-server
You need to be in the Sdk folder >Platform Tools
Now, restart your phone this will restart all the process in your phone.
And that's how i fixed it.
As has already been suggested, Flexbox is the answer - particularly because you only need to support a single modern browser: Mobile Safari.
See: http://jsfiddle.net/thirtydot/hLUHL/
You can remove the -moz-
prefixed properties if you like, I just left them in for future readers.
#blockContainer {_x000D_
display: -webkit-box;_x000D_
display: -moz-box;_x000D_
display: box;_x000D_
_x000D_
-webkit-box-orient: vertical;_x000D_
-moz-box-orient: vertical;_x000D_
box-orient: vertical;_x000D_
}_x000D_
#blockA {_x000D_
-webkit-box-ordinal-group: 2;_x000D_
-moz-box-ordinal-group: 2;_x000D_
box-ordinal-group: 2;_x000D_
}_x000D_
#blockB {_x000D_
-webkit-box-ordinal-group: 3;_x000D_
-moz-box-ordinal-group: 3;_x000D_
box-ordinal-group: 3;_x000D_
}
_x000D_
<div id="blockContainer">_x000D_
<div id="blockA">Block A</div>_x000D_
<div id="blockB">Block B</div>_x000D_
<div id="blockC">Block C</div>_x000D_
</div>
_x000D_
I combined Phil and jqno's answer and made untoggle comments with spaces:
autocmd FileType c,cpp,java,scala let b:comment_leader = '//'
autocmd FileType sh,ruby,python let b:comment_leader = '#'
autocmd FileType conf,fstab let b:comment_leader = '#'
autocmd FileType tex let b:comment_leader = '%'
autocmd FileType mail let b:comment_leader = '>'
autocmd FileType vim let b:comment_leader = '"'
function! CommentToggle()
execute ':silent! s/\([^ ]\)/' . escape(b:comment_leader,'\/') . ' \1/'
execute ':silent! s/^\( *\)' . escape(b:comment_leader,'\/') . ' \?' . escape(b:comment_leader,'\/') . ' \?/\1/'
endfunction
map <F7> :call CommentToggle()<CR>
how it works:
Lets assume we work with #-comments.
The first command s/\([^ ]\)/# \1/
searches for the first non-space character [^ ]
and replaces that with #
+itself
. The itself-replacement is done by the \(..\)
in the search-pattern and \1
in the replacement-pattern.
The second command s/^\( *\)# \?# \?/\1/
searches for lines starting with a double comment ^\( *\)# \?# \?
(accepting 0 or 1 spaces in between comments) and replaces those simply with the non-comment part \( *\)
(meaning the same number of preceeding spaces).
For more details about vim patterns check this out.
For reading REST data, at least OData Consider Microsoft Power Query. You won't be able to write data. However, you can read data very well.
Thanks for all Contributions;
that is happening with me in XML; I just Change application/XML to be text/XML which solve my Problem
In general the less number of calls to the database the better (meaning faster, more efficient), so try to code the inserts in such a way that it minimizes database accesses. Remember, unless your using a connection pool, each databse access has to create a connection, execute the sql, and then tear down the connection. Quite a bit of overhead!
Resurrecting this to post the DISTINCT FROM
option, which has been around since Postgres 8. The approach is similar to Brad Dre's answer. In your case, your select would be something like
SELECT *
FROM table_name
WHERE boolean_column IS DISTINCT FROM TRUE
Just send xml bytes directly:
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import requests
xml = """<?xml version='1.0' encoding='utf-8'?>
<a>?</a>"""
headers = {'Content-Type': 'application/xml'} # set what your server accepts
print requests.post('http://httpbin.org/post', data=xml, headers=headers).text
{
"origin": "x.x.x.x",
"files": {},
"form": {},
"url": "http://httpbin.org/post",
"args": {},
"headers": {
"Content-Length": "48",
"Accept-Encoding": "identity, deflate, compress, gzip",
"Connection": "keep-alive",
"Accept": "*/*",
"User-Agent": "python-requests/0.13.9 CPython/2.7.3 Linux/3.2.0-30-generic",
"Host": "httpbin.org",
"Content-Type": "application/xml"
},
"json": null,
"data": "<?xml version='1.0' encoding='utf-8'?>\n<a>\u0431</a>"
}
Try this
SqlCommand cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID=@id", con);
cmd.Parameters.AddWithValue("id", id.Text);
Try adding the line c = cv.WaitKey(10)
at the bottom of your repeat()
method.
This waits for 10 ms for the user to enter a key. Even if you're not using the key at all, put this in. I think there just needed to be some delay, so time.sleep(10)
may also work.
In regards to the camera index, you could do something like this:
for i in range(3):
capture = cv.CaptureFromCAM(i)
if capture: break
This will find the index of the first "working" capture device, at least for indices from 0-2. It's possible there are multiple devices in your computer recognized as a proper capture device. The only way I know of to confirm you have the right one is manually looking at your light. Maybe get an image and check its properties?
To add a user prompt to the process, you could bind a key to switching cameras in your repeat loop:
import cv
cv.NamedWindow("w1", cv.CV_WINDOW_AUTOSIZE)
camera_index = 0
capture = cv.CaptureFromCAM(camera_index)
def repeat():
global capture #declare as globals since we are assigning to them now
global camera_index
frame = cv.QueryFrame(capture)
cv.ShowImage("w1", frame)
c = cv.WaitKey(10)
if(c=="n"): #in "n" key is pressed while the popup window is in focus
camera_index += 1 #try the next camera index
capture = cv.CaptureFromCAM(camera_index)
if not capture: #if the next camera index didn't work, reset to 0.
camera_index = 0
capture = cv.CaptureFromCAM(camera_index)
while True:
repeat()
disclaimer: I haven't tested this so it may have bugs or just not work, but might give you at least an idea of a workaround.
And if you want to specify select's ID:
$("#nextPageLink").click(function(){
$('#myselect option:selected').next('option').attr('selected', 'selected');
$("#myselect").change();
});
If you click on item with id "nextPageLink", next option will be selected and onChange() event will be called. It may look like this:
$("#myselect").change(function(){
$('#myDivId').load(window.location.pathname,{myvalue:$("select#myselect").val()});
});
OnChange() event uses Ajax to load something into specified div.
window.location.pathname = actual address
OnChange() event is defined because it allowes you to change value not only using netx/prev button, but directly using standard selection. If value is changed, page does somethig automatically.
There are no Class literals for parameterized types, however there are Type objects that correctly define these types.
See java.lang.reflect.ParameterizedType - http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/ParameterizedType.html
Google's Gson library defines a TypeToken class that allows to simply generate parameterized types and uses it to spec json objects with complex parameterized types in a generic friendly way. In your example you would use:
Type typeOfListOfFoo = new TypeToken<List<Foo>>(){}.getType()
I intended to post links to the TypeToken and Gson classes javadoc but Stack Overflow won't let me post more than one link since I'm a new user, you can easily find them using Google search
Try the following query:
DECLARE @item VARCHAR(MAX) = 'LD-23DSP-1430'
SELECT
SUBSTRING( @item, 0, CHARINDEX('-', @item)) ,
SUBSTRING(
SUBSTRING( @item, CHARINDEX('-', @item)+1,LEN(@ITEM)) ,
0 ,
CHARINDEX('-', SUBSTRING( @item, CHARINDEX('-', @item)+1,LEN(@ITEM)))
),
REVERSE(SUBSTRING( REVERSE(@ITEM), 0, CHARINDEX('-', REVERSE(@ITEM))))
try
hive --outputformat==csv2 -e "select * from YOUR_TABLE";
This worked for me
my hive version is "Hive 3.1.0.3.1.0.0-78"
In Linux I resolve this problem by going to the root command prompt type:
# mysqladmin -u root password 'Secret Phrase Here'
Then go back and login. Works every time!
Swift 3
Time format 24 hours to 12 hours
let dateAsString = "13:15"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
let date = dateFormatter.date(from: dateAsString)
dateFormatter.dateFormat = "h:mm a"
let Date12 = dateFormatter.string(from: date!)
print("12 hour formatted Date:",Date12)
output will be 12 hour formatted Date: 1:15 PM
Time format 12 hours to 24 hours
let dateAsString = "1:15 PM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"
let date = dateFormatter.date(from: dateAsString)
dateFormatter.dateFormat = "HH:mm"
let Date24 = dateFormatter.string(from: date!)
print("24 hour formatted Date:",Date24)
output will be 24 hour formatted Date: 13:15
By default, py.test
captures the result of standard out so that it can control how it prints it out. If it didn't do this, it would spew out a lot of text without the context of what test printed that text.
However, if a test fails, it will include a section in the resulting report that shows what was printed to standard out in that particular test.
For example,
def test_good():
for i in range(1000):
print(i)
def test_bad():
print('this should fail!')
assert False
Results in the following output:
>>> py.test tmp.py
============================= test session starts ==============================
platform darwin -- Python 2.7.6 -- py-1.4.20 -- pytest-2.5.2
plugins: cache, cov, pep8, xdist
collected 2 items
tmp.py .F
=================================== FAILURES ===================================
___________________________________ test_bad ___________________________________
def test_bad():
print('this should fail!')
> assert False
E assert False
tmp.py:7: AssertionError
------------------------------- Captured stdout --------------------------------
this should fail!
====================== 1 failed, 1 passed in 0.04 seconds ======================
Note the Captured stdout
section.
If you would like to see print
statements as they are executed, you can pass the -s
flag to py.test
. However, note that this can sometimes be difficult to parse.
>>> py.test tmp.py -s
============================= test session starts ==============================
platform darwin -- Python 2.7.6 -- py-1.4.20 -- pytest-2.5.2
plugins: cache, cov, pep8, xdist
collected 2 items
tmp.py 0
1
2
3
... and so on ...
997
998
999
.this should fail!
F
=================================== FAILURES ===================================
___________________________________ test_bad ___________________________________
def test_bad():
print('this should fail!')
> assert False
E assert False
tmp.py:7: AssertionError
====================== 1 failed, 1 passed in 0.02 seconds ======================
try:
r = requests.post(url, data=data, verify='/path/to/public_key.pem')
Sometimes it is just easier to try something simple like this.
validateNumber(control: FormControl): { [s: string]: boolean } {
//revised to reflect null as an acceptable value
if (control.value === null) return null;
// check to see if the control value is no a number
if (isNaN(control.value)) {
return { 'NaN': true };
}
return null;
}
Hope this helps.
updated as per comment, You need to to call the validator like this
number: new FormControl('',[this.validateNumber.bind(this)])
The bind(this) is necessary if you are putting the validator in the component which is how I do it.
You can use disabled attribute to disable the textbox.
document.getElementById('color').disabled = true;
Tortoise Settings > Icon Overlays -> Overlay Handlers -> Start registry editor
1. Rename icon name :By adding a space(s) at the beginning of the file's name and then press F5 until it goes to top . example: " Tortoise1Normal" (in default 2 spaces included)? " Tortoise1Normal" (3 spaces)
2. Restart explorer in Task manager
In answer to your first question, there's no parameter substitution because you've put the delimiter in quotes - the bash manual says:
The format of here-documents is:
<<[-]word here-document delimiter
No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. [...]
If you change your first example to use <<EOF
instead of << "EOF"
you'll find that it works.
In your second example, the shell invokes sudo
only with the parameter cat
, and the redirection applies to the output of sudo cat
as the original user. It'll work if you try:
sudo sh -c "cat > /path/to/outfile" <<EOT
my text...
EOT
2nd October 2020: note that many bare-bones approaches are fraught with subtle bugs (eg. whitespace, implicit partial parsing, radix, coercion of arrays etc.) that many of the answers here fail to take into account. The following implementation might work for you, but note that it does not cater for number separators other than the decimal point ".
":
function isNumeric(str) {
if (typeof str != "string") return false // we only process strings!
return !isNaN(str) && // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)...
!isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail
}
This works regardless of whether the variable content is a string or number.
isNaN(num) // returns true if the variable does NOT contain a valid number
isNaN(123) // false
isNaN('123') // false
isNaN('1e10000') // false (This translates to Infinity, which is a number)
isNaN('foo') // true
isNaN('10px') // true
Of course, you can negate this if you need to. For example, to implement the IsNumeric
example you gave:
function isNumeric(num){
return !isNaN(num)
}
Only works if the string only contains numeric characters, else it returns NaN
.
+num // returns the numeric value of the string, or NaN
// if the string isn't purely numeric characters
+'12' // 12
+'12.' // 12
+'12..' // NaN
+'.12' // 0.12
+'..12' // NaN
+'foo' // NaN
+'12px' // NaN
Useful for converting '12px' to 12, for example:
parseInt(num) // extracts a numeric value from the
// start of the string, or NaN.
parseInt('12') // 12
parseInt('aaa') // NaN
parseInt('12px') // 12
parseInt('foo2') // NaN These last two may be different
parseInt('12a5') // 12 from what you expected to see.
Bear in mind that, unlike +num
, parseInt
(as the name suggests) will convert a float into an integer by chopping off everything following the decimal point (if you want to use parseInt()
because of this behaviour, you're probably better off using another method instead):
+'12.345' // 12.345
parseInt(12.345) // 12
parseInt('12.345') // 12
Empty strings may be a little counter-intuitive. +num
converts empty strings or strings with spaces to zero, and isNaN()
assumes the same:
+'' // 0
+' ' // 0
isNaN('') // false
isNaN(' ') // false
But parseInt()
does not agree:
parseInt('') // NaN
parseInt(' ') // NaN
You can use the mask to copy only the region of interest of an original image to a destination one:
cvCopy(origImage,destImage,mask);
where mask
should be an 8-bit single channel array.
See more at the OpenCV docs
Heh tried all these answers and none of them worked. I think a common cause of this issue is something a lot simpler.
I advise all who get this problem to look at their launch configuration:
Look! The launch configuration contains options for which APK to deploy. If you choose default, Android Studio will be dumb to any product flavors, build types etc. you have in your gradle file. In my case, I have multiple build types and product flavors, and received "no local path" when trying to launch a non-default product flavor.
Android Studio was not wrong! It couldn't find the default APK, because I was not building for it. I solve my issue by instead choosing "Do not deploy anything" and then executing the gradle install task I needed for my specific combination of product flavor / build type.
Turns out it needs to be specified via escaped unicode. This question is related and contains the answer.
The solution:
h2:after {
content: "\00a0";
}
<script>
$(document).ready(function(){
$('#connectBtn').click(function(e){
e.preventDefault();
})
});
</script>
This will prevent the default action.
You can use the v$session_connect_info
view against the current session ID (SID
from the USERENV
namespace in SYS_CONTEXT
).
e.g.
SELECT
DISTINCT
s.client_version
FROM
v$session_connect_info s
WHERE
s.sid = SYS_CONTEXT('USERENV', 'SID');
The view controller must be a child of some UINavigationController for the .title
property to take effect. If the UINavigationBar is simply a view, you need to push a navigation item containing the title, or modify the last navigation item:
UINavigationItem* item = [[UINavigationItem alloc] initWithTitle:@"title text"];
...
[bar pushNavigationItem:item animated:YES];
[item release];
or
bar.topItem.title = @"title text";
<span>
will allow you to style text, but it adds no semantic content.
As you're emphasizing some text, it sounds like you'd be better served by wrapping the text in <em></em>
and using CSS to change the color of the <em>
element. For example:
.description {
color: #fff;
}
.description em {
color: #ffa500;
}
<p class="description">Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Sed hendrerit mollis varius. Etiam ornare placerat
massa, <em>eget vulputate tellus fermentum.</em></p>
In fact, I'd go to great pains to avoid the <span>
element, as it's completely meaningless to everything that doesn't render your style sheet (bots, screen readers, luddites who disable styles, parsers, etc.) or renders it in unexpected ways (personal style sheets). In many ways, it's no better than using the <font>
element.
.description {_x000D_
color: #000;_x000D_
}_x000D_
_x000D_
.description em {_x000D_
color: #ffa500;_x000D_
}
_x000D_
<p class="description">Lorem ipsum dolor sit amet, consectetur _x000D_
adipiscing elit. Sed hendrerit mollis varius. Etiam ornare placerat _x000D_
massa, <em>eget vulputate tellus fermentum.</em></p>
_x000D_
Syntax of waitpid()
:
pid_t waitpid(pid_t pid, int *status, int options);
The value of pid
can be:
pid
.pid
.The value of options is an OR of zero or more of the following constants:
WNOHANG
: Return immediately if no child has exited.WUNTRACED
: Also return if a child has stopped. Status for traced children which have stopped is provided even if this option is not specified.WCONTINUED
: Also return if a stopped child has been resumed by delivery of SIGCONT
.For more help, use man waitpid
.
void QWidget::setWindowTitle ( const QString & )
EDIT: If you are using QtDesigner, on the property tab, there is an editable property called windowTitle which can be found under the QWidget section. The property tab can usually be found on the lower right part of the designer window.
Look at the traceback:
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
out = iter(out)
TypeError: 'bool' object is not iterable
Your code isn't iterating the value, but the code receiving it is.
The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)
) or enclose it in a tuple ((False,)
).
Always read the traceback: it's correct, and it's helpful.
Conceptually, arrays in JavaScript contain array.length
elements, starting with array[0]
up until array[array.length - 1]
. An array element with index i
is defined to be part of the array if i
is between 0
and array.length - 1
inclusive. If i is not in this range it's not in the array.
So by concept, arrays are linear, starting with zero and going to a maximum, without any mechanism for having "gaps" inside that range where no entries exist. To find out if a value exists at a given position index (where index is 0 or a positive integer), you literally just use
if (i >= 0 && i < array.length) {
// it is in array
}
Now, under the hood, JavaScript engines almost certainly won't allocate array space linearly and contiguously like this, as it wouldn't make much sense in a dynamic language and it would be inefficient for certain code. They're probably hash tables or some hybrid mixture of strategies, and undefined ranges of the array probably aren't allocated their own memory. Nonetheless, JavaScript the language wants to present arrays of array.length
n as having n members and they are named 0 to n - 1, and anything in this range is part of the array.
What you probably want, however, is to know if a value in an array is actually something defined - that is, it's not undefined
. Maybe you even want to know if it's defined and not null
. It's possible to add members to an array without ever setting their value: for example, if you add array values by increasing the array.length
property, any new values will be undefined
.
To determine if a given value is something meaningful, or has been defined. That is, not undefined
, or null
:
if (typeof array[index] !== 'undefined') {
or
if (typeof array[index] !== 'undefined' && array[index] !== null) {
Interestingly, because of JavaScript's comparison rules, my last example can be optimised down to this:
if (array[index] != null) {
// The == and != operators consider null equal to only null or undefined
}
Warning: this is an experimental feature that could dramatically change or even cease to exist in future releases
You can use ES7 statics:
npm install babel-preset-stage-0
And then add "stage-0"
to .babelrc presets:
{
"presets": ["es2015", "react", "stage-0"]
}
Afterwards, you go
class Component extends React.Component {
static foo = 'bar';
static baz = {a: 1, b: 2}
}
And then you use them like this:
Component.foo
Old topic, but never clearly answered. I've been working on similar as well, and found the solution:
The pipe (|) in this code sample from Austin isn't the delimiter, but to pipe the ForEach-Object, so if you want to use it as delimiter, you need to do this:
Import-Csv H:\Programs\scripts\SomeText.csv -delimiter "|" |`
ForEach-Object {
$Name += $_.Name
$Phone += $_."Phone Number"
}
Spent a good 15 minutes on this myself before I understood what was going on. Hope the answer helps the next person reading this avoid the wasted minutes! (Sorry for expanding on your comment Austin)
for my experience, Ellipsis works only if below two attributes are set.
android:ellipsize="end"
android:singleLine="true"
for the width of textview, wrap_content or match_parent should both be good.
Not being a numpy person, I took a shot with:
>>> import numpy as np
>>> import itertools
>>>
>>> a = np.array([1,2,3,4,5,6,7,8,9])
>>> index=[2,3,6]
>>> a = np.array(list(itertools.compress(a, [i not in index for i in range(len(a))])))
>>> a
array([1, 2, 5, 6, 8, 9])
According to my tests, this outperforms numpy.delete()
. I don't know why that would be the case, maybe due to the small size of the initial array?
python -m timeit -s "import numpy as np" -s "import itertools" -s "a = np.array([1,2,3,4,5,6,7,8,9])" -s "index=[2,3,6]" "a = np.array(list(itertools.compress(a, [i not in index for i in range(len(a))])))"
100000 loops, best of 3: 12.9 usec per loop
python -m timeit -s "import numpy as np" -s "a = np.array([1,2,3,4,5,6,7,8,9])" -s "index=[2,3,6]" "np.delete(a, index)"
10000 loops, best of 3: 108 usec per loop
That's a pretty significant difference (in the opposite direction to what I was expecting), anyone have any idea why this would be the case?
Even more weirdly, passing numpy.delete()
a list performs worse than looping through the list and giving it single indices.
python -m timeit -s "import numpy as np" -s "a = np.array([1,2,3,4,5,6,7,8,9])" -s "index=[2,3,6]" "for i in index:" " np.delete(a, i)"
10000 loops, best of 3: 33.8 usec per loop
Edit: It does appear to be to do with the size of the array. With large arrays, numpy.delete()
is significantly faster.
python -m timeit -s "import numpy as np" -s "import itertools" -s "a = np.array(list(range(10000)))" -s "index=[i for i in range(10000) if i % 2 == 0]" "a = np.array(list(itertools.compress(a, [i not in index for i in range(len(a))])))"
10 loops, best of 3: 200 msec per loop
python -m timeit -s "import numpy as np" -s "a = np.array(list(range(10000)))" -s "index=[i for i in range(10000) if i % 2 == 0]" "np.delete(a, index)"
1000 loops, best of 3: 1.68 msec per loop
Obviously, this is all pretty irrelevant, as you should always go for clarity and avoid reinventing the wheel, but I found it a little interesting, so I thought I'd leave it here.
Statement is static and prepared statement is dynamic.
Statement is suitable for DDL and prepared statment for DML.
Statement is slower while prepared statement is faster.
more differences (archived)
Whats with all these "works for me answers" ? We're all coding in the same language and the rules are
That is what will work for all. If a given solution only "works for you", its only because your application flow won't allow for a scenario where the reference may be null or the string length to be 0. The proper way to do this is the method that will handle what you want in all cases.
cell.Text = "your firstline<br style=\"mso-data-placement:same-cell;\">your secondline";
If you are getting the text from DB then:
cell.Text = textfromDB.Replace("\n", "<br style=\"mso-data-placement:same-cell;\">");
Generate the range of data first and then shuffle it like this
import random
data = range(numLow, numHigh)
random.shuffle(data)
print data
By doing this way, you will get all the numbers in the particular range but in a random order.
But you can use random.sample
to get the number of elements you need, from a range of numbers like this
print random.sample(range(numLow, numHigh), 3)
In general, in C++ functions have to be declared before you call them. So sometime before the definition of getSkewNormal()
, the compiler needs to see the declaration:
double integrate (double start, double stop, int numSteps, Evaluatable evalObj);
Mostly what people do is put all the declarations (only) in the header file, and put the actual code -- the definitions of the functions and methods -- into a separate source (*.cc
or *.cpp
) file. This neatly solves the problem of needing all the functions to be declared.
This should do the trick...
'recalculate all open workbooks
Application.Calculate
'recalculate a specific worksheet
Worksheets(1).Calculate
' recalculate a specific range
Worksheets(1).Columns(1).Calculate
To find the sessions, as a DBA use
select sid,serial# from v$session where username = '<your_schema>'
If you want to be sure only to get the sessions that use SQL Developer, you can add and program = 'SQL Developer'
. If you only want to kill sessions belonging to a specific developer, you can add a restriction on os_user
Then kill them with
alter system kill session '<sid>,<serial#>'
(e.g.
alter system kill session '39,1232'
)
A query that produces ready-built kill-statements could be
select 'alter system kill session ''' || sid || ',' || serial# || ''';' from v$session where username = '<your_schema>'
This will return one kill statement per session for that user - something like:
alter system kill session '375,64855';
alter system kill session '346,53146';
I wrote the following function. It replaces the following:
Single quote ['] with a slash and a single quote [\'].
Backslash [\] with two backslashes [\\]
function escapePhpString($target) {
$replacements = array(
"'" => '\\\'',
"\\" => '\\\\'
);
return strtr($target, $replacements);
}
You can modify it to add or remove character replacements in the $replacements array. For example, to replace \r\n, it becomes "\r\n" => "\r\n" and "\n" => "\n".
/**
* With new line replacements too
*/
function escapePhpString($target) {
$replacements = array(
"'" => '\\\'',
"\\" => '\\\\',
"\r\n" => "\\r\\n",
"\n" => "\\n"
);
return strtr($target, $replacements);
}
The neat feature about strtr is that it will prefer long replacements.
Example, "Cool\r\nFeature" will escape \r\n rather than escaping \n along.
In Python the passing by reference or by value has to do with what are the actual objects you are passing.So,if you are passing a list for example,then you actually make this pass by reference,since the list is a mutable object.Thus,you are passing a pointer to the function and you can modify the object (list) in the function body.
When you are passing a string,this passing is done by value,so a new string object is being created and when the function terminates it is destroyed. So it all has to do with mutable and immutable objects.
A better method is using strrpos + substr (faster than explode for that) :
$userfile_name = $_FILES['image']['name'];
$userfile_extn = substr($userfile_name, strrpos($userfile_name, '.')+1);
But, to check the type of a file, using mime_content_type is a better way : http://www.php.net/manual/en/function.mime-content-type.php
Here is the approach I use: http://thaiat.github.io/blog/2014/02/26/angularjs-and-requirejs-for-very-large-applications/
The page shows a possible implementation of AngularJS + RequireJS, where the code is split by features and then component type.
if you still looking for the answer you can use input type="number" in place of type="range" min max work if it set in that order:
1-name
2-maxlength
3-size
4-min
5-max
just copy it
<input name="X" maxlength="3" size="2" min="1" max="100" type="number" />
In kotlin you can use unaryPlus and unaryMinus
input = input.unaryPlus()
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/unary-plus.html https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/unary-minus.html
I think ("\") may be causing the problem because \ is the escape character. change it to ("\\")
I'm trying to close users connection in version 1.0 and found this method:
socket.conn.close()
The difference between this method and disconnect() is that the client will keep trying to reconnect to the server.
There are multiple answers based on what you are doing with the string.
1) Using the string as an id (will not be modified). Passing it in by const reference is probably the best idea here: (std::string const&)
2) Modifying the string but not wanting the caller to see that change. Passing it in by value is preferable: (std::string)
3) Modifying the string but wanting the caller to see that change. Passing it in by reference is preferable: (std::string &)
4) Sending the string into the function and the caller of the function will never use the string again. Using move semantics might be an option (std::string &&)
In the following line
<form method="post" action="display()">
the action should be the name of your script and you should call the function, Something like this
<form method="post" action="yourFileName.php">
<input type="text" name="studentname">
<input type="submit" value="click" name="submit"> <!-- assign a name for the button -->
</form>
<?php
function display()
{
echo "hello ".$_POST["studentname"];
}
if(isset($_POST['submit']))
{
display();
}
?>
Just a side comment, Before adding support for multidex - make sure you are not adding unnecessary dependencies.
For example In the official Facebook analytics guide
They clearly state that you should add the following dependency:
implementation 'com.facebook.android:facebook-android-sdk:[4,5)'
which is actually the entire FacebookSDK - so if you need for example just the Analytics you need to replace it with:
implementation 'com.facebook.android:facebook-core:5.+'
You're instantiating the Random
object inside your method.
The Random
object is seeded from the system clock, which means that if you call your method several times in quick succession it'll use the same seed each time, which means that it'll generate the same sequence of random numbers, which means that you'll get the same string.
To solve the problem, move your Random
instance outside of the method itself (and while you're at it you could get rid of that crazy sequence of calls to Convert
and Floor
and NextDouble
):
private readonly Random _rng = new Random();
private const string _chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private string RandomString(int size)
{
char[] buffer = new char[size];
for (int i = 0; i < size; i++)
{
buffer[i] = _chars[_rng.Next(_chars.Length)];
}
return new string(buffer);
}
1) First Insert JS file path in an index.html file :
<script src="assets/video.js" type="text/javascript"></script>
2) Import JS file and declare the variable in component.ts :
declare var RunPlayer: any;
NOTE: Variable name should be same as the name of a function in js file
3) Call the js method in the component
ngAfterViewInit(){
setTimeout(() => {
new RunPlayer();
});
}
1) I haven't found a working method for moving the public directory in L5. While you can modify some things in the bootstrap index.php
, it appears several helper functions are based on the assumption of that public directory being there. In all honestly you really shouldn't be moving the public directory.
2) If your using MAMP then you should be creating new vhosts for each project, each serving that projects public directory. Once created you access each project by your defined server name like this :
http://project1.dev
http://project2.dev
If the stop option is greyed out then your service did not indicate that it was accepting SERVICE_ACCEPT_STOP
when it last called SetServiceStatus
. If you're using .NET, then you need to set the CanStop
property in ServiceBase
.
Of course, if you're accepting stop requests, then you'd better make sure that your service can safely handle those requests, especially if your service is still progressing through its startup code.
You can use the VisualTreeHelper to find controls. Below is a method that uses the VisualTreeHelper to find a parent control of a specified type. You can use the VisualTreeHelper to find controls in other ways as well.
public static class UIHelper
{
/// <summary>
/// Finds a parent of a given item on the visual tree.
/// </summary>
/// <typeparam name="T">The type of the queried item.</typeparam>
/// <param name="child">A direct or indirect child of the queried item.</param>
/// <returns>The first parent item that matches the submitted type parameter.
/// If not matching item can be found, a null reference is being returned.</returns>
public static T FindVisualParent<T>(DependencyObject child)
where T : DependencyObject
{
// get parent item
DependencyObject parentObject = VisualTreeHelper.GetParent(child);
// we’ve reached the end of the tree
if (parentObject == null) return null;
// check if the parent matches the type we’re looking for
T parent = parentObject as T;
if (parent != null)
{
return parent;
}
else
{
// use recursion to proceed with next level
return FindVisualParent<T>(parentObject);
}
}
}
Call it like this:
Window owner = UIHelper.FindVisualParent<Window>(myControl);
git checkout -b NEW_BRANCH_NAME COMMIT_ID
This will create a new branch called 'NEW_BRANCH_NAME' and check it out.
("check out" means "to switch to the branch")
git branch NEW_BRANCH_NAME COMMIT_ID
This just creates the new branch without checking it out.
in the comments many people seem to prefer doing this in two steps. here's how to do so in two steps:
git checkout COMMIT_ID
# you are now in the "detached head" state
git checkout -b NEW_BRANCH_NAME
Use JavaScript's hasOwnProperty()
function:
if (json_object.hasOwnProperty('name')) {
//do struff
}
Latest and greatest way to do this:
Node supports file and buffer operations with the base64
encoding:
const fs = require('fs');
const contents = fs.readFileSync('/path/to/file.jpg', {encoding: 'base64'});
Or using the new promises API:
const fs = require('fs').promises;
const contents = await fs.readFile('/path/to/file.jpg', {encoding: 'base64'});
Easiest way to share code is with a public gist. Just write one up and paste in the embed code. Easy peasy.
To address the search engine issue, one can use hidden div
on the page as simple as:
<div style="display:none"> content </div>
Here is how to create the desired outcome:
library(reshape2); library(tidyverse)
melt(outer(1:4, 1:4), varnames = c("X1", "X2")) %>%
ggplot() +
geom_tile(aes(X1, X2, fill = value)) +
scale_fill_continuous(guide = guide_legend()) +
theme(legend.position="bottom",
legend.spacing.x = unit(0, 'cm'))+
guides(fill = guide_legend(label.position = "bottom"))
Created on 2019-12-07 by the reprex package (v0.3.0)
Edit: no need for these imperfect options anymore, but I'm leaving them here for reference.
Two imperfect options that don't give you exactly what you were asking for, but pretty close (will at least put the colours together).
library(reshape2); library(tidyverse)
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
theme(legend.position="bottom", legend.direction="vertical")
p1 + scale_fill_continuous(guide = "colorbar") + theme(legend.position="bottom")
Created on 2019-02-28 by the reprex package (v0.2.1)
zitao xiong's answer is pretty close to what I use; I also include the file name (by stripping off the path of FILE).
#ifdef DEBUG
#define NSLogDebug(format, ...) \
NSLog(@"<%s:%d> %s, " format, \
strrchr("/" __FILE__, '/') + 1, __LINE__, __PRETTY_FUNCTION__, ## __VA_ARGS__)
#else
#define NSLogDebug(format, ...)
#endif
Consider the following:
class Bad(object):
def __eq__(self, other):
return True
c = Bad()
c is None # False, equivalent to id(c) == id(None)
c == None # True, equivalent to c.__eq__(None)
In C# These ways you can Solve the problem, In UIkit these methods are available.
Label.Font = Label.Font.WithSize(5.0f);
Or
Label.Font = UIFont.FromName("Copperplate", 10.0f);
Or
Label.Font = UIFont.WithSize(5.0f);
I was also looking for it and ended up creating something for my code display. Here's a good way:
The way to reinstall Homebrew is completely remove it and start over. The Homebrew FAQ has a link to a shell script to uninstall homebrew.
If the only thing you've installed in /usr/local
is homebrew itself, you can just rm -rf /usr/local/* /usr/local/.git
to clear it out. But /usr/local/
is the standard Unix directory for all extra binaries, not just Homebrew, so you may have other things installed there. In that case uninstall_homebrew.sh
is a better bet. It is careful to only remove homebrew's files and leave the rest alone.
I solved this problem by adding user settings.
in nginx.conf
worker_processes 4;
user username;
change the 'username' with linux user name.
[Belmiro@HP-550 ~]$ uname -a
Linux HP-550 2.6.30.10-105.2.23.fc11.x86_64 #1 SMP Thu Feb 11 07:06:34 UTC 2010
x86_64 x86_64 x86_64 GNU/Linux
[Belmiro@HP-550 ~]$ lsb_release -a
LSB Version: :core-3.1-amd64:core-3.1-noarch:core-3.2-amd64:core-3.2-noarch:deskt
op-3.1-amd64:desktop-3.1-noarch:desktop-3.2-amd64:desktop-3.2-noarch
Distributor ID: Fedora
Description: Fedora release 11 (Leonidas)
Release: 11
Codename: Leonidas
[Belmiro@HP-550 ~]$
If the assembly is part of the build of an ASP.NET application, you can use the BuildManager class:
using System.Web.Compilation
...
BuildManager.GetType(typeName, false);
The array decays to a pointer when passed.
Section 6.4 of the C FAQ covers this very well and provides the K&R references etc.
That aside, imagine it were possible for the function to know the size of the memory allocated in a pointer. You could call the function two or more times, each time with different input arrays that were potentially different lengths; the length would therefore have to be passed in as a secret hidden variable somehow. And then consider if you passed in an offset into another array, or an array allocated on the heap (malloc
and all being library functions - something the compiler links to, rather than sees and reasons about the body of).
Its getting difficult to imagine how this might work without some behind-the-scenes slice objects and such right?
Symbian did have a AllocSize()
function that returned the size of an allocation with malloc()
; this only worked for the literal pointer returned by the malloc, and you'd get gobbledygook or a crash if you asked it to know the size of an invalid pointer or a pointer offset from one.
You don't want to believe its not possible, but it genuinely isn't. The only way to know the length of something passed into a function is to track the length yourself and pass it in yourself as a separate explicit parameter.
I recode again the code and now you can create an .xls file, later you can convert to Excel 2003 Open XML Format.
private static void exportToExcel(DataSet source, string fileName)
{
// Documentacion en:
// https://en.wikipedia.org/wiki/Microsoft_Office_XML_formats
// https://answers.microsoft.com/en-us/msoffice/forum/all/how-to-save-office-ms-xml-as-xlsx-file/4a77dae5-6855-457d-8359-e7b537beb1db
// https://riptutorial.com/es/openxml
const string startExcelXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"+
"<?mso-application progid=\"Excel.Sheet\"?>\r\n" +
"<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n" +
"xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n " +
"xmlns:x=\"urn:schemas-microsoft-com:office:excel\"\r\n " +
"xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n " +
"xmlns:html=\"http://www.w3.org/TR/REC-html40\">\r\n " +
"xmlns:html=\"https://www.w3.org/TR/html401/\">\r\n " +
"<DocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\">\r\n " +
" <Version>16.00</Version>\r\n " +
"</DocumentProperties>\r\n " +
" <OfficeDocumentSettings xmlns=\"urn:schemas-microsoft-com:office:office\">\r\n " +
" <AllowPNG/>\r\n " +
" </OfficeDocumentSettings>\r\n " +
" <ExcelWorkbook xmlns=\"urn:schemas-microsoft-com:office:excel\">\r\n " +
" <WindowHeight>9750</WindowHeight>\r\n " +
" <WindowWidth>24000</WindowWidth>\r\n " +
" <WindowTopX>0</WindowTopX>\r\n " +
" <WindowTopY>0</WindowTopY>\r\n " +
" <RefModeR1C1/>\r\n " +
" <ProtectStructure>False</ProtectStructure>\r\n " +
" <ProtectWindows>False</ProtectWindows>\r\n " +
" </ExcelWorkbook>\r\n " +
"<Styles>\r\n " +
"<Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n " +
"<Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>" +
"\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>" +
"\r\n <Protection/>\r\n </Style>\r\n " +
"<Style ss:ID=\"BoldColumn\">\r\n <Font " +
"x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n " +
"<Style ss:ID=\"StringLiteral\">\r\n <NumberFormat" +
" ss:Format=\"@\"/>\r\n </Style>\r\n <Style " +
"ss:ID=\"Decimal\">\r\n <NumberFormat " +
"ss:Format=\"0.0000\"/>\r\n </Style>\r\n " +
"<Style ss:ID=\"Integer\">\r\n <NumberFormat/>" +
"ss:Format=\"0\"/>\r\n </Style>\r\n <Style " +
"ss:ID=\"DateLiteral\">\r\n <NumberFormat " +
"ss:Format=\"dd/mm/yyyy;@\"/>\r\n </Style>\r\n " +
"</Styles>\r\n ";
System.IO.StreamWriter excelDoc = null;
excelDoc = new System.IO.StreamWriter(fileName,false);
int sheetCount = 1;
excelDoc.Write(startExcelXML);
foreach (DataTable table in source.Tables)
{
int rowCount = 0;
excelDoc.Write("<Worksheet ss:Name=\"" + table.TableName + "\">");
excelDoc.Write("<Table>");
excelDoc.Write("<Row>");
for (int x = 0; x < table.Columns.Count; x++)
{
excelDoc.Write("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");
excelDoc.Write(table.Columns[x].ColumnName);
excelDoc.Write("</Data></Cell>");
}
excelDoc.Write("</Row>");
foreach (DataRow x in table.Rows)
{
rowCount++;
//if the number of rows is > 64000 create a new page to continue output
if (rowCount == 1048576)
{
rowCount = 0;
sheetCount++;
excelDoc.Write("</Table>");
excelDoc.Write(" </Worksheet>");
excelDoc.Write("<Worksheet ss:Name=\"" + table.TableName + "\">");
excelDoc.Write("<Table>");
}
excelDoc.Write("<Row>"); //ID=" + rowCount + "
for (int y = 0; y < table.Columns.Count; y++)
{
System.Type rowType;
rowType = x[y].GetType();
switch (rowType.ToString())
{
case "System.String":
string XMLstring = x[y].ToString();
XMLstring = XMLstring.Trim();
XMLstring = XMLstring.Replace("&", "&");
XMLstring = XMLstring.Replace(">", ">");
XMLstring = XMLstring.Replace("<", "<");
excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
"<Data ss:Type=\"String\">");
excelDoc.Write(XMLstring);
excelDoc.Write("</Data></Cell>");
break;
case "System.DateTime":
//Excel has a specific Date Format of YYYY-MM-DD followed by
//the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000
//The Following Code puts the date stored in XMLDate
//to the format above
DateTime XMLDate = (DateTime)x[y];
string XMLDatetoString = ""; //Excel Converted Date
XMLDatetoString = XMLDate.Year.ToString() +
"-" +
(XMLDate.Month < 10 ? "0" +
XMLDate.Month.ToString() : XMLDate.Month.ToString()) +
"-" +
(XMLDate.Day < 10 ? "0" +
XMLDate.Day.ToString() : XMLDate.Day.ToString()) +
"T" +
(XMLDate.Hour < 10 ? "0" +
XMLDate.Hour.ToString() : XMLDate.Hour.ToString()) +
":" +
(XMLDate.Minute < 10 ? "0" +
XMLDate.Minute.ToString() : XMLDate.Minute.ToString()) +
":" +
(XMLDate.Second < 10 ? "0" +
XMLDate.Second.ToString() : XMLDate.Second.ToString()) +
".000";
excelDoc.Write("<Cell ss:StyleID=\"DateLiteral\">" +
"<Data ss:Type=\"DateTime\">");
excelDoc.Write(XMLDatetoString);
excelDoc.Write("</Data></Cell>");
break;
case "System.Boolean":
excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
"<Data ss:Type=\"String\">");
excelDoc.Write(x[y].ToString());
excelDoc.Write("</Data></Cell>");
break;
case "System.Int16":
case "System.Int32":
case "System.Int64":
case "System.Byte":
excelDoc.Write("<Cell ss:StyleID=\"Integer\">" +
"<Data ss:Type=\"Number\">");
excelDoc.Write(x[y].ToString());
excelDoc.Write("</Data></Cell>");
break;
case "System.Decimal":
case "System.Double":
excelDoc.Write("<Cell ss:StyleID=\"Decimal\">" +
"<Data ss:Type=\"Number\">");
excelDoc.Write(x[y].ToString());
excelDoc.Write("</Data></Cell>");
break;
case "System.DBNull":
excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
"<Data ss:Type=\"String\">");
excelDoc.Write("");
excelDoc.Write("</Data></Cell>");
break;
default:
throw (new Exception(rowType.ToString() + " not handled."));
}
}
excelDoc.Write("</Row>");
}
excelDoc.Write("</Table>");
excelDoc.Write("</Worksheet>");
sheetCount++;
}
const string endExcelOptions1 = "\r\n<WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">\r\n" +
"<Selected/>\r\n" +
"<ProtectObjects>False</ProtectObjects>\r\n" +
"<ProtectScenarios>False</ProtectScenarios>\r\n" +
"</WorksheetOptions>\r\n";
excelDoc.Write(endExcelOptions1);
excelDoc.Write("</Workbook>");
excelDoc.Close();
}
In case you want a quicker (but still very clean) way of achieving it for a personal purpose (for instance if you want to build a specific project having some strong requirements concerning the version of the compiler), just follow the following steps:
echo $PATH
and look for a personal directory having a very high priority (in my case, I have ~/.local/bin
);For instance:
ln -s /usr/bin/gcc-WHATEVER ~/.local/bin/gcc
ln -s /usr/bin/g++-WHATEVER ~/.local/bin/g++
Of course, this will work for a single user (it isn't a system wide solution), but on the other hand I don't like to change too many things in my installation.
You have to write you own remove. You can loop over the array, grab the index of the item you want to remove, and use splice
to remove it.
Alternatively, you can create a new array, loop over the current array, and if the current object doesn't match what you want to remove, put it in a new array.
One thing to note - as I had exactly this problem today, depending on your HTML jQuery may or may not parse it that well. jQuery wouldn't parse my HTML into a correct DOM - on smaller XML compliant files it worked fine, but the HTML I had (that would render in a page) wouldn't parse when passed back to an Ajax callback.
In the end I simply searched manually in the string for the tag I wanted, not ideal but did work.
Extending upon Mustafa's answer.
A) Install http://phantomjs.org/ and then
B) install the phantom node module https://github.com/amir20/phantomjs-node
C) Here is an example of rendering a pdf
var phantom = require('phantom');
phantom.create().then(function(ph) {
ph.createPage().then(function(page) {
page.open("http://www.google.com").then(function(status) {
page.render('google.pdf').then(function() {
console.log('Page Rendered');
ph.exit();
});
});
});
});
Output of the PDF:
EDIT: Silent printing that PDF
java -jar pdfbox-app-2.0.2.jar PrintPDF -silentPrint C:\print_mypdf.pdf
Basic Availability: The database appears to work most of the time.
Soft State: Stores don’t have to be write-consistent or mutually consistent all the time.
Eventual consistency: Data should always be consistent, with regards how any number of changes are performed.
You can do it all within .NET 3.5 using DeflateStream. The thing lacking in .NET 3.5 is the ability to process the file header sections that are used to organize the zipped files. PKWare has published this information, which you can use to process the zip file after you create the structures that are used. It is not particularly onerous, and it a good practice in tool building without using 3rd party code.
It isn't a one line answer, but it is completely doable if you are willing and able to take the time yourself. I wrote a class to do this in a couple of hours and what I got from that is the ability to zip and unzip files using .NET 3.5 only.
Download the source code here (Display PDF file inside my android application)
Add this dependency in your Grade:
compile com.github.barteksc:android-pdf-viewer:2.0.3
activity_main.xml
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
xmlns:android="http://schemas.android.com/apk/res/android" >
<TextView
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="@color/colorPrimaryDark"
android:text="View PDF"
android:textColor="#ffffff"
android:id="@+id/tv_header"
android:textSize="18dp"
android:gravity="center"></TextView>
<com.github.barteksc.pdfviewer.PDFView
android:id="@+id/pdfView"
android:layout_below="@+id/tv_header"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
MainActivity.java
import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.provider.OpenableColumns;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.shockwave.pdfium.PdfDocument;
import java.util.List;
public class MainActivity extends Activity implements OnPageChangeListener,OnLoadCompleteListener{
private static final String TAG = MainActivity.class.getSimpleName();
public static final String SAMPLE_FILE = "android_tutorial.pdf";
PDFView pdfView;
Integer pageNumber = 0;
String pdfFileName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pdfView= (PDFView)findViewById(R.id.pdfView);
displayFromAsset(SAMPLE_FILE);
}
private void displayFromAsset(String assetFileName) {
pdfFileName = assetFileName;
pdfView.fromAsset(SAMPLE_FILE)
.defaultPage(pageNumber)
.enableSwipe(true)
.swipeHorizontal(false)
.onPageChange(this)
.enableAnnotationRendering(true)
.onLoad(this)
.scrollHandle(new DefaultScrollHandle(this))
.load();
}
@Override
public void onPageChanged(int page, int pageCount) {
pageNumber = page;
setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
}
@Override
public void loadComplete(int nbPages) {
PdfDocument.Meta meta = pdfView.getDocumentMeta();
printBookmarksTree(pdfView.getTableOfContents(), "-");
}
public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
for (PdfDocument.Bookmark b : tree) {
Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));
if (b.hasChildren()) {
printBookmarksTree(b.getChildren(), sep + "-");
}
}
}
}
Try this for creating a column3 as a sum of column1 + column 2 in a table
tablename$column3=rowSums(cbind(tablename$column1,tablename$column2))
User.objects.filter(username='tom', groups__name='admin').exists()
That query will inform you user : "tom" whether belong to group "admin " or not
You can use "is not" for "not equal" or "!=". Please see the example below:
a = 2
if a == 2:
print("true")
else:
print("false")
The above code will print "true" as a = 2 assigned before the "if" condition. Now please see the code below for "not equal"
a = 2
if a is not 3:
print("not equal")
else:
print("equal")
The above code will print "not equal" as a = 2 as assigned earlier.
Note that the Element::innerText
property will not contain the text which has been hidden by CSS style "display:none
" in Google Chrome (as well it will drop the content that has been masked by other CSS technics (including font-size:0, color:transparent, and a few other similar effects that cause the text not to be rendered in any visible way).
Other CSS properties are also considered :
<br \>
that generates an inline newline will also generate an newline in the value of innerText.But Element::textContent
will still contain ALL contents of inner text elements independantly of the applied CSS even if they are invisible. And no extra newlines or whitespaces will be generated in textContent, which just ignores all styles and the structure and inline/block or positioned types of inner elements.
A copy/paste operation using mouse selection will discard the hidden text in the plain-text format that is put in the clipboard, so it won't contain everything in the textContent
, but only what is within innerText
(after whitespace/newline generation as above).
Both properties are then supported in Google Chrome, but their content may then be different. Older browsers still included in innetText everything like what textContent now contains (but their behavior in relation with then generation of whitespaces/newlines was inconsistant).
jQuery will solve these inconsistencies between browsers using the ".text()" method added to the parsed elements it returns via a $() query. Internally, it solves the difficulties by looking into the HTML DOM, working only with the "node" level. So it will return something looking more like the standard textContent.
The caveat is that that this jQuery method will not insert any extra spaces or line breaks that may be visible on screen caused by subelements (like <br />
) of the content.
If you design some scripts for accessibility and your stylesheet is parsed for non-aural rendering, such as plugins used to communicate with a Braille reader, this tool should use the textContent if it must include the specific punctuation signs that are added in spans styled with "display:none" and that are typically included in pages (for example for superscripts/subscripts), otherwise the innerText will be very confusive on the Braille reader.
Texts hidden by CSS tricks are now typically ignored by major search engines (that will also parse the CSS of your HTML pages, and will also ignore texts that are not in contrasting colors on the background) using an HTML/CSS parser and the DOM property "innerText" exactly like in modern visual browsers (at least this invisible content will not be indexed so hidden text cannot be used as a trick to force the inclusion of some keywords in the page to check its content) ; but this hidden text will be stil displayed in the result page (if the page was still qualified from the index to be included in results), using the "textContent" property instead of the full HTML to strip the extra styles and scripts.
IF you assign some plain-text in any one of these two properties, this will overwrite the inner markup and styles applied to it (only the assigned element will keep its type, attributes and styles), so both properties will then contain the same content. However, some browsers will now no longer honor the write to innerText, and will only let you overwrite the textContent property (you cannot insert HTML markup when writing to these properties, as HTML special characters will be properly encoded using numeric character references to appear literally, if you then read the innerHTML
property after the assignment of innerText
or textContent
.
Converting to a list without using the keys
method makes it more readable:
list(newdict)
and, when looping through dictionaries, there's no need for keys()
:
for key in newdict:
print key
unless you are modifying it within the loop which would require a list of keys created beforehand:
for key in list(newdict):
del newdict[key]
On Python 2 there is a marginal performance gain using keys()
.
If you simply open the file for writing with the truncate-option, you'll delete the content.
std::ofstream ofs;
ofs.open("test.txt", std::ofstream::out | std::ofstream::trunc);
ofs.close();
This error occurs when the linker can't find WinMain
function, so it is probably missing. In your case, you are probably missing main
too.
Consider the following Windows API-level program:
#define NOMINMAX
#include <windows.h>
int main()
{
MessageBox( 0, "Blah blah...", "My Windows app!", MB_SETFOREGROUND );
}
Now let's build it using GNU toolchain (i.e. g++), no special options. Here gnuc
is just a batch file that I use for that. It only supplies options to make g++ more standard:
C:\test> gnuc x.cpp C:\test> objdump -x a.exe | findstr /i "^subsystem" Subsystem 00000003 (Windows CUI) C:\test> _
This means that the linker by default produced a console subsystem executable. The subsystem value in the file header tells Windows what services the program requires. In this case, with console system, that the program requires a console window.
This also causes the command interpreter to wait for the program to complete.
Now let's build it with GUI subsystem, which just means that the program does not require a console window:
C:\test> gnuc x.cpp -mwindows C:\test> objdump -x a.exe | findstr /i "^subsystem" Subsystem 00000002 (Windows GUI) C:\test> _
Hopefully that's OK so far, although the -mwindows
flag is just semi-documented.
Building without that semi-documented flag one would have to more specifically tell the linker which subsystem value one desires, and some Windows API import libraries will then in general have to be specified explicitly:
C:\test> gnuc x.cpp -Wl,-subsystem,windows C:\test> objdump -x a.exe | findstr /i "^subsystem" Subsystem 00000002 (Windows GUI) C:\test> _
That worked fine, with the GNU toolchain.
But what about the Microsoft toolchain, i.e. Visual C++?
Well, building as a console subsystem executable works fine:
C:\test> msvc x.cpp user32.lib x.cpp C:\test> dumpbin /headers x.exe | find /i "subsystem" | find /i "Windows" 3 subsystem (Windows CUI) C:\test> _
However, with Microsoft's toolchain building as GUI subsystem does not work by default:
C:\test> msvc x.cpp user32.lib /link /subsystem:windows x.cpp LIBCMT.lib(wincrt0.obj) : error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartu p x.exe : fatal error LNK1120: 1 unresolved externals C:\test> _
Technically this is because Microsoft’s linker is non-standard by default for GUI subsystem. By default, when the subsystem is GUI, then Microsoft's linker uses a runtime library entry point, the function where the machine code execution starts, called winMainCRTStartup
, that calls Microsoft's non-standard WinMain
instead of standard main
.
No big deal to fix that, though.
All you have to do is to tell Microsoft's linker which entry point to use, namely mainCRTStartup
, which calls standard main
:
C:\test> msvc x.cpp user32.lib /link /subsystem:windows /entry:mainCRTStartup x.cpp C:\test> dumpbin /headers x.exe | find /i "subsystem" | find /i "Windows" 2 subsystem (Windows GUI) C:\test> _
No problem, but very tedious. And so arcane and hidden that most Windows programmers, who mostly only use Microsoft’s non-standard-by-default tools, do not even know about it, and mistakenly think that a Windows GUI subsystem program “must” have non-standard WinMain
instead of standard main
. In passing, with C++0x Microsoft will have a problem with this, since the compiler must then advertize whether it's free-standing or hosted (when hosted it must support standard main
).
Anyway, that's the reason why g++ can complain about WinMain
missing: it's a silly non-standard startup function that Microsoft's tools require by default for GUI subsystem programs.
But as you can see above, g++ has no problem with standard main
even for a GUI subsystem program.
So what could be the problem?
Well, you are probably missing a main
. And you probably have no (proper) WinMain
either! And then g++, after having searched for main
(no such), and for Microsoft's non-standard WinMain
(no such), reports that the latter is missing.
Testing with an empty source:
C:\test> type nul >y.cpp C:\test> gnuc y.cpp -mwindows c:/program files/mingw/bin/../lib/gcc/mingw32/4.4.1/../../../libmingw32.a(main.o):main.c:(.text+0xd2): undefined referen ce to `WinMain@16' collect2: ld returned 1 exit status C:\test> _
The current way to do this is by using the "Add Service Reference" command. If you specify "TestUploaderWebService
" as the service reference name, that will generate the type TestUploaderWebService.Service1
. That class will have a method named GetFileListOnWebServer
, which will return an array of strings (you can change that to be a list of strings if you like). You would use it like this:
string[] files = null;
TestUploaderWebService.Service1 proxy = null;
bool success = false;
try
{
proxy = new TestUploaderWebService.Service1();
files = proxy.GetFileListOnWebServer();
proxy.Close();
success = true;
}
finally
{
if (!success)
{
proxy.Abort();
}
}
P.S. Tell your instructor to look at "Microsoft: ASMX Web Services are a “Legacy Technology”", and ask why he's teaching out of date technology.
There is one case when you do it, with while
-loops.
When reading files, you usualy do like this:
void readFile(String pathToFile) {
// Create a FileInputStream object
FileInputStream fileIn = null;
try {
// Create the FileInputStream
fileIn = new FileInputStream(pathToFile);
// Create a variable to store the current line's text in
String currentLine;
// While the file has lines left, read the next line,
// store it in the variable and do whatever is in the loop
while((currentLine = in.readLine()) != null) {
// Print out the current line in the console
// (you can do whatever you want with the line. this is just an example)
System.out.println(currentLine);
}
} catch(IOException e) {
// Handle exception
} finally {
try {
// Close the FileInputStream
fileIn.close();
} catch(IOException e) {
// Handle exception
}
}
}
Look at the while
-loop at line 9. There, a new line is read and stored in a variable, and then the content of the loop is ran. I know this isn't an if
-statement, but I guess a while loop can be included in your question as well.
The reason to this is that when using a FileInputStream
, every time you call FileInputStream.readLine()
, it reads the next line in the file, so if you would have called it from the loop with just fileIn.readLine() != null
without assigning the variable, instead of calling (currentLine = fileIn.readLine()) != null
, and then called it from inside of the loop too, you would only get every second line.
Hope you understand, and good luck!
Simple php script worked for me.
Export:
// add all job codes in the array
$jobs = array("job1", "job2", "job3");
foreach ($jobs as $value)
{
fwrite(STDOUT, $value. " \n") or die("Unable to open file!");
$path = "http://server1:8080/jenkins/job/".$value."/config.xml";
$myfile = fopen($value.".xml", "w");
fwrite($myfile, file_get_contents($path));
fclose($myfile);
}
Import:
<?php
// add all job codes in the array
$jobs = array("job1", "job2", "job3");
foreach ($arr as $value)
{
fwrite(STDOUT, $value. " \n") or die("Unable to open file!");
$cmd = "java -jar jenkins-cli.jar -s http://server2:8080/jenkins/ create-job ".$value." < ".$value.".xml";
echo exec($cmd);
}
http://code.google.com/p/connectbot/, Compile src\com\trilead\ssh2 on windows linux or android , it can create Local Port Forwarder or create Dynamic Port Forwarder or other else
function isPrevDate() {
alert("startDate is " + Startdate);
if(Startdate.length != 0 && Startdate !='') {
var start_date = Startdate.split('-');
alert("Input date: "+ start_date);
start_date=start_date[1]+"/"+start_date[2]+"/"+start_date[0];
alert("start date arrray format " + start_date);
var a = new Date(start_date);
//alert("The date is a" +a);
var today = new Date();
var day = today.getDate();
var mon = today.getMonth()+1;
var year = today.getFullYear();
today = (mon+"/"+day+"/"+year);
//alert(today);
var today = new Date(today);
alert("Today: "+today.getTime());
alert("a : "+a.getTime());
if(today.getTime() > a.getTime() )
{
alert("Please select Start date in range");
return false;
} else {
return true;
}
}
}
from datetime import datetime, timedelta
yesterday = datetime.now() - timedelta(days=1)
yesterday.strftime('%m%d%y')
I often just open the console and look for the solution in the objects methods. Quite often it's already there:
>>> a = "hello ' s"
>>> dir(a)
[ (....) 'partition', 'replace' (....)]
>>> a.replace("'", " ")
'hello s'
Short answer: Use string.replace()
.
I've solved it, doing the following steps:
Here you have the images of these steps:
Google provides a Equilateral triangle here.
Choose VectorDrawable so the size is flexible.
It' integrated into Android Studio as plugin.
If you have an SVG image, you can use this to convert it to VectorDrawable too.
Once you have a VectorDrawable, changing its colour and rotation is easy like others have mentioned.
you can do it with Procedure also so i have a procedure for this
DELIMITER $$
CREATE PROCEDURE copyTo()
BEGIN
DECLARE x INT;
DECLARE str varchar(45);
SET x = 1;
set str = '';
WHILE x < 5 DO
set str = (select source_col from emp where id=x);
update emp set target_col =str where id=x;
SET x = x + 1;
END WHILE;
END$$
DELIMITER ;
Call Enum.GetValues
; this returns an array that represents all possible values for your enum. Pick a random item from this array. Cast that item back to the original enum type.
This works on windows 7: SET PATH=%PATH%;C:\CmdShortcuts
tested by typing echo %PATH% and it worked, fine. also set if you open a new cmd, no need for those pesky reboots any more :)
Same solution via Jquery. Works if you have more than one file input in the page.
$j(".filebutton").click(function() {
var input = $j(this).next().find('input');
input.click();
});
$j(".fileinput").change(function(){
var file = $j(this).val();
var fileName = file.split("\\");
var pai =$j(this).parent().parent().prev();
pai.html(fileName[fileName.length-1]);
event.preventDefault();
});
I needed to update my php from 5.3.8 to 5.3.29. (both Thread Safe) on Windows
Steps I did:
Hope that I covered everything.
Most probably these steps will not work if you change major versions of php, e.g. 5.3.x to 5.4.x, but for minor versions, it should work.
Also, a good way to see what's wrong... start command line and try to start httpd.exe, under xampp/apache/bin from there, it will list errors found.
How about:
private List<String> Parse(String str) {
List<String> output = new ArrayList<String>();
Matcher match = Pattern.compile("[0-9]+|[a-z]+|[A-Z]+").matcher(str);
while (match.find()) {
output.add(match.group());
}
return output;
}
SELECT col1,
col2
FROM
(SELECT rownum X,col_table1 FROM table1) T1
INNER JOIN
(SELECT rownum Y, col_table2 FROM table2) T2
ON T1.X=T2.Y;
The initial size()
of V
will be 0, while int n contains any random value because you don't initialize it.
V.size() < n
is probably false.
Silly me missed the "Enter the amount of numbers you want to evaluate: "
If you enter a n
that's smaller than V.size()
at that time, the loop will terminate.
I believe you can create a unix style datestamp accurate to a second using the following
//Find unix timestamp (seconds since 01/01/1970)
long ticks = DateTime.UtcNow.Ticks - DateTime.Parse("01/01/1970 00:00:00").Ticks;
ticks /= 10000000; //Convert windows ticks to seconds
timestamp = ticks.ToString();
Adjusting the denominator allows you to choose your level of precision
Your html is invalid button
is not a null tag. Try
<div id="Content">
<button id="Add">Add</button>
</div>
If you don't feel like dropping and recreating the whole shebang just to reload your data, you could use MyModel.destroy_all
(or delete_all
) in the seed.db file to clean out a table before your MyModel.create!(...)
statements load the data. Then, you can redo the db:seed
operation over and over. (Obviously, this only affects the tables you've loaded data into, not the rest of them.)
There's a "dirty hack" at https://stackoverflow.com/a/14957893/4553442 to add a "de-seeding" operation similar to migrating up and down...
Edit: Please read Malvolio's comments below as this answer's knowledge is outdated.
You cannot do cross-domain XMLHttpRequests.
The call to 127.0.0.1
works because your test page is located at 127.0.0.1
, and the local test also works since, well... it's a local test.
The other two tests fail because JavaScript cannot communicate with a distant server through XMLHttpRequest.
You might instead consider either:
Hope that helps
add this code to Your AppKernel Class:
public function init()
{
date_default_timezone_set('Asia/Tehran');
parent::init();
}
Yes, you can, without adding a new column. You have to be careful to do it correctly in order to avoid corrupting the database, so you should completely back up your database before trying this.
for your specific example:
CREATE TABLE child(
id INTEGER PRIMARY KEY,
parent_id INTEGER,
description TEXT
);
--- create the table we want to reference
create table parent(id integer not null primary key);
--- now we add the foreign key
pragma writable_schema=1;
update SQLITE_MASTER set sql = replace(sql, 'description TEXT)',
'description TEXT, foreign key (parent_id) references parent(id))'
) where name = 'child' and type = 'table';
--- test the foreign key
pragma foreign_keys=on;
insert into parent values(1);
insert into child values(1, 1, 'hi'); --- works
insert into child values(2, 2, 'bye'); --- fails, foreign key violation
or more generally:
pragma writable_schema=1;
// replace the entire table's SQL definition, where new_sql_definition contains the foreign key clause you want to add
UPDATE SQLITE_MASTER SET SQL = new_sql_definition where name = 'child' and type = 'table';
// alternatively, you might find it easier to use replace, if you can match the exact end of the sql definition
// for example, if the last column was my_last_column integer not null:
UPDATE SQLITE_MASTER SET SQL = replace(sql, 'my_last_column integer not null', 'my_last_column integer not null, foreign key (col1, col2) references other_table(col1, col2)') where name = 'child' and type = 'table';
pragma writable_schema=0;
Either way, you'll probably want to first see what the SQL definition is before you make any changes:
select sql from SQLITE_MASTER where name = 'child' and type = 'table';
If you use the replace() approach, you may find it helpful, before executing, to first test your replace() command by running:
select replace(sql, ...) from SQLITE_MASTER where name = 'child' and type = 'table';
in my magento2 website ,show exactly the same error when click a product,
my solution is to go to edit the value of Search Engine Optimization - URL Key of this product,
make sure that there are only alphabet,number and - in URL Key, such as 100-washed-cotton-duvet-cover-set, deleting all other special characters ,such as % .
There are three ways of underling the text in TextView.
setPaintFlags(); of TextView
Let me explain you all approaches :
1st Approach
For underling the text in TextView you have to use SpannableString
String udata="Underlined Text";
SpannableString content = new SpannableString(udata);
content.setSpan(new UnderlineSpan(), 0, udata.length(), 0);
mTextView.setText(content);
2nd Approach
You can make use of setPaintFlags method of TextView to underline the text of TextView.
For eg.
mTextView.setPaintFlags(mTextView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
mTextView.setText("This text will be underlined");
You can refer constants of Paint class if you want to strike thru the text.
3rd Approach
Make use of Html.fromHtml(htmlString);
String htmlString="<u>This text will be underlined</u>";
mTextView.setText(Html.fromHtml(htmlString));
OR
txtView.setText(Html.fromHtml("<u>underlined</u> text"));
Try this as root (maybe you can use sudo
or su
):
/etc/init.d/postgresql restart
Without any argument the script also gives you a hint on how to restart a specific version
[Uqbar@Feynman ~] /etc/init.d/postgresql
Usage: /etc/init.d/postgresql {start|stop|restart|reload|force-reload|status} [version ...]
Similarly, in case you have it, you can also use the service
tool:
[Uqbar@Feynman ~] service postgresql
Usage: /etc/init.d/postgresql {start|stop|restart|reload|force reload|status} [version ...]
Please, pay attention to the optional [version ...]
trailing argument.
That's meant to allow you, the user, to act on a specific version, in case you were running multiple ones. So you can restart version X while keeping version Y and Z untouched and running.
Finally, in case you are running systemd, then you can use systemctl
like this:
[support@Feynman ~] systemctl status postgresql
? postgresql.service - PostgreSQL database server
Loaded: loaded (/usr/lib/systemd/system/postgresql.service; enabled; vendor preset: disabled)
Active: active (running) since Wed 2017-11-14 12:33:35 CET; 7min ago
...
You can replace status
with stop
, start
or restart
as well as other actions. Please refer to the documentation for full details.
In order to operate on multiple concurrent versions, the syntax is slightly different. For example to stop v12
and reload v13
you can run:
systemctl stop postgresql-12.service
systemctl reload postgresql-13.service
Thanks to @Jojo for pointing me to this very one.
Finally Keep in mind that root
permissions may be needed for non-informative tasks as in the other cases seen earlier.