ASMX Web services can only be invoked by HTTP (traditional webservice with .asmx). While WCF Service or a WCF component can be invoked by any protocol (like http, tcp etc.) and any transport type.
Second, ASMX web services are not flexible. However, WCF Services are flexible. If you make a new version of the service then you need to just expose a new end. Therefore, services are agile and which is a very practical approach looking at the current business trends.
We develop WCF as contracts, interface, operations, and data contracts. As the developer we are more focused on the business logic services and need not worry about channel stack. WCF is a unified programming API for any kind of services so we create the service and use configuration information to set up the communication mechanism like HTTP/TCP/MSMQ etc
For me it was due to "multiple" attribute on select input control as Angular has different ValueAccessor for this type of control.
const countryControl = new FormControl();
And inside template use like this
<select multiple name="countries" [formControl]="countryControl">
<option *ngFor="let country of countries" [ngValue]="country">
{{ country.name }}
</option>
</select>
More details ref Official Docs
From Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning
the following
Excessive GC Time and OutOfMemoryError
The concurrent collector will throw an OutOfMemoryError if too much time is being spent in garbage collection: if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, an OutOfMemoryError will be thrown. This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small. If necessary, this feature can be disabled by adding the option -XX:-UseGCOverheadLimit to the command line.
The policy is the same as that in the parallel collector, except that time spent performing concurrent collections is not counted toward the 98% time limit. In other words, only collections performed while the application is stopped count toward excessive GC time. Such collections are typically due to a concurrent mode failure or an explicit collection request (e.g., a call to System.gc()).
in conjunction with a passage further down
One of the most commonly encountered uses of explicit garbage collection occurs with RMIs distributed garbage collection (DGC). Applications using RMI refer to objects in other virtual machines. Garbage cannot be collected in these distributed applications without occasionally collection the local heap, so RMI forces full collections periodically. The frequency of these collections can be controlled with properties. For example,
java -Dsun.rmi.dgc.client.gcInterval=3600000
-Dsun.rmi.dgc.server.gcInterval=3600000
specifies explicit collection once per hour instead of the default rate of once per minute. However, this may also cause some objects to take much longer to be reclaimed. These properties can be set as high as Long.MAX_VALUE to make the time between explicit collections effectively infinite, if there is no desire for an upper bound on the timeliness of DGC activity.
Seems to imply that the evaluation period for determining the 98% is one minute long, but it might be configurable on Sun's JVM with the correct define.
Of course, other interpretations are possible.
No need to bother with iTunesConnect for sharing your adhoc builds. Just upload your ipa file to diawi and after successful uploading you will get a link open the link in safari and you will be asked to install app. Tap on install and enjoy
The id of the input seems is not WallSearch
. Maybe you're confusing that name
and id
. They are two different properties. name
is used to define the name by which the value is posted, while id
is the unique identification of the element inside the DOM.
Other possibility is that you have two elements with the same id. The browser will pick any of these (probably the last, maybe the first) and return an element that doesn't support the value
property.
class Foo (object):
# ^class name #^ inherits from object
bar = "Bar" #Class attribute.
def __init__(self):
# #^ The first variable is the class instance in methods.
# # This is called "self" by convention, but could be any name you want.
#^ double underscore (dunder) methods are usually special. This one
# gets called immediately after a new instance is created.
self.variable = "Foo" #instance attribute.
print self.variable, self.bar #<---self.bar references class attribute
self.bar = " Bar is now Baz" #<---self.bar is now an instance attribute
print self.variable, self.bar
def method(self, arg1, arg2):
#This method has arguments. You would call it like this: instance.method(1, 2)
print "in method (args):", arg1, arg2
print "in method (attributes):", self.variable, self.bar
a = Foo() # this calls __init__ (indirectly), output:
# Foo bar
# Foo Bar is now Baz
print a.variable # Foo
a.variable = "bar"
a.method(1, 2) # output:
# in method (args): 1 2
# in method (attributes): bar Bar is now Baz
Foo.method(a, 1, 2) #<--- Same as a.method(1, 2). This makes it a little more explicit what the argument "self" actually is.
class Bar(object):
def __init__(self, arg):
self.arg = arg
self.Foo = Foo()
b = Bar(a)
b.arg.variable = "something"
print a.variable # something
print b.Foo.variable # Foo
The Response was Empty. Most of the case the codes will stats with 1xx, 2xx, 3xx, 4xx, 5xx.
The doubling up of the quote should have worked, so it's peculiar that it didn't work for you; however, an alternative is using double quote characters, instead of single ones, around the string. I.e.,
insert into my_table values("hi, my name's tim."
);
Easy way to remove the underline from the anchor tag if you use bootstrap. for my case, I used to like this;
<a href="#first1" class=" nav-link">
<button type="button" class="btn btn-warning btn-lg btn-block">
Reserve Table
</button>
</a>
Yes.
$array[] = new stdClass;
$array[] = new stdClass;
print_r($array);
Results in:
Array
(
[0] => stdClass Object
(
)
[1] => stdClass Object
(
)
)
Slightly neater C# code from Miroslav Zadravec's code assuming all columns are to be autosized
for (int i = 0; i < dgvProblems.Columns.Count; i++)
{
dgvProblems.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
int colw = dgvProblems.Columns[i].Width;
dgvProblems.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
dgvProblems.Columns[i].Width = colw;
}
Set theory is inappropriate for lists since duplicates will result in wrong answers using set theory.
For example:
a = [1, 3, 3, 3, 5]
b = [1, 3, 3, 4, 5]
set(b) > set(a)
has no meaning. Yes, it gives a false answer but this is not correct since set theory is just comparing: 1,3,5 versus 1,3,4,5. You must include all duplicates.
Instead you must count each occurrence of each item and do a greater than equal to check. This is not very expensive, because it is not using O(N^2) operations and does not require quick sort.
#!/usr/bin/env python
from collections import Counter
def containedInFirst(a, b):
a_count = Counter(a)
b_count = Counter(b)
for key in b_count:
if a_count.has_key(key) == False:
return False
if b_count[key] > a_count[key]:
return False
return True
a = [1, 3, 3, 3, 5]
b = [1, 3, 3, 4, 5]
print "b in a: ", containedInFirst(a, b)
a = [1, 3, 3, 3, 4, 4, 5]
b = [1, 3, 3, 4, 5]
print "b in a: ", containedInFirst(a, b)
Then running this you get:
$ python contained.py
b in a: False
b in a: True
For copy directory use following command
cp -r source Destination
For example
cp -r /home/hasan /opt
For copy file use command without -r
cp /home/file /home/hasan/
Since it's just false and json object, why don't you check whether it's false, otherwise it must be json.
if(ret == false || ret == "false") {
// json
}
Piggybacking on what the other answers say, since you don't know how to do them at all, here's an example of how you might do it in JavaScript:
var charactersOnly = "This contains only characters";
var nonCharacters = "This has _@#*($()*@#$(*@%^_(#@!$ non-characters";
if (charactersOnly.search(/[^a-zA-Z]+/) === -1) {
alert("Only characters");
}
if (nonCharacters.search(/[^a-zA-Z]+/)) {
alert("There are non characters.");
}
The /
starting and ending the regular expression signify that it's a regular expression. The search
function takes both strings and regexes, so the /
are necessary to specify a regex.
From the MDN Docs, the function returns -1
if there is no match.
Also note: that this works for only a-z, A-Z. If there are spaces, it will fail.
The withColumn function in pyspark enables you to make a new variable with conditions, add in the when and otherwise functions and you have a properly working if then else structure. For all of this you would need to import the sparksql functions, as you will see that the following bit of code will not work without the col() function. In the first bit, we declare a new column -'new column', and then give the condition enclosed in when function (i.e. fruit1==fruit2) then give 1 if the condition is true, if untrue the control goes to the otherwise which then takes care of the second condition (fruit1 or fruit2 is Null) with the isNull() function and if true 3 is returned and if false, the otherwise is checked again giving 0 as the answer.
from pyspark.sql import functions as F
df=df.withColumn('new_column',
F.when(F.col('fruit1')==F.col('fruit2'), 1)
.otherwise(F.when((F.col('fruit1').isNull()) | (F.col('fruit2').isNull()), 3))
.otherwise(0))
Besides the already stated answers about using Vector, Vector also has a bunch of methods around enumeration and element retrieval which are different than the List interface, and developers (especially those who learned Java before 1.2) can tend to use them if they are in the code. Although Enumerations are faster, they don't check if the collection was modified during iteration, which can cause issues, and given that Vector might be chosen for its syncronization - with the attendant access from multiple threads, this makes it a particularly pernicious problem. Usage of these methods also couples a lot of code to Vector, such that it won't be easy to replace it with a different List implementation.
[[ ]] double brackets are unsuported under certain version of SunOS and totally unsuported inside function declarations by : GNU bash, version 2.02.0(1)-release (sparc-sun-solaris2.6)
You can do this by thinking of it a little bit differently. Detect when the body is clicked (document.body.onclick
- i.e. anything on the page) and then check if the element clicked (event.srcElement
/ e.target
) has a class and that that class name is the one you want:
document.body.onclick = function(e) { //when the document body is clicked
if (window.event) {
e = event.srcElement; //assign the element clicked to e (IE 6-8)
}
else {
e = e.target; //assign the element clicked to e
}
if (e.className && e.className.indexOf('someclass') != -1) {
//if the element has a class name, and that is 'someclass' then...
alert('hohoho');
}
}
Or a more concise version of the above:
document.body.onclick= function(e){
e=window.event? event.srcElement: e.target;
if(e.className && e.className.indexOf('someclass')!=-1)alert('hohoho');
}
Okay so little bit of digging and I found these gems from Bill Philips article on RecycleView
RecyclerView can do more than ListView, but the RecyclerView class itself has fewer responsibilities than ListView. Out of the box, RecyclerView does not:
- Position items on the screen
- Animate views
- Handle any touch events apart from scrolling
All of this stuff was baked in to ListView, but RecyclerView uses collaborator classes to do these jobs instead.
The ViewHolders you create are beefier, too. They subclass
RecyclerView.ViewHolder
, which has a bunch of methodsRecyclerView
uses.ViewHolders
know which position they are currently bound to, as well as which item ids (if you have those). In the process,ViewHolder
has been knighted. It used to be ListView’s job to hold on to the whole item view, andViewHolder
only held on to little pieces of it.Now, ViewHolder holds on to all of it in the
ViewHolder.itemView
field, which is assigned in ViewHolder’s constructor for you.
Create a branch on the local system with that name. e.g. say you want to get the branch named branch-05142011
git branch branch-05142011 origin/branch-05142011
It'll give you a message:
$ git checkout --track origin/branch-05142011
Branch branch-05142011 set up to track remote branch refs/remotes/origin/branch-05142011.
Switched to a new branch "branch-05142011"
Now just checkout the branch like below and you have the code
git checkout branch-05142011
DOUBLE columns are not the same as DECIMAL columns, and you will get in trouble if you use DOUBLE columns for financial data.
DOUBLE is actually just a double precision (64 bit instead of 32 bit) version of FLOAT. Floating point numbers are approximate representations of real numbers and they are not exact. In fact, simple numbers like 0.01 do not have an exact representation in FLOAT or DOUBLE types.
DECIMAL columns are exact representations, but they take up a lot more space for a much smaller range of possible numbers. To create a column capable of holding values from 0.0001 to 99.9999 like you asked you would need the following statement
CREATE TABLE your_table
(
your_column DECIMAL(6,4) NOT NULL
);
The column definition follows the format DECIMAL(M, D) where M is the maximum number of digits (the precision) and D is the number of digits to the right of the decimal point (the scale).
This means that the previous command creates a column that accepts values from -99.9999 to 99.9999. You may also create an UNSIGNED DECIMAL column, ranging from 0.0000 to 99.9999.
For more information on MySQL DECIMAL the official docs are always a great resource.
Bear in mind that all of this information is true for versions of MySQL 5.0.3 and greater. If you are using previous versions, you really should upgrade.
This worked for me:
string string_test = "80123456";
unsigned long x;
signed long val;
std::stringstream ss;
ss << std::hex << string_test;
ss >> x;
// ss >> val; // if I try this val = 0
val = (signed long)x; // However, if I cast the unsigned result I get val = 0x80123456
curl -X PUT -d 'new_value' URL_PATH/key
where,
X - option to be used for request command
d - option to be used in order to put data on remote url
URL_PATH - remote url
new_value - value which we want to put to the server's key
"final" also allows a compiler optimization to bypass the indirect call:
class IAbstract
{
public:
virtual void DoSomething() = 0;
};
class CDerived : public IAbstract
{
void DoSomething() final { m_x = 1 ; }
void Blah( void ) { DoSomething(); }
};
with "final", the compiler can call CDerived::DoSomething()
directly from within Blah()
, or even inline. Without it, it has to generate an indirect call inside of Blah()
because Blah()
could be called inside a derived class which has overridden DoSomething()
.
Note that you can also combine the two, which is pretty cool (although it looks a bit odd):
// simple interpolated verbatim string
WriteLine($@"Path ""C:\Windows\{file}"" not found.");
If looking for a unique list while grouping multiple columns this could probably help:
df.groupby('a').agg(lambda x: list(set(x))).reset_index()
The data you want is in the "cols" meta-data table:
SELECT * FROM COLS WHERE COLUMN_NAME = 'id'
This one will give you a list of tables that have all of the columns you want:
select distinct
C1.TABLE_NAME
from
cols c1
inner join
cols c2
on C1.TABLE_NAME = C2.TABLE_NAME
inner join
cols c3
on C2.TABLE_NAME = C3.TABLE_NAME
inner join
cols c4
on C3.TABLE_NAME = C4.TABLE_NAME
inner join
tab t
on T.TNAME = C1.TABLE_NAME
where T.TABTYPE = 'TABLE' --could be 'VIEW' if you wanted
and upper(C1.COLUMN_NAME) like upper('%id%')
and upper(C2.COLUMN_NAME) like upper('%fname%')
and upper(C3.COLUMN_NAME) like upper('%lname%')
and upper(C4.COLUMN_NAME) like upper('%address%')
To do this in a different schema, just specify the schema in front of the table, as in
SELECT * FROM SCHEMA1.COLS WHERE COLUMN_NAME LIKE '%ID%';
If you want to combine the searches of many schemas into one output result, then you could do this:
SELECT DISTINCT
'SCHEMA1' AS SCHEMA_NAME
,TABLE_NAME
FROM SCHEMA1.COLS
WHERE COLUMN_NAME LIKE '%ID%'
UNION
SELECT DISTINCT
'SCHEMA2' AS SCHEMA_NAME
,TABLE_NAME
FROM SCHEMA2.COLS
WHERE COLUMN_NAME LIKE '%ID%'
for CMake remove/disable with_libv4l
with_v4l
variables if you do not need this lib.
In httpd.conf, search for "ServerName". It's usually commented out by default on Mac. Just uncomment it and fill it in. Make sure you also have the name/ip combo set in /etc/hosts.
In Jenkins 2.138.3 there are two different types of pipelines.
Declarative and Scripted pipelines.
"Declarative pipelines is a new extension of the pipeline DSL (it is basically a pipeline script with only one step, a pipeline step with arguments (called directives), these directives should follow a specific syntax. The point of this new format is that it is more strict and therefore should be easier for those new to pipelines, allow for graphical editing and much more. scripted pipelines is the fallback for advanced requirements."
jenkins pipeline: agent vs node?
Here is an example of using environment and global variables in a Declarative Pipeline. From what I can tell enviroment are static after they are set.
def browser = 'Unknown'
pipeline {
agent any
environment {
//Use Pipeline Utility Steps plugin to read information from pom.xml into env variables
IMAGE = readMavenPom().getArtifactId()
VERSION = readMavenPom().getVersion()
}
stages {
stage('Example') {
steps {
script {
browser = sh(returnStdout: true, script: 'echo Chrome')
}
}
}
stage('SNAPSHOT') {
when {
expression {
return !env.JOB_NAME.equals("PROD") && !env.VERSION.contains("RELEASE")
}
}
steps {
echo "SNAPSHOT"
echo "${browser}"
}
}
stage('RELEASE') {
when {
expression {
return !env.JOB_NAME.equals("TEST") && !env.VERSION.contains("RELEASE")
}
}
steps {
echo "RELEASE"
echo "${browser}"
}
}
}//end of stages
}//end of pipeline
They might be just a \r
or a \n
. I just checked and the text visualizer in VS 2010 displays both as newlines as well as \r\n
.
This string
string test = "blah\r\nblah\rblah\nblah";
Shows up as
blah
blah
blah
blah
in the text visualizer.
So you could try
string modifiedString = originalString
.Replace(Environment.NewLine, "<br />")
.Replace("\r", "<br />")
.Replace("\n", "<br />");
One of the advantages that stems from Static factory is that that API can return objects without making their classes public. This lead to very compact API. In java this is achieved by Collections class which hides around 32 classes which makes it collection API very compact.
Try this example. If the directory does not exist, no error is raised. You may need PowerShell v3.0.
remove-item -path "c:\Test Temp\Test Folder" -Force -Recurse -ErrorAction SilentlyContinue
Well... These are PHP. There is an sms one from google here.
And github has one here.
Another sms one is here. However, this one has a lot more code, so it may take up more space.
This tutorial should help you:
Getting Started with Oracle SQL Developer
See the prerequisites:
Unlock the HR user. Login to SQL*Plus as the SYS user and execute the following command:
alter user hr identified by hr account unlock;
Download and unzip the sqldev_mngdb.zip file that contains all the files you need to perform this tutorial.
Another version from May 2011: Getting Started with Oracle SQL Developer
For more info check this related question:
How to create a new database after initally installing oracle database 11g Express Edition?
Clustered Index
Clustered indexes sort and store the data rows in the table or view based on their key values. These are the columns included in the index definition. There can be only one clustered index per table, because the data rows themselves can be sorted in only one order.
The only time the data rows in a table are stored in sorted order is when the table contains a clustered index. When a table has a clustered index, the table is called a clustered table. If a table has no clustered index, its data rows are stored in an unordered structure called a heap.
Nonclustered
Nonclustered indexes have a structure separate from the data rows. A nonclustered index contains the nonclustered index key values and each key value entry has a pointer to the data row that contains the key value. The pointer from an index row in a nonclustered index to a data row is called a row locator. The structure of the row locator depends on whether the data pages are stored in a heap or a clustered table. For a heap, a row locator is a pointer to the row. For a clustered table, the row locator is the clustered index key.
You can add nonkey columns to the leaf level of the nonclustered index to by-pass existing index key limits, and execute fully covered, indexed, queries. For more information, see Create Indexes with Included Columns. For details about index key limits see Maximum Capacity Specifications for SQL Server.
I have a sample program for this:
public class BrowserBackForward {
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("http://seleniumhq.org/");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//maximize the window
driver.manage().window().maximize();
driver.findElement(By.linkText("Documentation")).click();
System.out.println(driver.getCurrentUrl());
driver.navigate().back();
System.out.println(driver.getCurrentUrl());
Thread.sleep(30000);
driver.navigate().forward();
System.out.println("Forward");
Thread.sleep(30000);
driver.navigate().refresh();
}
}
For those of us accomplishing this with Angular JS, I used a directive
HTML:
<textarea elastic ng-model="someProperty"></textarea>
JS:
.directive('elastic', [
'$timeout',
function($timeout) {
return {
restrict: 'A',
link: function($scope, element) {
$scope.initialHeight = $scope.initialHeight || element[0].style.height;
var resize = function() {
element[0].style.height = $scope.initialHeight;
element[0].style.height = "" + element[0].scrollHeight + "px";
};
element.on("input change", resize);
$timeout(resize, 0);
}
};
}
]);
$timeout
queues an event that will fire after the DOM loads, which is what's necessary to get the right scrollHeight (otherwise you'll get undefined
)
Perfect Regex like Google Email
"^[A-Z0-9a-z][a-zA-Z0-9_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
As of Helios Service Release 2, there is no longer support for JAR files.You can add them, but Eclipse will not recognize them as libraries, therefore you can only "import" but can never use.
Inspired by Jon's answer, how about this one
word = 'hello'
q = deque(word)
''.join(q.pop() for _ in range(len(word)))
You can use
String hex = String.format("#%02x%02x%02x", r, g, b);
Use capital X's if you want your resulting hex-digits to be capitalized (#FFFFFF
vs. #ffffff
).
You get SyntaxError
error exception because Python has no &&
operator. It has and
and &
where the latter one is the correct choice to create boolean expressions on Column
(|
for a logical disjunction and ~
for logical negation).
Condition you created is also invalid because it doesn't consider operator precedence. &
in Python has a higher precedence than ==
so expression has to be parenthesized.
(col("Age") == "") & (col("Survived") == "0")
## Column<b'((Age = ) AND (Survived = 0))'>
On a side note when
function is equivalent to case
expression not WHEN
clause. Still the same rules apply. Conjunction:
df.where((col("foo") > 0) & (col("bar") < 0))
Disjunction:
df.where((col("foo") > 0) | (col("bar") < 0))
You can of course define conditions separately to avoid brackets:
cond1 = col("Age") == ""
cond2 = col("Survived") == "0"
cond1 & cond2
You can also customize the card theme globally with ThemeData.cardTheme
:
MaterialApp(
title: 'savvy',
theme: ThemeData(
cardTheme: CardTheme(
shape: RoundedRectangleBorder(
borderRadius: const BorderRadius.all(
Radius.circular(8.0),
),
),
),
// ...
In order to let you open your application from another, you'll need to make changes in both applications. Here are the steps using Swift 3 with iOS 10 update:
1. Register your application that you want to open
Update the Info.plist
by defining your application's custom and unique URL Scheme.
Note that your scheme name should be unique, otherwise if you have another application with the same URL scheme name installed on your device, then this will be determined runtime which one gets opened.
2. Include the previous URL scheme in your main application
You'll need to specify the URL scheme you want the app to be able to use with the canOpenURL:
method of the UIApplication
class. So open the main application's Info.plist
and add the other application's URL scheme to LSApplicationQueriesSchemes
. (Introduced in iOS 9.0)
3. Implement the action that opens your application
Now everything is set up, so you're good to write your code in your main application that opens your other app. This should looks something like this:
let appURLScheme = "MyAppToOpen://"
guard let appURL = URL(string: appURLScheme) else {
return
}
if UIApplication.shared.canOpenURL(appURL) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(appURL)
}
else {
UIApplication.shared.openURL(appURL)
}
}
else {
// Here you can handle the case when your other application cannot be opened for any reason.
}
Note that these changes requires a new release if you want your existing app (installed from AppStore) to open. If you want to open an application that you've already released to Apple AppStore, then you'll need to upload a new version first that includes your URL scheme registration.
spark-submit \
--class org.apache.spark.examples.SparkPi \
--master yarn \
--deploy-mode cluster \ # can be client for client mode
--executor-memory 2G \
--num-executors 5 \
/path/to/examples.jar \
1000
The shortest code would be:
Select CAST((@EndDateTime-@StartDateTime) as time(0)) '[hh:mm:ss]'
<table style='border:1px solid black'>
<tr>
<td>Derp</td>
</tr>
</table>
This should work. I use the shorthand syntax for borders.
My Solution
User.find()
.exec()
.then(users => {
const response = {
count: users.length,
users: users.map(user => {
return {
_id: user._id,
// other property
}
})
};
res.status(200).json(response);
}).catch(err => {
console.log(err);
res.status(500).json({
success: false
})
})
Add into the global properties section in the pom file:
<project>
...
<properties>
<additionalparam>-Xdoclint:none</additionalparam>
</properties>
The common solution provided here in the other answers (adding that property in the plugins section) did not work for some reason. Only by setting it globally I could build the javadoc jar successfully.
I got this error because I was using require('https')
where I should have been using require('http')
.
I use Eclipse Java EE edition
Create a "Dynamic Web Project"
Install a local server in the server view, for the version of Tomcat I'm using. Then debug, and run on that server for testing.
When I deploy I export the project to a war file.
I think you should mention dataType: 'json'
in ajax config and to access that value:
data[0].name
I use GWTDesigner http://www.instantiations.com/gwtdesigner/ which is not free but works well. Best of all, their customer support is top notch - very responsive.
If it is just one instance that needs to be wrapped over 2 or 3 lines I would just use a few <wbr>
in the string. It will treat those just like <br>
but it wont insert the line break if it isn't necessary.
<div id="w74" class="dpinfo">
adsfadsadsads<wbr>fadsadsadsfadsadsa<wbr>dsfadsadsadsfadsadsads<wbr>fadsadsadsfadsadsadsfa<wbr>dsadsadsfadsadsadsfadsad<wbr>sadsfadsadsads<wbr>fadsadsadsfadsads adsfadsads
</div>
Here is a fiddle.
For an IIS MVC 5 / Angular CLI ( Yes, I am well aware your problem is with Angular JS ) project with API I did the following:
web.config under <system.webServer>
node
<staticContent>
<remove fileExtension=".woff2" />
<mimeMap fileExtension=".woff2" mimeType="font/woff2" />
</staticContent>
<httpProtocol>
<customHeaders>
<clear />
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type, atv2" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
</customHeaders>
</httpProtocol>
global.asax.cs
protected void Application_BeginRequest() {
if (Request.Headers.AllKeys.Contains("Origin", StringComparer.OrdinalIgnoreCase) && Request.HttpMethod == "OPTIONS") {
Response.Flush();
Response.End();
}
}
That should fix your issues for both MVC and WebAPI without having to do all the other run around. I then created an HttpInterceptor in the Angular CLI project that automatically added in the the relevant header information. Hope this helps someone out in a similar situation.
NOTE : NOT tested!
string[] test(string[] myStringArray)
{
List<String> myStringList = new List<string>();
foreach (string s in myStringArray)
{
if (!myStringList.Contains(s))
{
myStringList.Add(s);
}
}
return myStringList.ToString();
}
Might do what you need...
EDIT Argh!!! beaten to it by rob by under a minute!
This is a solution for HTML tag and   etc and you can remove and add conditions to get the text without HTML and you can replace it by any.
convertHtmlToText(passHtmlBlock)
{
str = str.toString();
return str.replace(/<[^>]*(>|$)| |‌|»|«|>/g, 'ReplaceIfYouWantOtherWiseKeepItEmpty');
}
What about something like :
angle = angle % 360;
I also got the same running java JDBC in NetBeans. This is how it fixed
I use Xampp. In conf button of Apache I opened httpd.conf file and on first line I typed
# Set timezone to Europe/Athens UTC+02:00
SetEnv TZ Europe/Athens.
In conf button of MySQL I opened my.ini file and on last line I typed "Europe/Athens"
Stopped and started both Apache and MySQL
Problem fixed.
*(Local mechine time zone is different, but no problem.)
The C/A Browser forum sets what is and is not valid in a certificate, and what CA's should reject.
According to their Baseline Requirements for the Issuance and Management of Publicly-Trusted Certificates document, CAs must, since 2015, not issue certificats where the common name, or common alternate names fields contains a reserved IP or internal name, where reserved IP addresses are IPs that IANA has listed as reserved - which includes all NAT IPs - and internal names are any names that don't resolve on the public DNS.
Public IP addresses CAN be used (and the baseline requirements doc specifies what kinds of checks a CA must perform to ensure the applicant owns the IP).
The following is equivalent to your second code block:
var f = function () {
//Some logic here...
};
var fr = f;
fr(pars);
If you want to actually pass a reference to a function to some other function, you can do something like this:
function fiz(x, y, z) {
return x + y + z;
}
// elsewhere...
function foo(fn, p, q, r) {
return function () {
return fn(p, q, r);
}
}
// finally...
f = foo(fiz, 1, 2, 3);
f(); // returns 6
You're almost certainly better off using a framework for this sort of thing, though.
:nth-last-child(-n+2)
should do the trick
If you are doing this in more than one place in your application it would make sense to use a client-side JSON database because creating custom search functions that get called by array.filter() is messy and less maintainable than the alternative.
Check out ForerunnerDB which provides you with a very powerful client-side JSON database system and includes a very simple query language to help you do exactly what you are looking for:
// Create a new instance of ForerunnerDB and then ask for a database
var fdb = new ForerunnerDB(),
db = fdb.db('myTestDatabase'),
coll;
// Create our new collection (like a MySQL table) and change the default
// primary key from "_id" to "id"
coll = db.collection('myCollection', {primaryKey: 'id'});
// Insert our records into the collection
coll.insert([
{"name":"my Name","id":12,"type":"car owner"},
{"name":"my Name2","id":13,"type":"car owner2"},
{"name":"my Name4","id":14,"type":"car owner3"},
{"name":"my Name4","id":15,"type":"car owner5"}
]);
// Search the collection for the string "my nam" as a case insensitive
// regular expression - this search will match all records because every
// name field has the text "my Nam" in it
var searchResultArray = coll.find({
name: /my nam/i
});
console.log(searchResultArray);
/* Outputs
[
{"name":"my Name","id":12,"type":"car owner"},
{"name":"my Name2","id":13,"type":"car owner2"},
{"name":"my Name4","id":14,"type":"car owner3"},
{"name":"my Name4","id":15,"type":"car owner5"}
]
*/
Disclaimer: I am the developer of ForerunnerDB.
ps aux | grep -ie amarok | awk '{print $2}' | xargs kill -9
xargs(1): xargs -- construct argument list(s) and execute utility. Helpful when you want to pipe in arguments to something like kill
or ls
or so on.
Try:
if haystackstr.lower().find(needlestr.lower()) != -1:
# True
PUSHD and POPD should help in your case.
@echo off
:: Create a temporary drive letter mapped to your UNC root location
:: and effectively CD to that location
pushd \\server\soft
:: Do your work
WP15\setup.exe
robocopy.exe "WP15\Custom" /copyall "C:\Program Files (x86)\WP\Custom Templates"
Regedit.exe /s WPX5\Custom\Migrate.reg
:: Remove the temporary drive letter and return to your original location
popd
Type PUSHD /?
from the command line for more information.
The response from server is JSON String format. If the set dataType as 'json' jquery will attempt to use it directly. You need to set dataType as 'text' and then parse it manually.
$.ajax({
type: 'GET',
dataType: "text", // You need to use dataType text else it will try to parse it.
url: "http://someotherdomain.com/service.svc",
success: function (responseData, textStatus, jqXHR) {
console.log("in");
var data = JSON.parse(responseData['AuthenticateUserResult']);
console.log(data);
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed.');
}
});
There is a whole page in the MATLAB documentation dedicated to this topic: Array vs. Matrix Operations. The gist of it is below:
MATLAB® has two different types of arithmetic operations: array operations and matrix operations. You can use these arithmetic operations to perform numeric computations, for example, adding two numbers, raising the elements of an array to a given power, or multiplying two matrices.
Matrix operations follow the rules of linear algebra. By contrast, array operations execute element by element operations and support multidimensional arrays. The period character (
.
) distinguishes the array operations from the matrix operations. However, since the matrix and array operations are the same for addition and subtraction, the character pairs.+
and.-
are unnecessary.
NumPy has a numpy.mean
which is an arithmetic mean. Usage is as simple as this:
>>> import numpy
>>> a = [1, 2, 4]
>>> numpy.mean(a)
2.3333333333333335
Not suitable for 2008 when the question was asked, but these days this works well for me:
async function newImageSrc(src) {
// Get a reference to the image in whatever way suits.
let image = document.getElementById('image-id');
// Update the source.
img.src = src;
// Wait for it to load.
await new Promise((resolve) => { image.onload = resolve; });
// Done!
console.log('image loaded! do something...');
}
array_map
cannot change the values inside input array(s) while array_walk
can; in particular, array_map
never changes its arguments.array_map
cannot operate with the array keys, array_walk
can.array_map
returns a new array, array_walk
only returns true
. Hence, if you don't want to create an array as a result of traversing one array, you should use array_walk
.array_map
also can receive an arbitrary number of arrays and it can iterate over them in parallel, while array_walk
operates only on one.array_walk
can receive an extra arbitrary parameter to pass to the callback. This mostly irrelevant since PHP 5.3 (when anonymous functions were introduced).array_map
has the same length as that of the largest input array; array_walk
does not return an array but at the same time it cannot alter the number of elements of original array; array_filter
picks only a subset of the elements of the array according to a filtering function. It does preserve the keys.Example:
<pre>
<?php
$origarray1 = array(2.4, 2.6, 3.5);
$origarray2 = array(2.4, 2.6, 3.5);
print_r(array_map('floor', $origarray1)); // $origarray1 stays the same
// changes $origarray2
array_walk($origarray2, function (&$v, $k) { $v = floor($v); });
print_r($origarray2);
// this is a more proper use of array_walk
array_walk($origarray1, function ($v, $k) { echo "$k => $v", "\n"; });
// array_map accepts several arrays
print_r(
array_map(function ($a, $b) { return $a * $b; }, $origarray1, $origarray2)
);
// select only elements that are > 2.5
print_r(
array_filter($origarray1, function ($a) { return $a > 2.5; })
);
?>
</pre>
Result:
Array
(
[0] => 2
[1] => 2
[2] => 3
)
Array
(
[0] => 2
[1] => 2
[2] => 3
)
0 => 2.4
1 => 2.6
2 => 3.5
Array
(
[0] => 4.8
[1] => 5.2
[2] => 10.5
)
Array
(
[1] => 2.6
[2] => 3.5
)
AFAIK, RewriteBase is only used to fix cases where mod_rewrite is running in a .htaccess
file not at the root of a site and it guesses the wrong web path (as opposed to filesystem path) for the folder it is running in. So if you have a RewriteRule in a .htaccess in a folder that maps to http://example.com/myfolder
you can use:
RewriteBase myfolder
If mod_rewrite isn't working correctly.
Trying to use it to achieve something unusual, rather than to fix this problem sounds like a recipe to getting very confused.
Remember these 3 points:
Change onClick() from with onChange() in the . You can send the option value to a javascript function.
<select id="selector" onChange="doSomething(document.getElementById(this).options[document.getElementById(this).selectedIndex].value);">
<option value="option1"> Option1 </option>
<option value="option2"> Option2 </option>
<option value="optionN"> OptionN </option>
</select>
Use summarise
in the dplyr
package:
library(dplyr)
summarise(df, Average = mean(col_name, na.rm = T))
note: dplyr
supports both summarise
and summarize
.
If you want a destructive backspace, you'll need something like
"\b \b"
i.e. a backspace, a space, and another backspace.
I got insprired by the answers above (especially by the hint from @e.vyushin regarding the security of Math.random() ) and I came up with the following solution that uses the crypto.getRandomValues() to generate a rondom array of UInt32 values with the length of the password length.
Then, it loops through the array and devides each element by 2^32 (max value of a UInt32) to calculate the ratio between the actual value and the max. possible value. This ratio is then mapped to the charset string to determine which character of the string is picked.
console.log(createPassword(16,"letters+numbers+signs"));
function createPassword(len, charset) {
if (charset==="letters+numbers") {
var chars = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
} else if (charset==="letters+numbers+signs") {
var chars = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!§$%&/?#+-_@";
}
var arr = new Uint32Array(len);
var maxRange = Math.pow(2,32);
var passwd = '';
window.crypto.getRandomValues(arr);
for (let i=0;i<len;i++) {
var c = Math.floor(arr[i] / maxRange * chars.length + 1);
passwd += chars.charAt(c);
}
return passwd;
}
Thus, the code is able to use the advantage of the crypto-Class (improved security for the random value generation) and is adaptable to use any kind of charset the user wished. A next step would be to use regular expression strings to define the charset to be used.
To remove all OIDs from your database tables, you can use this Linux script:
First, login as PostgreSQL superuser:
sudo su postgres
Now run this script, changing YOUR_DATABASE_NAME with you database name:
for tbl in `psql -qAt -c "select schemaname || '.' || tablename from pg_tables WHERE schemaname <> 'pg_catalog' AND schemaname <> 'information_schema';" YOUR_DATABASE_NAME` ; do psql -c "alter table $tbl SET WITHOUT OIDS" YOUR_DATABASE_NAME ; done
I used this script to remove all my OIDs, since Npgsql 3.0 doesn't work with this, and it isn't important to PostgreSQL anymore.
Use String.PadLeft like this:
var result = input.ToString().PadLeft(length, '0');
As chmullig wrote, use Jenkins. Some additional points:
In fact, arguably it was Oracle who did the forking! And technically, too, that's kinda what happened.
It's interesting to see what comes out of "Hudson" though. While the "Winston summarizes the state and rosy future of the Hudson project" stuff they posted on the (new) Hudson website originally seemed like odd humour to me, perhaps this was a purposeful takeover, and the Sonatype guys actually have some big ideas up their sleeve. This analysis, suggesting a deliberate strategy by Oracle/Sonatype to oust Kohsuke and crew to create a more "enterprisy" Hudson is a very interesting read!
In any case, this brief comparison a fortnight after the split—while not exactly scientific—shows Jenkins to be by far more active of the two projects.
...and a little background info:
The creator of Hudson, Kohsuke Kawaguchi, started the project on his free time, even if he was working for Sun Microsystems and later paid by them to develop it further. As @erickson noted at another SO question,
[Hudson/Jenkins] is the product of a single genius intellect—Kohsuke Kawaguchi. Because of that, it's consistent, coherent, and rock solid.
After the acquisition by Oracle, Kohsuke didn't hang around for long (due to lack of monitors...? ;-]), and went to work for CloudBees. What started in late 2010 as conflict over tools between the dev community and Oracle and ended in the rename/fork/split is well documented in the links chmullig provided. To me, that whole conundrum speaks, perhaps more than anything else, to Oracle's utter inability or unwillingness to sponsor an open-source project in a way that keeps all parties (Oracle, developers, users) happy. It's not in their DNA or something, as we've seen in other cases too.
Given all of the above, I would personally follow Kohsuke and other core developers in this matter, and go with Jenkins.
An abstract class can have a constructor BUT you can not create an object of abstract class so how do you use that constructor?
Thing is when you inherit that abstract class in your subclass you can pass values to its(abstract's) constructor through super(value) method in your subclass and no you don't inherit a constructor.
so using super you can pass values in a constructor of the abstract class and as far as I remember it has to be the first statement in your method or constructor.
Try adding this at the end of your code:
import matplotlib.pyplot as plt
plt.title('add title here')
Just run in Terminal react-native start
:
cd your react native app directory/ react-native start
It will start up the packager, now don't close this terminal window, in another terminal window run your project. This is the only want that I found to get it working properly.
NERDcommenter is an excellent plugin for commenting which automatically detects a number of filetypes and their associated comment characters. Ridiculously easy to install using Pathogen.
Comment with <leader>cc
. Uncomment with <leader>cu
. And toggle comments with <leader>c<space>
.
(The default <leader>
key in vim is \
)
Ternary operator works because the first part of it returns a Boolean value. In your case, jQuery's css method returns the jQuery object, thus not valid for ternary operation.
Try This:
window.scrollBy(0,180); // horizontal and vertical scroll increments
What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.
I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)
git rm
will remove the file from the index and working directory ( only index if you used --cached
) so that the deletion is staged for next commit.
Another advantage of using the '[[' operator is that it works both with data.frame and data.table. So if the function has to be made running for both data.frame and data.table, and you want to extract a column from it as a vector then
data[["column_name"]]
is best.
Your going to use the checkbox1.checked
property in your if statement, this returns true or false depending on weather it is checked or not.
Edit ImageUploader.php - either remove line (cause BulletProofException not used anywhere)
class BulletProofException extends Exception{}
or move it under line
namespace BulletProof;
With Angular2
RC5 and angular-cli 1.0.0-beta.11-webpack.8
you can achieve this with css imports.
Just install font awesome:
npm install font-awesome --save
and then import font-awesome in one of your configured style files:
@import '../node_modules/font-awesome/css/font-awesome.css';
(style files are configured in angular-cli.json
)
You can use this code snippet for creating a two buttoned Alert box,
import 'package:flutter/material.dart';
class BaseAlertDialog extends StatelessWidget {
//When creating please recheck 'context' if there is an error!
Color _color = Color.fromARGB(220, 117, 218 ,255);
String _title;
String _content;
String _yes;
String _no;
Function _yesOnPressed;
Function _noOnPressed;
BaseAlertDialog({String title, String content, Function yesOnPressed, Function noOnPressed, String yes = "Yes", String no = "No"}){
this._title = title;
this._content = content;
this._yesOnPressed = yesOnPressed;
this._noOnPressed = noOnPressed;
this._yes = yes;
this._no = no;
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: new Text(this._title),
content: new Text(this._content),
backgroundColor: this._color,
shape:
RoundedRectangleBorder(borderRadius: new BorderRadius.circular(15)),
actions: <Widget>[
new FlatButton(
child: new Text(this._yes),
textColor: Colors.greenAccent,
onPressed: () {
this._yesOnPressed();
},
),
new FlatButton(
child: Text(this._no),
textColor: Colors.redAccent,
onPressed: () {
this._noOnPressed();
},
),
],
);
}
}
To show the dialog you can have a method that calls it NB after importing BaseAlertDialog
class
_confirmRegister() {
var baseDialog = BaseAlertDialog(
title: "Confirm Registration",
content: "I Agree that the information provided is correct",
yesOnPressed: () {},
noOnPressed: () {},
yes: "Agree",
no: "Cancel");
showDialog(context: context, builder: (BuildContext context) => baseDialog);
}
OUTPUT WILL BE LIKE THIS
try using ";" to separate the commands if you are in verions two e.g.
command: "sleep 20; echo 'a'"
If you're okay adding more third-party packages, I used the angular2-moment library. Installation was pretty straightforward, and you should follow the latest instructions on the README. I also installed typings as a result of this.
Worked like a charm for me, and barely added any code to get it working.
For me the bold work when I change the font style from font-family: 'Open Sans', sans-serif;
to Arial
You can also do this.
//find the index of the CompanyName column
int columnIndex = thisReader.GetOrdinal("CompanyName");
//Get the value of the column. Will throw if the value is null.
string companyName = thisReader.GetString(columnIndex);
add this in the parent div at the bottom
<div style="clear:both"></div>
Use the ASCII to Integer atoi()
function which accepts a string and converts it into an integer:
#include <stdlib.h>
int num = atoi("23"); // 23
If the string contains a decimal, the number will be truncated:
int num = atoi("23.21"); // 23
Creation time isn't stored.
What are stored are three timestamps (generally, they can be turned off on certain filesystems or by certain filesystem options):
a "Change" to the file is counted as permission changes, rename etc. While the modification is contents only.
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.TempValue = "Index Action called at HomeController";
return View();
}
[ChildActionOnly]
public ActionResult ChildAction(string param)
{
ViewBag.Message = "Child Action called. " + param;
return View();
}
}
The code is initially invoking an Index action that in turn returns two Index views and at the View level it calls the ChildAction named “ChildAction”.
@{
ViewBag.Title = "Index";
}
<h2>
Index
</h2>
<!DOCTYPE html>
<html>
<head>
<title>Error</title>
</head>
<body>
<ul>
<li>
@ViewBag.TempValue
</li>
<li>@ViewBag.OnExceptionError</li>
@*<li>@{Html.RenderAction("ChildAction", new { param = "first" });}</li>@**@
@Html.Action("ChildAction", "Home", new { param = "first" })
</ul>
</body>
</html>
Copy and paste the code to see the result .thanks
Insert into table(col1,col2) select col1,col2 from table_2;
Please refer to MySQL documentation on INSERT Statement
Underscore.js is a good library for these sorts of operations - it uses the builtin routines such as Array.filter if available, or uses its own if not.
http://documentcloud.github.com/underscore/
The docs will give an idea of use - the javascript lambda syntax is nowhere near as succinct as ruby or others (I always forget to add an explicit return statement for example) and scope is another easy way to get caught out, but you can do most things quite easily with the exception of constructs such as lazy list comprehensions.
From the docs for .select() (.filter() is an alias for the same)
Looks through each value in the list, returning an array of all the values that pass a truth test (iterator). Delegates to the native filter method, if it exists.
var evens = _.select([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [2, 4, 6]
<a href="http://the.url.com/page.html">
<span onclick="hide(); return false">Hide me</span>
</a>
This is the easiest solution.
If I've understood your problem correctly, there are two possible problems here:
resultset
is null
- I assume that this can't be the case as if it was you'd get an exception in your while loop and nothing would be output.resultset.getString(i++)
will get columns 1,2,3 and so on from each subsequent row.I think that the second point is probably your problem here.
Lets say you only had 1 row returned, as follows:
Col 1, Col 2, Col 3
A , B, C
Your code as it stands would only get A - it wouldn't get the rest of the columns.
I suggest you change your code as follows:
ResultSet resultset = ...;
ArrayList<String> arrayList = new ArrayList<String>();
while (resultset.next()) {
int i = 1;
while(i <= numberOfColumns) {
arrayList.add(resultset.getString(i++));
}
System.out.println(resultset.getString("Col 1"));
System.out.println(resultset.getString("Col 2"));
System.out.println(resultset.getString("Col 3"));
System.out.println(resultset.getString("Col n"));
}
Edit:
To get the number of columns:
ResultSetMetaData metadata = resultset.getMetaData();
int numberOfColumns = metadata.getColumnCount();
by using replaceChild():
<html>
<head>
</head>
<body>
<div>
<a id="myAnchor" href="http://www.stackoverflow.com">StackOverflow</a>
</div>
<script type="text/JavaScript">
var myAnchor = document.getElementById("myAnchor");
var mySpan = document.createElement("span");
mySpan.innerHTML = "replaced anchor!";
myAnchor.parentNode.replaceChild(mySpan, myAnchor);
</script>
</body>
</html>
Here's my post-RIA entity-update method (for the Ef6 time frame):
public static void UpdateSegment(ISegment data)
{
if (data == null) throw new ArgumentNullException("The expected Segment data is not here.");
var context = GetContext();
var originalData = context.Segments.SingleOrDefault(i => i.SegmentId == data.SegmentId);
if (originalData == null) throw new NullReferenceException("The expected original Segment data is not here.");
FrameworkTypeUtility.SetProperties(data, originalData);
context.SaveChanges();
}
Note that FrameworkTypeUtility.SetProperties()
is a tiny utility function I wrote long before AutoMapper on NuGet:
public static void SetProperties<TIn, TOut>(TIn input, TOut output, ICollection<string> includedProperties)
where TIn : class
where TOut : class
{
if ((input == null) || (output == null)) return;
Type inType = input.GetType();
Type outType = output.GetType();
foreach (PropertyInfo info in inType.GetProperties())
{
PropertyInfo outfo = ((info != null) && info.CanRead)
? outType.GetProperty(info.Name, info.PropertyType)
: null;
if (outfo != null && outfo.CanWrite
&& (outfo.PropertyType.Equals(info.PropertyType)))
{
if ((includedProperties != null) && includedProperties.Contains(info.Name))
outfo.SetValue(output, info.GetValue(input, null), null);
else if (includedProperties == null)
outfo.SetValue(output, info.GetValue(input, null), null);
}
}
}
Use detectOS.js:
var Detect = {
init: function () {
this.OS = this.searchString(this.dataOS);
},
searchString: function (data) {
for (var i=0;i<data.length;i++) {
var dataString = data[i].string;
var dataProp = data[i].prop;
if (dataString) {
if (dataString.indexOf(data[i].subString) != -1)
return data[i].identity;
}
else if (dataProp)
return data[i].identity;
}
},
dataOS : [
{
string: navigator.platform,
subString: 'Win',
identity: 'Windows'
},
{
string: navigator.platform,
subString: 'Mac',
identity: 'macOS'
},
{
string: navigator.userAgent,
subString: 'iPhone',
identity: 'iOS'
},
{
string: navigator.userAgent,
subString: 'iPad',
identity: 'iOS'
},
{
string: navigator.userAgent,
subString: 'iPod',
identity: 'iOS'
},
{
string: navigator.userAgent,
subString: 'Android',
identity: 'Android'
},
{
string: navigator.platform,
subString: 'Linux',
identity: 'Linux'
}
]
};
Detect.init();
console.log("We know your OS – it's " + Detect.OS + ". We know everything about you.");
If the image is placed inside the 'src' folder, use the following:
<img src={require('../logo.png')} alt="logo" className="brand-logo"/>
With System.getProperty("user.dir")
you get the "Base of non-absolute paths" look at
For anyone else looking for multi-line comments in Python - using the triple quote format can have some problematic consequences, as I've just learned the hard way. Consider this:
this_dict = {
'name': 'Bob',
"""
This is a multiline comment in the middle of a dictionary
"""
'species': 'Cat'
}
The multi-line comment will be tucked into the next string, messing up the
'species'
key. Better to just use #
for comments.
I worked on this for too long. The answer that helped me was at: send Content-Type: application/json post with node.js
Which uses the following format:
request({
url: url,
method: "POST",
headers: {
"content-type": "application/json",
},
json: requestData
// body: JSON.stringify(requestData)
}, function (error, resp, body) { ...
Since you tagged Java-ee as well - then YES it is possible.
and in core java as well it is possible using static blocks
and check this How can you run a Java program without main method?
Edit:
as already pointed out in other answers - it does not support from Java 7
Test with this in trackingCode.html:
<script type="text/javascript">
$(function() {
show_alert();
function show_alert() {
alert("Inside the jQuery ready");
}
});
</script>
If you are styling calc in a GWT project, its parser might not parse calc for you as it did not for me... the solution is to wrap it in a css literal like this:
height: literal("-moz-calc(100% - (20px + 30px))");
height: literal("-webkit-calc(100% - (20px + 30px))");
height: literal("calc(100% - (20px + 30px))");
You can also just access $s1 like an array, if you only need to access it:
$s1 = "hello world";
echo $s1[0]; // -> h
You could also set them to float to the right.
#ul_top_hypers li {
float: right;
}
This allows them to still be block level, but will appear on the same line.
DTD is pretty much deprecated because it is limited in its usefulness as a schema language, doesn't support namespace, and does not support data type. In addition, DTD's syntax is quite complicated, making it difficult to understand and maintain..
[answer written based on python 3.4; the metaclass syntax differs in 2 but I think the technique will still work]
You can do this with a metaclass...mostly. Dappawit's almost works, but I think it has a flaw:
class MetaFoo(type):
@property
def thingy(cls):
return cls._thingy
class Foo(object, metaclass=MetaFoo):
_thingy = 23
This gets you a classproperty on Foo, but there's a problem...
print("Foo.thingy is {}".format(Foo.thingy))
# Foo.thingy is 23
# Yay, the classmethod-property is working as intended!
foo = Foo()
if hasattr(foo, "thingy"):
print("Foo().thingy is {}".format(foo.thingy))
else:
print("Foo instance has no attribute 'thingy'")
# Foo instance has no attribute 'thingy'
# Wha....?
What the hell is going on here? Why can't I reach the class property from an instance?
I was beating my head on this for quite a while before finding what I believe is the answer. Python @properties are a subset of descriptors, and, from the descriptor documentation (emphasis mine):
The default behavior for attribute access is to get, set, or delete the attribute from an object’s dictionary. For instance,
a.x
has a lookup chain starting witha.__dict__['x']
, thentype(a).__dict__['x']
, and continuing through the base classes oftype(a)
excluding metaclasses.
So the method resolution order doesn't include our class properties (or anything else defined in the metaclass). It is possible to make a subclass of the built-in property decorator that behaves differently, but (citation needed) I've gotten the impression googling that the developers had a good reason (which I do not understand) for doing it that way.
That doesn't mean we're out of luck; we can access the properties on the class itself just fine...and we can get the class from type(self)
within the instance, which we can use to make @property dispatchers:
class Foo(object, metaclass=MetaFoo):
_thingy = 23
@property
def thingy(self):
return type(self).thingy
Now Foo().thingy
works as intended for both the class and the instances! It will also continue to do the right thing if a derived class replaces its underlying _thingy
(which is the use case that got me on this hunt originally).
This isn't 100% satisfying to me -- having to do setup in both the metaclass and object class feels like it violates the DRY principle. But the latter is just a one-line dispatcher; I'm mostly okay with it existing, and you could probably compact it down to a lambda or something if you really wanted.
$db = new mysqli('Server_Name', 'Name', 'password', 'database_name');
In computer science, parsing is the process of analysing text to determine if it belongs to a specific language or not (i.e. is syntactically valid for that language's grammar). It is an informal name for the syntactic analysis process.
For example, suppose the language a^n b^n
(which means same number of characters A followed by the same number of characters B). A parser for that language would accept AABB
input and reject the AAAB
input. That is what a parser does.
In addition, during this process a data structure could be created for further processing. In my previous example, it could, for instance, to store the AA
and BB
in two separate stacks.
Anything that happens after it, like giving meaning to AA
or BB
, or transform it in something else, is not parsing. Giving meaning to parts of an input sequence of tokens is called semantic analysis.
I think the best way for understanding the parsing concept is to begin with the simpler concepts. The simplest one in language processing subject is the finite automaton. It is a formalism to parsing regular languages, such as regular expressions.
It is very simple, you have an input, a set of states and a set of transitions. Consider the following language built over the alphabet { A, B }
, L = { w | w starts with 'AA' or 'BB' as substring }
. The automaton below represents a possible parser for that language whose all valid words starts with 'AA' or 'BB'.
A-->(q1)--A-->(qf)
/
(q0)
\
B-->(q2)--B-->(qf)
It is a very simple parser for that language. You start at (q0)
, the initial state, then you read a symbol from the input, if it is A
then you move to (q1)
state, otherwise (it is a B
, remember the remember the alphabet is only A
and B
) you move to (q2)
state and so on. If you reach (qf)
state, then the input was accepted.
As it is visual, you only need a pencil and a piece of paper to explain what a parser is to anyone, including a child. I think the simplicity is what makes the automata the most suitable way to teaching language processing concepts, such as parsing.
Finally, being a Computer Science student, you will study such concepts in-deep at theoretical computer science classes such as Formal Languages and Theory of Computation.
In my case, I used the ssl
module to "workaround" the certification like so:
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
Then to read your link content, you can use:
urllib.request.urlopen(urllink)
No, find() method is not a member of std::list
.
Instead, use std::find
from <algorithm>
std :: list < int > l;
std :: list < int > :: iterator pos;
l.push_back(1);
l.push_back(2);
l.push_back(3);
l.push_back(4);
l.push_back(5);
l.push_back(6);
int elem = 3;
pos = find(l.begin() , l.end() , elem);
if(pos != l.end() )
std :: cout << "Element is present. "<<std :: endl;
else
std :: cout << "Element is not present. "<<std :: endl;
This answer from another forum solved the problem.
(substitute your own range for the "I:I" shown here)
Re: CountA not working in VBA
Should be:
Nonblank = Application.WorksheetFunction.CountA(Range("I:I"))
You have to refer to ranges in the vba format, not the in-excel format.
Here's a simple function that serves to explain the usage:
def print_wrap(arg1, *args, **kwargs):
print(arg1)
print(args)
print(kwargs)
print(arg1, *args, **kwargs)
Any arguments that are not specified in the function definition will be put in the args
list, or the kwargs
list, depending on whether they are keyword arguments or not:
>>> print_wrap('one', 'two', 'three', end='blah', sep='--')
one
('two', 'three')
{'end': 'blah', 'sep': '--'}
one--two--threeblah
If you add a keyword argument that never gets passed to a function, an error will be raised:
>>> print_wrap('blah', dead_arg='anything')
TypeError: 'dead_arg' is an invalid keyword argument for this function
let content = "<center><h1>404 Not Found</h1></center>"
let result = $("<div/>").html(content).text()
content: <center><h1>404 Not Found</h1></center>
,
result: "404 Not Found"
This is exactly what the in
operator is for. Use it like this:
if (index in currentData)
{
Ti.API.info(index + " exists: " + currentData[index]);
}
The accepted answer is wrong, it will give a false negative if the value at index
is undefined
:
const currentData = ['a', undefined], index = 1;_x000D_
_x000D_
if (index in currentData) {_x000D_
console.info('exists');_x000D_
}_x000D_
// ...vs..._x000D_
if (typeof currentData[index] !== 'undefined') {_x000D_
console.info('exists');_x000D_
} else {_x000D_
console.info('does not exist'); // incorrect!_x000D_
}
_x000D_
Zach had this one right.. using his method you could also make a seemingly "multi-dimensional" array.. I created a quick example at JSFiddle http://jsfiddle.net/LcnvJ/2/
// array[0][0] will produce brian
// array[0][1] will produce james
// array[1][0] will produce kevin
// array[1][1] will produce haley
var array = [];
array[0] = "brian,james,doug".split(",");
array[1] = "kevin,haley,steph".split(",");
document.getElementById('myinput').onkeydown = function(e) {
if(!((e.keyCode > 95 && e.keyCode < 106)
|| (e.keyCode > 47 && e.keyCode < 58)
|| e.keyCode == 8
|| e.keyCode == 9)) {
return false;
}
}
In Python 3, /
is float division
In Python 2, /
is integer division (assuming int
inputs)
In both 2 and 3, //
is integer division
(To get float division in Python 2 requires either of the operands be a float, either as 20.
or float(20)
)
myList = [i.split('\t')[0] for i in myList]
By Using Gson you can send json response see below code
You can see this code
@WebServlet(urlPatterns = {"/jsonResponse"})
public class JsonResponse extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
Student student = new Student(12, "Ram Kumar", "Male", "1234565678");
Subject subject1 = new Subject(1, "Computer Fundamentals");
Subject subject2 = new Subject(2, "Computer Graphics");
Subject subject3 = new Subject(3, "Data Structures");
Set subjects = new HashSet();
subjects.add(subject1);
subjects.add(subject2);
subjects.add(subject3);
student.setSubjects(subjects);
Address address = new Address(1, "Street 23 NN West ", "Bhilai", "Chhattisgarh", "India");
student.setAddress(address);
Gson gson = new Gson();
String jsonData = gson.toJson(student);
PrintWriter out = response.getWriter();
try {
out.println(jsonData);
} finally {
out.close();
}
}
}
helpful from json response from servlet in java
check it in mdpi device.. If the ad displays correctly, the error should be in "px" to "dip" conversion..
you can get the key value pair as
<pre>
function test(){
var data=[{'com':'something'},{'com':'some other thing'}];
$.each(data, function(key,value) {
alert(key);
alert(value.com);
});
}
</pre>
Use textView.text
for getter and setter, ex:
val textView = findViewById<TextView>(R.id.textView)
// Set text
textView.text = "Hello World!"
// Get text
val textViewString = textView.text.toString()
when you add a new data set to a geom you need to use the data=
argument. Or put the arguments in the proper order mapping=..., data=...
. Take a look at the arguments for ?geom_line
.
Thus:
p + geom_line(data=df.last, aes(HrEnd, MWh, group=factor(Date)), color="red")
Or:
p + geom_line(aes(HrEnd, MWh, group=factor(Date)), df.last, color="red")
According to Google documentation they said that this is the best way to do it. First create this function to find out how many markers there are/
function setMapOnAll(map1) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map1);
}
}
Next create another function to take away all these markers
function clearMarker(){
setMapOnAll(null);
}
Then create this final function to erase all the markers when ever this function is called upon.
function delateMarkers(){
clearMarker()
markers = []
//console.log(markers) This is just if you want to
}
Hope that helped good luck
task :build => [:some_other_tasks] do
build
end
task :build_all do
[:debug, :release].each { |t| build t }
end
def build(type = :debug)
# ...
end
rake
's idioms, here are your possibilities, compiled from past answers:This always executes the task, but it doesn't execute its dependencies:
Rake::Task["build"].execute
This one executes the dependencies, but it only executes the task if it has not already been invoked:
Rake::Task["build"].invoke
This first resets the task's already_invoked state, allowing the task to then be executed again, dependencies and all:
Rake::Task["build"].reenable
Rake::Task["build"].invoke
Note that dependencies already invoked are not automatically re-executed unless they are re-enabled. In Rake >= 10.3.2, you can use the following to re-enable those as well:
Rake::Task["build"].all_prerequisite_tasks.each(&:reenable)
According to new Gradle based build system
. We have to put assets
under main
folder.
Or simply right click on your project and create it like
File > New > folder > assets Folder
import java.io.*;
public class DataStreamExample {
public static void main(String args[]){
try{
FileWriter fin=new FileWriter("testout.txt");
BufferedWriter d = new BufferedWriter(fin);
int a[] = new int[3];
a[0]=1;
a[1]=22;
a[2]=3;
String s="";
for(int i=0;i<3;i++)
{
s=Integer.toString(a[i]);
d.write(s);
d.newLine();
}
System.out.println("Success");
d.close();
fin.close();
FileReader in=new FileReader("testout.txt");
BufferedReader br=new BufferedReader(in);
String i="";
int sum=0;
while ((i=br.readLine())!= null)
{
sum += Integer.parseInt(i);
}
System.out.println(sum);
}catch(Exception e){System.out.println(e);}
}
}
OUTPUT:: Success 26
Also, I used array to make it simple.... you can directly take integer input and convert it into string and send it to file. input-convert-Write-Process... its that simple.
You would want to use __slots__
if you are going to instantiate a lot (hundreds, thousands) of objects of the same class. __slots__
only exists as a memory optimization tool.
It's highly discouraged to use __slots__
for constraining attribute creation.
Pickling objects with __slots__
won't work with the default (oldest) pickle protocol; it's necessary to specify a later version.
Some other introspection features of python may also be adversely affected.
If you rename your Database, MS SQL Server does not rename the underlying files.
Following query gives you the current name of the database and the Logical file name (which might be the original name of the Database when it was created) and also corresponding physical file names.
Note: Un-comment the last line to see only the actual data files
select db.database_id,
db.name "Database Name",
files.name "Logical File Name",
files.physical_name
from sys.master_files files
join sys.databases db on db.database_id = files.database_id
-- and files.type_desc = 'ROWS'
Reference:
In computer programming, particularly in the C, C++, and C# programming languages, a variable or object declared with the volatile
keyword usually has special properties related to optimization and/or threading. Generally speaking, the volatile
keyword is intended to prevent the (pseudo)compiler from applying any optimizations on the code that assume values of variables cannot change "on their own." (c) Wikipedia
getconf uses the fewest system calls:
$ strace getconf LONG_BIT | wc -l
253
$ strace arch | wc -l
280
$ strace uname -m | wc -l
281
$ strace grep -q lm /proc/cpuinfo | wc -l
301
A bit of a hack, but it works fine for me:
Integer id = 2;
String query = "SELECT * FROM table WHERE id = ?";
PreparedStatement statement = m_connection.prepareStatement( query );
statement.setObject( 1, value );
String statementText = statement.toString();
query = statementText.substring( statementText.indexOf( ": " ) + 2 );
not() is a function in xpath (as opposed to an operator), so
//a[not(contains(@id, 'xx'))]
For my case, dmatrices
in patsy
solved my problem. Actually, this function is designed for the generation of dependent and independent variables from a given DataFrame with an R-style formula string. But it can be used for the generation of dummy features from the categorical features. All you need to do would be drop the column 'Intercept' that is generated by dmatrices
automatically regardless of your original DataFrame.
import pandas as pd
from patsy import dmatrices
df_original = pd.DataFrame({
'A': ['red', 'green', 'red', 'green'],
'B': ['car', 'car', 'truck', 'truck'],
'C': [10,11,12,13],
'D': ['alice', 'bob', 'charlie', 'alice']},
index=[0, 1, 2, 3])
_, df_dummyfied = dmatrices('A ~ A + B + C + D', data=df_original, return_type='dataframe')
df_dummyfied = df_dummyfied.drop('Intercept', axis=1)
df_dummyfied.columns
Index([u'A[T.red]', u'B[T.truck]', u'D[T.bob]', u'D[T.charlie]', u'C'], dtype='object')
df_dummyfied
A[T.red] B[T.truck] D[T.bob] D[T.charlie] C
0 1.0 0.0 0.0 0.0 10.0
1 0.0 0.0 1.0 0.0 11.0
2 1.0 1.0 0.0 1.0 12.0
3 0.0 1.0 0.0 0.0 13.0
It can be done using SQL Server Import and Export Wizard. But if you're familiar with SSIS and don't want to run the SQL Server Import and Export Wizard, create an SSIS package that uses the Excel Source and the SQL Server Destination in the data flow.
You can do something like this:
HTML:
<div class='div'>
<label>Something</label>
<input type='text' class='input'/>
<div>
CSS:
.div{
margin-bottom: 10px;
display: grid;
grid-template-columns: 1fr 4fr;
}
.input{
width: 50%;
}
Hope this helps ! :)
The instruction given at VS Code Command Line for launching a path are incorrect; the leading colon shown in the example doesn't work. However, launching with a backslash terminated directory name opens the specified directory as expected.
So, for example,
code C:\Users\DAVE\Documents\Programming\Angular\StringCalculator\src\
opens the Visual Studio Code editor in directory C:\Users\DAVE\Documents\Programming\Angular\StringCalculator\src
.
Important: The terminal backslash, though optional, is useful, as it makes clear that the intend is to open a directory, as opposed to a file. Bear in mind that file name extensions are, and always have been, optional.
Beware: The directory that gets appended to the PATH list is the \bin
directory, and the shell command code
launches a Windows NT Command script.
Hence, when incorporated into another shell script, code
must be called or started if you expect the remainder of the script to run. Thankfully, I discovered this before my first test of a new shell script that I am creating to start an Angular 2 project in a local Web server, my default Web browser, and Visual Studio Code, all at once.
Following is my Angular startup script, adapted to eliminate a dependency on one of my system utilities that is published elsewhere, but not strictly required.
@echo off
goto SKIPREM
=========================================================================
Name: StartAngularApp.CMD
Synopsis: Start the Angular 2 application installed in a specified
directory.
Arguments: %1 = OPTIONAL: Name of directory in which to application
is installed
Remarks: If no argument is specified, the application must be in
the current working directory.
This is a completely generalized Windows NT command
script (shell script) that uses the NPM Angular CLI to
load an Angular 2 application into a Node development
Web server, the default Web browser, and the Visual
Studio Code text editor.
Dependencies: Unless otherwise specified in the command line, the
application is created in the current working directory.
All of the following shell scripts and programs must be
installed in a directory that is on the Windows PATH
directory list.
1) ShowTime.CMD
2) WWPause.exe
3) WWSleep.exe
4) npm (the Node Package Manager) and its startup
script, npm.cmd, must be accessible via the Windows
PATH environment string. By default, this goes into
directory C:\Program Files\nodejs.
5) The Angular 2 startup script, ng.cmd, and the Node
Modules library must be installed for global access.
By default, these go into directory %AppData%\npm.
Author: David A. Gray
Created: Monday, 23 April 2017
-----------------------------------------------------------------------
Revision History
-----------------------------------------------------------------------
Date By Synopsis
---------- --- --------------------------------------------------------
2017/04/23 DAG Script created, tested, and deployed.
=======================================================================
:SKIPREM
echo BOJ %~0, version %~t0
echo.
echo -------------------------------------------------------
echo Displaying the current node.js version:
echo -------------------------------------------------------
echo.
node -v
echo.
echo -------------------------------------------------------
echo Displaying the current Node Package Manager version:
echo -------------------------------------------------------
echo.
call npm -v
echo.
echo -------------------------------------------------------
echo Loading Angular starter application %1
echo into a local Web server, the default Web browser, and
echo the Visual Studio Code text editor.
echo -------------------------------------------------------
echo.
if "%1" neq "" (
echo.
echo -------------------------------------------------------
echo Starting the Angular application in directory %1
echo -------------------------------------------------------
echo.
cd "%~1"
call code %1\src\
) else (
echo.
echo -------------------------------------------------------
echo Starting the Angular application in directory %CD%
echo -------------------------------------------------------
echo.
call code %CD%\src\
)
call ng serve --open
echo.
echo -------------------------------------------------------
echo %~nx0 Done!
echo -------------------------------------------------------
echo.
Pause
Perhaps another way to code conditional constructs in XML:
<rule>
<if>
<conditions>
<condition var="something" operator=">">400</condition>
<!-- more conditions possible -->
</conditions>
<statements>
<!-- do something -->
</statements>
</if>
<elseif>
<conditions></conditions>
<statements></statements>
</elseif>
<else>
<statements></statements>
</else>
</rule>
Pandas merge
offers a naive, fast solution to the problem:
# given the lists
x, y, z = [1, 2, 3], [4, 5], [6, 7]
# get dfs with same, constant index
x = pd.DataFrame({'x': x}, index=np.repeat(0, len(x))
y = pd.DataFrame({'y': y}, index=np.repeat(0, len(y))
z = pd.DataFrame({'z': z}, index=np.repeat(0, len(z))
# get all permutations stored in a new df
df = pd.merge(x, pd.merge(y, z, left_index=True, righ_index=True),
left_index=True, right_index=True)
I easily solve this problem by right clicking on my solution and then clicking on the Enable NuGet Package Restore option
(P.S: Ensure that you have the Nuget Install From Tools--> Extensions and Update--> Nuget Package Manager for Visual Studio 2013. If not install this extention first)
Hope it helps.
If the commits you want to fix are the latest ones, and just a couple of them, you can use a combination of git reset
and git stash
to go back an commit them again after configuring the right name and email.
The sequence will be something like this (for 2 wrong commits, no pending changes):
git config user.name <good name>
git config user.email <good email>
git reset HEAD^
git stash
git reset HEAD^
git commit -a
git stash pop
git commit -a
After build. Refresh project and if still persist just right click Problems tab in eclipse and choose delete all.
It often happens if you do maven install and eclipse properties files do not get updated properly. Even though your project does not have any errors. Hopefully!
I had this issue, by mistake I had placed @Transient
annotation above that particular attribute. In my case this error make sense.
Try:
chmod -R ug+rwx <dir>
where <dir>
is the directory on which you
want to change permissions.
A map-reduce solution:
var urlParams = location.search.split(/[?&]/).slice(1).map(function(paramPair) {
return paramPair.split(/=(.+)?/).slice(0, 2);
}).reduce(function (obj, pairArray) {
obj[pairArray[0]] = pairArray[1];
return obj;
}, {});
Usage:
For url: http://example.com?one=1&two=2
console.log(urlParams.one) // 1
console.log(urlParams.two) // 2
This one seems the easiest to me: http://jsfiddle.net/thomporter/DwKZh/
(Code is not mine, I accidentally stumbled upon it)
angular.module('myApp', []).directive('numbersOnly', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
// this next if is necessary for when using ng-required on your input.
// In such cases, when a letter is typed first, this parser will be called
// again, and the 2nd time, the value will be undefined
if (inputValue == undefined) return ''
var transformedInput = inputValue.replace(/[^0-9]/g, '');
if (transformedInput!=inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
You'll need to use the HTML()
or display()
functions from IPython's display module:
from IPython.display import display, HTML
# Assuming that dataframes df1 and df2 are already defined:
print "Dataframe 1:"
display(df1)
print "Dataframe 2:"
display(HTML(df2.to_html()))
Note that if you just print df1.to_html()
you'll get the raw, unrendered HTML.
You can also import from IPython.core.display
with the same effect
ORA-12899: value too large for column "DJ"."CUSTOMERS"."ADDRESS" (actual: 25, maximum: 2
Tells you what the error is. Address can hold maximum of 20 characters, you are passing 25 characters.
The following configuration taken from MSDN can be applied to enable tracing on your WCF service.
<configuration>
<system.diagnostics>
<sources>
<source name="System.ServiceModel"
switchValue="Information, ActivityTracing"
propagateActivity="true" >
<listeners>
<add name="xml"/>
</listeners>
</source>
<source name="System.ServiceModel.MessageLogging">
<listeners>
<add name="xml"/>
</listeners>
</source>
<source name="myUserTraceSource"
switchValue="Information, ActivityTracing">
<listeners>
<add name="xml"/>
</listeners>
</source>
</sources>
<sharedListeners>
<add name="xml"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData="Error.svclog" />
</sharedListeners>
</system.diagnostics>
</configuration>
To view the log file, you can use "C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\SvcTraceViewer.exe".
If "SvcTraceViewer.exe" is not on your system, you can download it from the "Microsoft Windows SDK for Windows 7 and .NET Framework 4" package here:
You don't have to install the entire thing, just the ".NET Development / Tools" part.
When/if it bombs out during installation with a non-sensical error, Petopas' answer to Windows 7 SDK Installation Failure solved my issue.
map
: It returns a new RDD
by applying a function to each element of the RDD
. Function in .map can return only one item.
flatMap
: Similar to map, it returns a new RDD
by applying a function to each element of the RDD, but the output is flattened.
Also, function in flatMap
can return a list of elements (0 or more)
For Example:
sc.parallelize([3,4,5]).map(lambda x: range(1,x)).collect()
Output: [[1, 2], [1, 2, 3], [1, 2, 3, 4]]
sc.parallelize([3,4,5]).flatMap(lambda x: range(1,x)).collect()
Output: notice o/p is flattened out in a single list [1, 2, 1, 2, 3, 1, 2, 3, 4]
Source:https://www.linkedin.com/pulse/difference-between-map-flatmap-transformations-spark-pyspark-pandey/
Swift 5+
extension Date {
func get(_ type: Calendar.Component)-> String {
let calendar = Calendar.current
let t = calendar.component(type, from: self)
return (t < 10 ? "0\(t)" : t.description)
}
}
Usage:
print(Date().get(.year)) // => 2020
print(Date().get(.month)) // => 08
print(Date().get(.day)) // => 18
To align one flex child to the right set it withmargin-left: auto;
From the flex spec:
One use of auto margins in the main axis is to separate flex items into distinct "groups". The following example shows how to use this to reproduce a common UI pattern - a single bar of actions with some aligned on the left and others aligned on the right.
.wrap div:last-child {
margin-left: auto;
}
.wrap {_x000D_
display: flex;_x000D_
background: #ccc;_x000D_
width: 100%;_x000D_
justify-content: space-between;_x000D_
}_x000D_
.wrap div:last-child {_x000D_
margin-left: auto;_x000D_
}_x000D_
.result {_x000D_
background: #ccc;_x000D_
margin-top: 20px;_x000D_
}_x000D_
.result:after {_x000D_
content: '';_x000D_
display: table;_x000D_
clear: both;_x000D_
}_x000D_
.result div {_x000D_
float: left;_x000D_
}_x000D_
.result div:last-child {_x000D_
float: right;_x000D_
}
_x000D_
<div class="wrap">_x000D_
<div>One</div>_x000D_
<div>Two</div>_x000D_
<div>Three</div>_x000D_
</div>_x000D_
_x000D_
<!-- DESIRED RESULT -->_x000D_
<div class="result">_x000D_
<div>One</div>_x000D_
<div>Two</div>_x000D_
<div>Three</div>_x000D_
</div>
_x000D_
Note:
You could achieve a similar effect by setting flex-grow:1 on the middle flex item (or shorthand flex:1
) which would push the last item all the way to the right. (Demo)
The obvious difference however is that the middle item becomes bigger than it may need to be. Add a border to the flex items to see the difference.
.wrap {_x000D_
display: flex;_x000D_
background: #ccc;_x000D_
width: 100%;_x000D_
justify-content: space-between;_x000D_
}_x000D_
.wrap div {_x000D_
border: 3px solid tomato;_x000D_
}_x000D_
.margin div:last-child {_x000D_
margin-left: auto;_x000D_
}_x000D_
.grow div:nth-child(2) {_x000D_
flex: 1;_x000D_
}_x000D_
.result {_x000D_
background: #ccc;_x000D_
margin-top: 20px;_x000D_
}_x000D_
.result:after {_x000D_
content: '';_x000D_
display: table;_x000D_
clear: both;_x000D_
}_x000D_
.result div {_x000D_
float: left;_x000D_
}_x000D_
.result div:last-child {_x000D_
float: right;_x000D_
}
_x000D_
<div class="wrap margin">_x000D_
<div>One</div>_x000D_
<div>Two</div>_x000D_
<div>Three</div>_x000D_
</div>_x000D_
_x000D_
<div class="wrap grow">_x000D_
<div>One</div>_x000D_
<div>Two</div>_x000D_
<div>Three</div>_x000D_
</div>_x000D_
_x000D_
<!-- DESIRED RESULT -->_x000D_
<div class="result">_x000D_
<div>One</div>_x000D_
<div>Two</div>_x000D_
<div>Three</div>_x000D_
</div>
_x000D_
in your Product Web API controller:
[RoutePrefix("api/product")]
public class ProductController : ApiController
{
private readonly IProductRepository _repository;
public ProductController(IProductRepository repository)
{
this._repository = repository;
}
[HttpGet, Route("orders")]
public async Task<IHttpActionResult> GetProductPeriodOrders(string productCode, DateTime dateStart, DateTime dateEnd)
{
try
{
IList<Order> orders = await _repository.GetPeriodOrdersAsync(productCode, dateStart.ToUniversalTime(), dateEnd.ToUniversalTime());
return Ok(orders);
}
catch(Exception ex)
{
return NotFound();
}
}
}
test GetProductPeriodOrders method in Fiddler - Composer:
http://localhost:46017/api/product/orders?productCode=100&dateStart=2016-12-01T00:00:00&dateEnd=2016-12-31T23:59:59
DateTime format:
yyyy-MM-ddTHH:mm:ss
javascript pass parameter use moment.js
const dateStart = moment(startDate).format('YYYY-MM-DDTHH:mm:ss');
const dateEnd = moment(endDate).format('YYYY-MM-DDTHH:mm:ss');
The better option if you cannot control user input, it is to establish the css property, overflow:hidden, so if the string is superior to the width, it will not deform the design.
Edited:
I like the answer: "word-wrap: break-word", and for those browsers that do not support it, for example, IE6 or IE7, I would use my solution.
Keep in mind though that passing arguments on Activator.CreateInstance has a significant performance difference versus parameterless creation.
There are better alternatives for dynamically creating objects using pre compiled lambda. Of course always performance is subjective and it clearly depends on each case if it's worth it or not.
Details about the issue on this article.
Graph is taken from the article and represents time taken in ms per 1000 calls.
It works when I change to sudo gdb executableFileName
! :)
A Popen
object has a .wait()
method exactly defined for this: to wait for the completion of a given subprocess (and, besides, for retuning its exit status).
If you use this method, you'll prevent that the process zombies are lying around for too long.
(Alternatively, you can use subprocess.call()
or subprocess.check_call()
for calling and waiting. If you don't need IO with the process, that might be enough. But probably this is not an option, because your if the two subprocesses seem to be supposed to run in parallel, which they won't with (check_
)call()
.)
If you have several subprocesses to wait for, you can do
exit_codes = [p.wait() for p in p1, p2]
which returns as soon as all subprocesses have finished. You then have a list of return codes which you maybe can evaluate.
According to this article on the w3c website:
CDATA is a sequence of characters from the document character set and may include character entities. User agents should interpret attribute values as follows:
- Replace character entities with characters,
- Ignore line feeds,
- Replace each carriage return or tab with a single space.
This means that (at least) CR and LF won't work inside title attribute. I suggest that you use a tooltip plugin. Most of these plugins allow arbitrary HTML to be displayed as an element's tooltip.
<WebView ref={'webview'} automaticallyAdjustContentInsets={false} source={require('../Assets/aboutus.html')} />
This worked for me :) I have html text aboutus file.
In case if someone needs to create a dictionary object dynamically you can use the following code snippet
let vars = [{key:"key", value:"value"},{key:"key2", value:"value2"}];
let dict={}
vars.map(varItem=>{
dict[varItem.key]=varItem.value
})
console.log(dict)
_x000D_
Considering the question's environment.
And quoting from: http://php.net/manual/en/function.mkdir.php
bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = FALSE [, resource $context ]]] )
Manual says that the only required parameter is the $pathname
!
so, We can simply code:
<?php
error_reporting(0);
if(!mkdir('wp-content/uploads')){
// todo
}
?>
We don't have to pass any parameter or check if folder exists or even pass mode parameter unless needed; for the following reasons:
mode
is ignored on Windows Hosting running PHP.mkdir
command has build in checker if folder exists; so we need to check the return only True|False ; and its not an error, its a warning only, and Warning is disabled in hosting servers by default.This is just another way to look into the question and not claiming a better or most optimal solution.
Tested on PHP7, Production Server, Linux
If you want to avoid both mutability and boxing, there is no way out of the box. But you can create a class which holds primitive array inside and provides read-only access to elements via method(s).
try this code
<script>
angular.element(document.querySelectorAll("#div1")).addClass("alpha");
</script>
click the link and understand more
Note: Keep in mind that angular.element() function will not find directly select any documnet location using this perameters angular.element(document).find(...) or $document.find(), or use the standard DOM APIs, e.g. document.querySelectorAll()
This is usually simply due to mismatching times between your host and client machines. You can try to synchronize the times on your machines using ntp.
I haven't seen that the PowerShell has really taken off, at least not yet. So it might not be worth the effort of learning it unless those others on your team already know it.
For your predicament you might be better off with a scripting language that others could get behind, Perl like you mentioned, or others like Ruby or Python.
I think a lot of it depends on what you need to do. Personally I've been using Python for my own personal scripts, but I know when I start writing something that I'll never be able to pass it on - so I try not to do anything too revolutionary.
I'm starting to learn about this myself, being very new to android development and I found this video very helpful.
https://www.youtube.com/watch?v=qcotbMLjlA4
It specifically covers to to get JSONArray to JSONObject at 19:30 in the video.
Code from the video for JSONArray to JSONObject:
JSONArray queryArray = quoteJSONObject.names();
ArrayList<String> list = new ArrayList<String>();
for(int i = 0; i < queryArray.length(); i++){
list.add(queryArray.getString(i));
}
for(String item : list){
Log.v("JSON ARRAY ITEMS ", item);
}
You can Try using :- git ls-files -s
Besides the original answer, I have done the following:
Instead of use img src="", try to create a div and set background-image as the image you want.
Right now it's working for me.
example:
App.js
import React, { Component } from 'react';
import './App.css';
class App extends Component {
render() {
return (
<div>
<div className="myImage"> </div>
</div>
);
}
}
export default App;
App.css
.myImage {
width: 60px;
height: 60px;
background-image: url("./icons/add-circle.png");
background-repeat: no-repeat;
background-size: 100%;
}
you have to git add css/mobile.css
the new file and git rm css/iphone.css
, so git knows about it. then it will show the same output in git status
you can see it clearly in the status output (the new name of the file):
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
and (the old name):
# Changed but not updated:
# (use "git add/rm <file>..." to update what will be committed)
i think behind the scenes git mv
is nothing more than a wrapper script which does exactly that: delete the file from the index and add it under a different name
function showstuff(boxid){
document.getElementById(boxid).style.visibility="visible";
}
<button onclick="showstuff('id_to_show');" />
This will help you, I think.
Here is a way to get a NIO FileChannel from System.in and check for availability of data using a timeout, which is a special case of the problem described in the question. Run it at the console, don't type any input, and wait for the results. It was tested successfully under Java 6 on Windows and Linux.
import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedByInterruptException;
public class Main {
static final ByteBuffer buf = ByteBuffer.allocate(4096);
public static void main(String[] args) {
long timeout = 1000 * 5;
try {
InputStream in = extract(System.in);
if (! (in instanceof FileInputStream))
throw new RuntimeException(
"Could not extract a FileInputStream from STDIN.");
try {
int ret = maybeAvailable((FileInputStream)in, timeout);
System.out.println(
Integer.toString(ret) + " bytes were read.");
} finally {
in.close();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/* unravels all layers of FilterInputStream wrappers to get to the
* core InputStream
*/
public static InputStream extract(InputStream in)
throws NoSuchFieldException, IllegalAccessException {
Field f = FilterInputStream.class.getDeclaredField("in");
f.setAccessible(true);
while( in instanceof FilterInputStream )
in = (InputStream)f.get((FilterInputStream)in);
return in;
}
/* Returns the number of bytes which could be read from the stream,
* timing out after the specified number of milliseconds.
* Returns 0 on timeout (because no bytes could be read)
* and -1 for end of stream.
*/
public static int maybeAvailable(final FileInputStream in, long timeout)
throws IOException, InterruptedException {
final int[] dataReady = {0};
final IOException[] maybeException = {null};
final Thread reader = new Thread() {
public void run() {
try {
dataReady[0] = in.getChannel().read(buf);
} catch (ClosedByInterruptException e) {
System.err.println("Reader interrupted.");
} catch (IOException e) {
maybeException[0] = e;
}
}
};
Thread interruptor = new Thread() {
public void run() {
reader.interrupt();
}
};
reader.start();
for(;;) {
reader.join(timeout);
if (!reader.isAlive())
break;
interruptor.start();
interruptor.join(1000);
reader.join(1000);
if (!reader.isAlive())
break;
System.err.println("We're hung");
System.exit(1);
}
if ( maybeException[0] != null )
throw maybeException[0];
return dataReady[0];
}
}
Interestingly, when running the program inside NetBeans 6.5 rather than at the console, the timeout doesn't work at all, and the call to System.exit() is actually necessary to kill the zombie threads. What happens is that the interruptor thread blocks (!) on the call to reader.interrupt(). Another test program (not shown here) additionally tries to close the channel, but that doesn't work either.
As above @niravdesai said App-prefs.
I found that App-Prefs:
works for both iOS 9, 10 and 11. devices tested.
where as prefs:
only works on iOS 9.
Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:
public class ItemLinkedList {
private ItemInfoNode head;
private ItemInfoNode tail;
private int size = 0;
public int getSize() {
return size;
}
public void addBack(ItemInfo info) {
size++;
if (head == null) {
head = new ItemInfoNode(info, null, null);
tail = head;
} else {
ItemInfoNode node = new ItemInfoNode(info, null, tail);
this.tail.next =node;
this.tail = node;
}
}
public void addFront(ItemInfo info) {
size++;
if (head == null) {
head = new ItemInfoNode(info, null, null);
tail = head;
} else {
ItemInfoNode node = new ItemInfoNode(info, head, null);
this.head.prev = node;
this.head = node;
}
}
public ItemInfo removeBack() {
ItemInfo result = null;
if (head != null) {
size--;
result = tail.info;
if (tail.prev != null) {
tail.prev.next = null;
tail = tail.prev;
} else {
head = null;
tail = null;
}
}
return result;
}
public ItemInfo removeFront() {
ItemInfo result = null;
if (head != null) {
size--;
result = head.info;
if (head.next != null) {
head.next.prev = null;
head = head.next;
} else {
head = null;
tail = null;
}
}
return result;
}
public class ItemInfoNode {
private ItemInfoNode next;
private ItemInfoNode prev;
private ItemInfo info;
public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
this.info = info;
this.next = next;
this.prev = prev;
}
public void setInfo(ItemInfo info) {
this.info = info;
}
public void setNext(ItemInfoNode node) {
next = node;
}
public void setPrev(ItemInfoNode node) {
prev = node;
}
public ItemInfo getInfo() {
return info;
}
public ItemInfoNode getNext() {
return next;
}
public ItemInfoNode getPrev() {
return prev;
}
}
}
EDIT:
Declare ItemInfo as this:
public class ItemInfo {
private String name;
private String rfdNumber;
private double price;
private String originalPosition;
public ItemInfo(){
}
public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
this.name = name;
this.rfdNumber = rfdNumber;
this.price = price;
this.originalPosition = originalPosition;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRfdNumber() {
return rfdNumber;
}
public void setRfdNumber(String rfdNumber) {
this.rfdNumber = rfdNumber;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getOriginalPosition() {
return originalPosition;
}
public void setOriginalPosition(String originalPosition) {
this.originalPosition = originalPosition;
}
}
Then, You can use your nodes inside the linked list like this:
public static void main(String[] args) {
ItemLinkedList list = new ItemLinkedList();
for (int i = 1; i <= 10; i++) {
list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));
}
while (list.size() > 0){
System.out.println(list.removeFront().getName());
}
}
As of 2019_10_10 I have NOT tested it, but there is the "GPU Ocelot" project
that according to its advertisement tries to compile CUDA code for a variety of targets, including AMD GPUs.
In base R, we can select the columns which we want to test using grep
, compare the data with 0, use rowSums
to select rows which has all non-zero values.
cols <- grep("^Mac", names(df))
df[rowSums(df[cols] != 0) == length(cols), ]
# DateTime Mac1 Mac2 Mac3 Mac4
#1 2011-04-02 06:05 21 21 21 21
#2 2011-04-02 06:10 22 22 22 22
#3 2011-04-02 06:20 24 24 24 24
Doing this with inverted logic but giving the same output
df[rowSums(df[cols] == 0) == 0, ]
In dplyr
, we can use filter_at
to test for specific columns and use all_vars
to select rows where all the values are not equal to 0.
library(dplyr)
df %>% filter_at(vars(starts_with("Mac")), all_vars(. != 0))
data
df <- structure(list(DateTime = structure(1:6, .Label = c("2011-04-02 06:00",
"2011-04-02 06:05", "2011-04-02 06:10", "2011-04-02 06:15", "2011-04-02 06:20",
"2011-04-02 06:25"), class = "factor"), Mac1 = c(20L, 21L, 22L,
23L, 24L, 0L), Mac2 = c(0L, 21L, 22L, 23L, 24L, 25L), Mac3 = c(20L,
21L, 22L, 0L, 24L, 25L), Mac4 = c(20L, 21L, 22L, 23L, 24L, 0L
)), class = "data.frame", row.names = c(NA, -6L))
Try changing CodeBehind="Default.aspx.cs"
to CodeFile="Default.aspx.cs"
Demo :
<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
Based on your question:
<connectionStrings>
<add name="itmall" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True" />
</connectionStrings>
Refer links:
http://www.connectionstrings.com/store-connection-string-in-webconfig/
Retrive connection string from web.config file:
write the below code in your file where you want;
string connstring=ConfigurationManager.ConnectionStrings["itmall"].ConnectionString;
SqlConnection con = new SqlConnection(connstring);
or you can go in your way like
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["itmall"].ConnectionString);
Note:
The "name" which you gave in web.config file and name which you used in connection string must be same(like "itmall" in this solution.)
According to this, cmd + / should do it.
And for Windows and Linux, it is ctrl + /.
Here is a good example -
ul li{
list-style-type: disc;
list-style-position: inside;
padding: 10px 0 10px 20px;
text-indent: -1em;
}
Working Demo: http://jsfiddle.net/d9VNk/
Best way to store date
in SQlite DB is to store the current DateTimeMilliseconds
. Below is the code snippet to do so_
- Get the
DateTimeMilliseconds
public static long getTimeMillis(String dateString, String dateFormat) throws ParseException {
/*Use date format as according to your need! Ex. - yyyy/MM/dd HH:mm:ss */
String myDate = dateString;//"2017/12/20 18:10:45";
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat/*"yyyy/MM/dd HH:mm:ss"*/);
Date date = sdf.parse(myDate);
long millis = date.getTime();
return millis;
}
- Insert the data in your DB
public void insert(Context mContext, long dateTimeMillis, String msg) {
//Your DB Helper
MyDatabaseHelper dbHelper = new MyDatabaseHelper(mContext);
database = dbHelper.getWritableDatabase();
ContentValues contentValue = new ContentValues();
contentValue.put(MyDatabaseHelper.DATE_MILLIS, dateTimeMillis);
contentValue.put(MyDatabaseHelper.MESSAGE, msg);
//insert data in DB
database.insert("your_table_name", null, contentValue);
//Close the DB connection.
dbHelper.close();
}
Now, your data (date is in currentTimeMilliseconds) is get inserted in DB .
Next step is, when you want to retrieve data from DB you need to convert the respective date time milliseconds in to corresponding date. Below is the sample code snippet to do the same_
- Convert date milliseconds in to date string.
public static String getDate(long milliSeconds, String dateFormat)
{
// Create a DateFormatter object for displaying date in specified format.
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat/*"yyyy/MM/dd HH:mm:ss"*/);
// Create a calendar object that will convert the date and time value in milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
return formatter.format(calendar.getTime());
}
- Now, Finally fetch the data and see its working...
public ArrayList<String> fetchData() {
ArrayList<String> listOfAllDates = new ArrayList<String>();
String cDate = null;
MyDatabaseHelper dbHelper = new MyDatabaseHelper("your_app_context");
database = dbHelper.getWritableDatabase();
String[] columns = new String[] {MyDatabaseHelper.DATE_MILLIS, MyDatabaseHelper.MESSAGE};
Cursor cursor = database.query("your_table_name", columns, null, null, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()){
do{
//iterate the cursor to get data.
cDate = getDate(cursor.getLong(cursor.getColumnIndex(MyDatabaseHelper.DATE_MILLIS)), "yyyy/MM/dd HH:mm:ss");
listOfAllDates.add(cDate);
}while(cursor.moveToNext());
}
cursor.close();
//Close the DB connection.
dbHelper.close();
return listOfAllDates;
}
Hope this will help all! :)