You can try to use TCPView utility.
Try to find in the localport column is there any process worked on "busy" port. Right click and end the process. Then try to start the Tomcat.
Its really works for me.
Annotate the property like below
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
To use identity columns for all value-generated properties on a new model, simply place the following in your context's OnModelCreating():
builder.ForNpgsqlUseIdentityColumns();
This will create make all keys and other properties which have .ValueGeneratedOnAdd() have Identity by default. You can use ForNpgsqlUseIdentityAlwaysColumns() to have Identity always, and you can also specify identity on a property-by-property basis with UseNpgsqlIdentityColumn() and UseNpgsqlIdentityAlwaysColumn().
git bundle
I like that method, as it results in only one file, easier to copy around.
See ProGit: little bundle of joy.
See also "How can I email someone a git repository?", where the command
git bundle create /tmp/foo-all --all
is detailed:
git bundle
will only package references that are shown by git show-ref: this includes heads, tags, and remote heads.
It is very important that the basis used be held by the destination.
It is okay to err on the side of caution, causing the bundle file to contain objects already in the destination, as these are ignored when unpacking at the destination.
For using that bundle, you can clone it, specifying a non-existent folder (outside of any git repo):
git clone /tmp/foo-all newFolder
You can also use the environment variable $window
so that a global variable declare outside a controller can be checked inside a $watch
var initWatch = function($scope,$window){
$scope.$watch(function(scope) { return $window.globalVar },
function(newValue) {
$scope.updateDisplayedVar(newValue);
});
}
Becareful, the digest cycle is longer with these global values, so it is not always real-timed updated. I need to investigate on that digest time with this configuration.
If you have WL server installed, pick it up from under
\Oracle\Middleware\wlserver_10.3\server\lib\mysql-connector-java-commercial-5.1.17-bin.jar
Otherwise, download it from:
http://www.java2s.com/Code/JarDownload/mysql/mysql-connector-java-5.1.17-bin.jar.zip
For VS2010 and above (VS2010 needs a plugin). If you have checked/set the options of the tab size in Visual Studio but it still won't work. Then check if you have a .editorconfig file in your project! This will override the Visual Studio settings. Edit the tab-size in that file.
This can happen if you install an Angular application in your project with the Angular-Cli.
Well any Javascript object functions sort-of like a "map"
randomObject['hello'] = 'world';
Typically people build simple objects for the purpose:
var myMap = {};
// ...
myMap[newKey] = newValue;
edit — well the problem with having an explicit "put" function is that you'd then have to go to pains to avoid having the function itself look like part of the map. It's not really a Javascripty thing to do.
13 Feb 2014 — modern JavaScript has facilities for creating object properties that aren't enumerable, and it's pretty easy to do. However, it's still the case that a "put" property, enumerable or not, would claim the property name "put" and make it unavailable. That is, there's still only one namespace per object.
I just used post and an if:
data = getDataObjectByForm(form);
var jqxhr = $.post(url, data, function(){}, 'json')
.done(function (response) {
if (response instanceof Object)
var json = response;
else
var json = $.parseJSON(response);
// console.log(response);
// console.log(json);
jsonToDom(json);
if (json.reload != undefined && json.reload)
location.reload();
$("body").delay(1000).css("cursor", "default");
})
.fail(function (jqxhr, textStatus, error) {
var err = textStatus + ", " + error;
console.log("Request Failed: " + err);
alert("Fehler!");
});
Sometimes, the database will not be mounted correctly, so we need to mount it manually. For that, shut it down and start it up then mount. Log in as oracle user, then run the following commands:
sqlplus / as sysdba;
shutdown immediate;
startup nomount;
alter database mount;
alter database open;
If you want to avoid hardcoding your keystore & password in build.gradle, you can use a properties file as explained here: HANDLING SIGNING CONFIGS WITH GRADLE
Basically:
1) create a myproject.properties file at /home/[username]/.signing with such contents:
keystore=[path to]\release.keystore
keystore.password=*********
keyAlias=***********
keyPassword=********
2) create a gradle.properties file (perhaps at the root of your project directory) with the contents:
MyProject.properties=/home/[username]/.signing/myproject.properties
3) refer to it in your build.gradle like this:
if(project.hasProperty("MyProject.properties")
&& new File(project.property("MyProject.properties")).exists()) {
Properties props = new Properties()
props.load(new FileInputStream(file(project.property("MyProject.properties"))))
signingConfigs {
release {
storeFile file(props['keystore'])
storePassword props['keystore.password']
keyAlias props['keyAlias']
keyPassword props['keyPassword']
}
}
}
HttpContext.Response.AddHeader("content-disposition","attachment; filename=form.pdf");
if the filename is generating dynamically then how to define filename here, it is generating through guid here.
If you have already migrated to androidx
, you should change your layout xml
from
<android.support.design.widget.NavigationView ... />
to
<com.google.android.material.navigation.NavigationView ... />
private string GetExtension(string attachment_name)
{
var index_point = attachment_name.IndexOf(".") + 1;
return attachment_name.Substring(index_point);
}
If it is possible pass the params through regular GET/POST with a different name and let your server side code handles it.
I had a similar issue with my own proxy to bypass CORS and I got the same error of POST->OPTION in Chrome. It was the Authorization
header in my case ("x-li-format"
and "X-UserName"
here in your case.) I ended up passing it in a dummy format (e.g. AuthorizatinJack
in GET) and I changed the code for my proxy to turn that into a header when making the call to the destination. Here it is in PHP:
if (isset($_GET['AuthorizationJack'])) {
$request_headers[] = "Authorization: Basic ".$_GET['AuthorizationJack'];
}
1st Reason could be the ending tag of your application's web.xml file which could not have been closed properly.
web.xml might be ending with <web-app>
, but must end with </web-app>
2nd Reason which worked in my case could be the lib folder of your tomcat must contain the supporting jar file of your database.
ojdbc
on case of Oracle or sqljdbc
in case of SqlServer
I hit this issue with Ubuntu 18.04 and none of the previous answers solved it. Eventually I succeeded by installing devtools
with the package manager itself:
sudo apt install r-cran-devtools
git pull
= git fetch
+ git merge
against tracking upstream branch
git pull --rebase
= git fetch
+ git rebase
against tracking upstream branch
If you want to know how git merge
and git rebase
differ, read this.
Make Executable your jar and after that double click on it on Mac OS then it works successfully.
sudo chmod +x filename.jar
Try this, I hope this works.
Try the following :
Make sure you add M2_HOME
variable to your environment variables. It looks like you might have set M2_HOME
temporarily in a cmd
window and not as a permanent environment variable. Also append M2_HOME
to the PATH
variable.
Go to the m2
folder in your user directory.
Example: On Windows, for user bot
, the .m2
directory will be under C:\Users\bot
. Look for the settings.xml
file in this directory and look for the repository url within this file. See if you are able to hit this url from your browser. If not, you probably need to point to a different maven repository or use a proxy.
If you are able to hit the repository url from the browser, then check if the repository contains the maven-resource-plugin
version 2.6. This can be found by navigating to org.apache.maven.plugins
folder in the browser. It's possible that your pom
has hard-coded the dependency of the plugin to 2.6 but it is not available in the repository. This can be fixed by changing the depndency version to the one available in the repository.
It's possible to know if the character is a letter or not by using a standard builtin function isNaN or Number.isNaN() from ES6:
isNaN('s') // true
isNaN('-') // true
isNaN('32') // false, '32' is converted to the number 32 which is not NaN
It retruns true if the given value is not a number, otherwise false.
The latest 2020 build doesn't have the shorten command line option by default we need to add that option from the configuration.
Run > Edit Configurations > Select the corresponding run configuration and click on Modify options for adding the shorten command-line configuration to the UI.
Select the shorten command line option
Now choose jar manifest from the shorten command line option
I know this is a quite old question, but when you have JavaScript available you could use jQuery and its AJAX methods.
First, create a page with all the navigation bar's HTML content.
Next, use jQuery's $.get
method to fetch the content of the page. For example, let's say you've put all the navigation bar's HTML into a file called navigation.html
and added a placeholder tag (Like <div id="nav-placeholder">
) in your index.html
, then you would use the following code:
<script src="//code.jquery.com/jquery.min.js"></script>
<script>
$.get("navigation.html", function(data){
$("#nav-placeholder").replaceWith(data);
});
</script>
A FragmentActivity
is a subclass of Activity
that was built for the Android Support Package.
The FragmentActivity
class adds a couple new methods to ensure compatibility with older versions of Android, but other than that, there really isn't much of a difference between the two. Just make sure you change all calls to getLoaderManager()
and getFragmentManager()
to getSupportLoaderManager()
and getSupportFragmentManager()
respectively.
but I can't initialize my derived class, I mean I did this Inheritance so I can add animals to my PetStore but now since sizeF is private how can I do that ?? so I'm thinking maybe in the PetStore default constructor I can call Farm()... so any Idea ???
Don't panic.
Farm constructor will be called in the constructor of PetStore, automatically.
See the base class inheritance calling rules: What are the rules for calling the superclass constructor?
Try
if (isset($_POST['fromPerson']) && $_POST['fromPerson'] != "") {
echo "Cool";
}
You can use
LEFT(column, length)
or
SUBSTRING(column, start index, length)
Every time we write an algorithm or code we try to analyze its asymptotic complexity. It is different from its time complexity.
Asymptotic complexity is the behavior of execution time of an algorithm while the time complexity is the actual execution time. But some people use these terms interchangeably.
Because time complexity depends on various parameters viz.
1. Physical System
2. Programming Language
3. coding Style
4. And much more ......
The actual execution time is not a good measure for analysis.
Instead we take input size as the parameter because whatever the code is, the input is same. So the execution time is a function of input size.
Following is an example of Linear Time Algorithm
Linear Search
Given n input elements, to search an element in the array you need at most 'n' comparisons. In other words, no matter what programming language you use, what coding style you prefer, on what system you execute it. In the worst case scenario it requires only n comparisons.The execution time is linearly proportional to the input size.
And its not just search, whatever may be the work (increment, compare or any operation) its a function of input size.
So when you say any algorithm is O(log n) it means the execution time is log times the input size n.
As the input size increases the work done(here the execution time) increases.(Hence proportionality)
n Work
2 1 units of work
4 2 units of work
8 3 units of work
See as the input size increased the work done is increased and it is independent of any machine. And if you try to find out the value of units of work It's actually dependent onto those above specified parameters.It will change according to the systems and all.
A slight change in the execute query will solve the problem:
DECLARE @dbName nvarchar(128) = 'myDb'
DECLARE @siteId int
exec ('SELECT TOP 1 **''@siteId''** = Id FROM ' + @dbName + '..myTbl')
select @siteId
You can play with delay
prop of animation, just set visibility:visible
after a delay, demo:
@keyframes delayedShow {_x000D_
to {_x000D_
visibility: visible;_x000D_
}_x000D_
}_x000D_
_x000D_
.delayedShow{_x000D_
visibility: hidden;_x000D_
animation: 0s linear 2.3s forwards delayedShow ;_x000D_
}
_x000D_
So, Where are you?_x000D_
_x000D_
<div class="delayedShow">_x000D_
Hey, I'm here!_x000D_
</div>
_x000D_
The HTML
<a href="#" id="btn">click</a>
And the javascript
// get a cross-browser function for adding events, place this in [global] or somewhere you can access it
var on = (function(){
if (window.addEventListener) {
return function(target, type, listener){
target.addEventListener(type, listener, false);
};
}
else {
return function(object, sEvent, fpNotify){
object.attachEvent("on" + sEvent, fpNotify);
};
}
}());
// find the element
var el = document.getElementById("btn");
// add the first listener
on(el, "click", function(){
alert("foo");
});
// add the second listener
on(el, "click", function(){
alert("bar");
});
This will alert both 'foo' and 'bar' when clicked.
Just use this : Make sure using nibName otherwise preloaded views of xib will not show :
var vc : ViewController = ViewController(nibName: "ViewController", bundle: nil)
//change this to your class name
self.presentViewController(vc, animated: true, completion: nil)
From Android P, defining the READ_PHONE_STATE permission in AndroidManifest only, will not work. We have to actually request for the permission. Below code works for me:
@RequiresApi(api = Build.VERSION_CODES.P)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 101);
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected void onResume() {
super.onResume();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
return;
}
Log.d(TAG,Build.getSerial());
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 101:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
return;
}
} else {
//not granted
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
Add this permissions in AndroidManifest.xml
<uses-permission android:name = "android.permission.INTERNET"/>
<uses-permission android:name = "android.permission.READ_PHONE_STATE" />
Hope this helps.
Thank You, MJ
To get a random integer value between 1 and N (inclusive) you can use the following.
CInt(Math.Ceiling(Rnd() * n)) + 1
This is better:
<?php
//* Permanently redirect page
header("Location: new_page.php",TRUE,301);
?>
Just one call including code 301. Also notice the relative path to the file in the same directory (not "/dir/dir/new_page.php", etc.), which all modern browsers seem to support.
I think this is valid since PHP 5.1.2, possibly earlier.
In System.Web.Mvc.Html ( in System.Web.Mvc.dll ) the begin form is defined like:- Details
BeginForm ( this HtmlHelper htmlHelper, string actionName, string
controllerName, object routeValues, FormMethod method, object htmlAttributes)
Means you should use like this :
Html.BeginForm( string actionName, string controllerName,object routeValues, FormMethod method, object htmlAttributes)
So, it worked in MVC 4
@using (Html.BeginForm(null, null, new { @id = string.Empty }, FormMethod.Post,
new { @id = "signupform" }))
{
<input id="TRAINER_LIST" name="TRAINER_LIST" type="hidden" value="">
<input type="submit" value="Create" id="btnSubmit" />
}
I collected some ideas from other SO question (largely from here and this css page)
The idea is to use relative and absolute positioning to move your line to the bottom:
@media (min-width: 768px ) {
.row {
position: relative;
}
#bottom-align-text {
position: absolute;
bottom: 0;
right: 0;
}}
The display:flex
option is at the moment a solution to make the div get the same size as its parent. This breaks on the other hand the bootstrap possibilities to auto-linebreak on small devices by adding col-sx-12
class. (This is why the media query is needed)
Another attempt to make your code harder to steal is to use jython and then use java obfuscator.
This should work pretty well as jythonc translate python code to java and then java is compiled to bytecode. So ounce you obfuscate the classes it will be really hard to understand what is going on after decompilation, not to mention recovering the actual code.
The only problem with jython is that you can't use python modules written in c.
set
is what you want, so you should use set
. Trying to be clever introduces subtle bugs like forgetting to add one tomax(mylist)
! Code defensively. Worry about what's faster when you determine that it is too slow.
range(min(mylist), max(mylist) + 1) # <-- don't forget to add 1
Assuming SQL Server 2000, the following StackOverflow question should address your problem.
If using SQL Server 2005/2008, you can use the following code (taken from here):
select cast(replace(cast(myntext as nvarchar(max)),'find','replace') as ntext)
from myntexttable
For future reference, you can get help for any command by using the /?
switch, which should explain what switches do what.
According to the set /?
screen, the format for set /p
is SET /P variable=[promptString]
which would indicate that the p in /p
is "prompt." It just prints in your example because <nul
passes in a nul character which immediately ends the prompt so it just acts like it's printing. It's still technically prompting for input, it's just immediately receiving it.
/L
in for /L
generates a List of numbers.
From ping /?
:
Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
[-r count] [-s count] [[-j host-list] | [-k host-list]]
[-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name
Options:
-t Ping the specified host until stopped.
To see statistics and continue - type Control-Break;
To stop - type Control-C.
-a Resolve addresses to hostnames.
-n count Number of echo requests to send.
-l size Send buffer size.
-f Set Don't Fragment flag in packet (IPv4-only).
-i TTL Time To Live.
-v TOS Type Of Service (IPv4-only. This setting has been deprecated
and has no effect on the type of service field in the IP Header).
-r count Record route for count hops (IPv4-only).
-s count Timestamp for count hops (IPv4-only).
-j host-list Loose source route along host-list (IPv4-only).
-k host-list Strict source route along host-list (IPv4-only).
-w timeout Timeout in milliseconds to wait for each reply.
-R Use routing header to test reverse route also (IPv6-only).
-S srcaddr Source address to use.
-4 Force using IPv4.
-6 Force using IPv6.
Something like this in your form main. Double click the form in the visual editor to create the form load event.
Timer Clock=new Timer();
Clock.Interval=2700000; // not sure if this length of time will work
Clock.Start();
Clock.Tick+=new EventHandler(Timer_Tick);
Then add an event handler to do something when the timer fires.
public void Timer_Tick(object sender,EventArgs eArgs)
{
if(sender==Clock)
{
// do something here
}
}
This code works perfectly from Spark 2.x with Scala 2.11
Import necessary classes
import org.apache.spark.sql.{Row, SparkSession}
import org.apache.spark.sql.types.{DoubleType, StringType, StructField, StructType}
Create SparkSession
Object, and Here it's spark
val spark: SparkSession = SparkSession.builder.master("local").getOrCreate
val sc = spark.sparkContext // Just used to create test RDDs
Let's an RDD
to make it DataFrame
val rdd = sc.parallelize(
Seq(
("first", Array(2.0, 1.0, 2.1, 5.4)),
("test", Array(1.5, 0.5, 0.9, 3.7)),
("choose", Array(8.0, 2.9, 9.1, 2.5))
)
)
Using SparkSession.createDataFrame(RDD obj)
.
val dfWithoutSchema = spark.createDataFrame(rdd)
dfWithoutSchema.show()
+------+--------------------+
| _1| _2|
+------+--------------------+
| first|[2.0, 1.0, 2.1, 5.4]|
| test|[1.5, 0.5, 0.9, 3.7]|
|choose|[8.0, 2.9, 9.1, 2.5]|
+------+--------------------+
Using SparkSession.createDataFrame(RDD obj)
and specifying column names.
val dfWithSchema = spark.createDataFrame(rdd).toDF("id", "vals")
dfWithSchema.show()
+------+--------------------+
| id| vals|
+------+--------------------+
| first|[2.0, 1.0, 2.1, 5.4]|
| test|[1.5, 0.5, 0.9, 3.7]|
|choose|[8.0, 2.9, 9.1, 2.5]|
+------+--------------------+
This way requires the input rdd
should be of type RDD[Row]
.
val rowsRdd: RDD[Row] = sc.parallelize(
Seq(
Row("first", 2.0, 7.0),
Row("second", 3.5, 2.5),
Row("third", 7.0, 5.9)
)
)
create the schema
val schema = new StructType()
.add(StructField("id", StringType, true))
.add(StructField("val1", DoubleType, true))
.add(StructField("val2", DoubleType, true))
Now apply both rowsRdd
and schema
to createDataFrame()
val df = spark.createDataFrame(rowsRdd, schema)
df.show()
+------+----+----+
| id|val1|val2|
+------+----+----+
| first| 2.0| 7.0|
|second| 3.5| 2.5|
| third| 7.0| 5.9|
+------+----+----+
The above problem can be solved by adding the following dependencies in your project, as i was facing the same problem.For more detail answer to this solution please refer link SEVERE:MessageBodyWriter not found for media type=application/xml type=class java.util.HashMap
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.25</version>
</dependency>
My personal preference is not to save the images to a database as such. Save the image somewhere in the file system and save a reference in the database.
The best way to overcome on this issue is that, just remove node_modules and package-lock.json file and further install npm with npm i it solved my problem
Easier way to do it in one line of code
this.setState({ object: { ...this.state.object, objectVarToChange: newData } })
here is an another example
<a data-container = "body" data-toggle = "popover" data-placement = "left"
data-content = "<img src='<?php echo baseImgUrl . $row1[2] ?>' width='250' height='100' ><div><h3> <?php echo $row1['1'] ?></h3> <p> <span><?php echo $countsss ?>videos </span>
<span><?php echo $countsss1 ?> followers</span>
</p></div>
<?php echo $row1['4'] ?> <hr><div>
<span> <button type='button' class='btn btn-default pull-left green'>Follow </button> </span> <span> <button type='button' class='btn btn-default pull-left green'> Go to channel page</button> </span><span> <button type='button' class='btn btn-default pull-left green'>Close </button> </span>
</div>">
<?php echo $row1['1'] ?>
</a>
I had a similar issue attempting to get a character count without the leading whitespace provided by wc
, which led me to this page. After trying out the answers here, the following are the results from my personal testing on Mac (BSD Bash). Again, this is for character count; for line count you'd do wc -l
. echo -n
omits the trailing line break.
FOO="bar"
echo -n "$FOO" | wc -c # " 3" (x)
echo -n "$FOO" | wc -c | bc # "3" (v)
echo -n "$FOO" | wc -c | tr -d ' ' # "3" (v)
echo -n "$FOO" | wc -c | awk '{print $1}' # "3" (v)
echo -n "$FOO" | wc -c | cut -d ' ' -f1 # "" for -f < 8 (x)
echo -n "$FOO" | wc -c | cut -d ' ' -f8 # "3" (v)
echo -n "$FOO" | wc -c | perl -pe 's/^\s+//' # "3" (v)
echo -n "$FOO" | wc -c | grep -ch '^' # "1" (x)
echo $( printf '%s' "$FOO" | wc -c ) # "3" (v)
I wouldn't rely on the cut -f*
method in general since it requires that you know the exact number of leading spaces that any given output may have. And the grep
one works for counting lines, but not characters.
bc
is the most concise, and awk
and perl
seem a bit overkill, but they should all be relatively fast and portable enough.
Also note that some of these can be adapted to trim surrounding whitespace from general strings, as well (along with echo `echo $FOO`
, another neat trick).
You can also do this :
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "showError",
"alert('" + ex.Message + "');", true);
}
this will show the exeption message in the alert box
Generally, the backtrace is used to get the stack of the current thread, but if there is a necessity to get the stack trace of all the threads, use the following command.
thread apply all bt
If you don't care for IE6 and IE7 users, simply use display: table-cell
for your divs:
Note the use of wrapper with display: table
.
For IE6/IE7 users - if you have them - you'll probably need to fallback to Javascript.
To see list of all packages that are installed.
$ npm ls --parseable | awk '{gsub(/\/.*\//,"",$1); print}'| sort -u
show parseable of npm packages list https://docs.npmjs.com/cli/ls#parseable
Just pass it in, like this:
Game(list_a, list_b, Rule1)
and then your Game function could look something like this (still pseudocode):
def Game(listA, listB, rules=None):
if rules:
# do something useful
# ...
result = rules(variable) # this is how you can call your rule
else:
# do something useful without rules
Use the zzz
format specifier to get the timezone offset as hours and minutes. You also want to use the HH
format specifier to get the hours in 24 hour format.
DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz")
Result:
2011-08-09T23:49:58+02:00
Some culture settings uses periods instead of colons for time, so you might want to use literal colons instead of time separators:
DateTime.Now.ToString("yyyy-MM-ddTHH':'mm':'sszzz")
TryParse works if your number is less than Int32.MaxValue. This also gives you the opportunity to handle badly formatted strings. Works the same for Int64.MaxValue and Int64.TryParse.
int number;
if(Int32.TryParse(nvarchar, out number))
{
// etc...
number.ToString();
}
Why not just call list()
on the Queryset
?
answers_list = list(answers)
This will also evaluate the QuerySet
/run the query. You can then remove/add from that list.
By overriding Equals you're basically stating that you are the one who knows better how to compare two instances of a given type, so you're likely to be the best candidate to provide the best hash code.
This is an example of how ReSharper writes a GetHashCode() function for you:
public override int GetHashCode()
{
unchecked
{
var result = 0;
result = (result * 397) ^ m_someVar1;
result = (result * 397) ^ m_someVar2;
result = (result * 397) ^ m_someVar3;
result = (result * 397) ^ m_someVar4;
return result;
}
}
As you can see it just tries to guess a good hash code based on all the fields in the class, but since you know your object's domain or value ranges you could still provide a better one.
I was just dealing with this mess after wanting longclick to not end with a click event.
Here's what I did.
public boolean onLongClick(View arg0) {
Toast.makeText(getContext(), "long click", Toast.LENGTH_SHORT).show();
longClicked = true;
return false;
}
public void onClick(View arg0) {
if(!longClicked){
Toast.makeText(getContext(), "click", Toast.LENGTH_SHORT).show();
}
longClick = false; // sets the clickability enabled
}
boolean longClicked = false;
It's a bit of a hack but it works.
You can't do it like this, but you can execute the entire query storing it in a variable.
For example:
DECLARE @listOfIDs NVARCHAR(MAX) =
'1,2,3'
DECLARE @query NVARCHAR(MAX) =
'Select *
From TabA
Where TabA.ID in (' + @listOfIDs + ')'
Exec (@query)
The Immediate window is used to debug and evaluate expressions, execute statements, print variable values, and so forth. It allows you to enter expressions to be evaluated or executed by the development language during debugging.
To display Immediate Window, choose Debug >Windows >Immediate or press Ctrl-Alt-I
Here is an example with Immediate Window:
int Sum(int x, int y) { return (x + y);}
void main(){
int a, b, c;
a = 5;
b = 7;
c = Sum(a, b);
char temp = getchar();}
add breakpoint
call commands
Use the in
keyword without is
.
if "x" in dog:
print "Yes!"
If you'd like to check for the non-existence of a character, use not in
:
if "x" not in dog:
print "No!"
unsigned char c;
for( int i = 7; i >= 0; i-- ) {
printf( "%d", ( c >> i ) & 1 ? 1 : 0 );
}
printf("\n");
Explanation:
With every iteration, the most significant bit is being read from the byte by shifting it and binary comparing with 1.
For example, let's assume that input value is 128, what binary translates to 1000 0000. Shifting it by 7 will give 0000 0001, so it concludes that the most significant bit was 1. 0000 0001 & 1 = 1. That's the first bit to print in the console. Next iterations will result in 0 ... 0.
I will do something simple like :
.thickness-underline {
display: inline-block;
text-decoration: none;
border-bottom: 1px solid black;
margin-bottom: -1px;
}
line-height
or padding-bottom
to set possition between themdisplay: inline
in some caseIf you are using Underscore.js or Lodash, there is a function 'omit' that will do it.
http://underscorejs.org/#omit
var thisIsObject= {
'Cow' : 'Moo',
'Cat' : 'Meow',
'Dog' : 'Bark'
};
_.omit(thisIsObject,'Cow'); //It will return a new object
=> {'Cat' : 'Meow', 'Dog' : 'Bark'} //result
If you want to modify the current object, assign the returning object to the current object.
thisIsObject = _.omit(thisIsObject,'Cow');
With pure JavaScript, use:
delete thisIsObject['Cow'];
Another option with pure JavaScript.
thisIsObject.cow = undefined;
thisIsObject = JSON.parse(JSON.stringify(thisIsObject ));
The colour code is the issue here. Instead of using 195/255, use 0.7647 or 195.f/255.f The problem is converting the float is not working properly. Try using exact float value.
It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:
Access-Control-Allow-Origin:*
or
Access-Control-Allow-Origin:your domain
In Apache config files, the code is like this:
Header set Access-Control-Allow-Origin "*"
In nodejs,the code is like this:
res.setHeader('Access-Control-Allow-Origin','*');
If you don't mind a third party dependency, there is a class named Collectors2 in Eclipse Collections which contains methods returning Collectors for summing and summarizing BigDecimal and BigInteger. These methods take a Function as a parameter so you can extract a BigDecimal or BigInteger value from an object.
List<BigDecimal> list = mList(
BigDecimal.valueOf(0.1),
BigDecimal.valueOf(1.1),
BigDecimal.valueOf(2.1),
BigDecimal.valueOf(0.1));
BigDecimal sum =
list.stream().collect(Collectors2.summingBigDecimal(e -> e));
Assert.assertEquals(BigDecimal.valueOf(3.4), sum);
BigDecimalSummaryStatistics statistics =
list.stream().collect(Collectors2.summarizingBigDecimal(e -> e));
Assert.assertEquals(BigDecimal.valueOf(3.4), statistics.getSum());
Assert.assertEquals(BigDecimal.valueOf(0.1), statistics.getMin());
Assert.assertEquals(BigDecimal.valueOf(2.1), statistics.getMax());
Assert.assertEquals(BigDecimal.valueOf(0.85), statistics.getAverage());
Note: I am a committer for Eclipse Collections.
I think AWK is what you are looking for:
awk '{sum+=$1}END{print sum}'
You can use this command either by passing the numbers list through the standard input or by passing the file containing the numbers as a parameter.
CMake (Cross platform make) is a build system generator. It doesn't build your source, instead, generates what a build system needs: the build scripts. Doing so you don't need to write or maintain platform specific build files. CMake uses relatively high level CMake language which usually written in CMakeLists.txt
files. Your general workflow when consuming third party libraries usually boils down the following commands:
cmake -S thelibrary -B build
cmake --build build
cmake --install build
The first line known as configuration step, this generates the build files on your system. -S
(ource) is the library source, and -B
(uild) folder. CMake falls back to generate build according to your system. it will be MSBuild on Windows, GNU Makefiles on Linux. You can specify the build using -G
(enerator) paramater, like:
cmake -G Ninja -S libSource -B build
end of the this step, generates build scripts, like Makefile, *.sln files etc. on build directory.
The second line invokes the actual build command, it's like invoking make
on the build folder.
The third line install the library. If you're on Windows, you can quickly open generated project by, cmake --open build
.
Now you can use the installed library on your project with configured by CMake, writing your own CMakeLists.txt file. To do so, you'll need to create a your target and find the package you installed using find_package
command, which will export the library target names, and link them against your own target.
Your problem is that, if the user clicks cancel, operationType
is null and thus throws a NullPointerException. I would suggest that you move
if (operationType.equalsIgnoreCase("Q"))
to the beginning of the group of if statements, and then change it to
if(operationType==null||operationType.equalsIgnoreCase("Q")).
This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.
Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.
%02x
means print at least 2 digits, prepend it with 0
's if there's less. In your case it's 7 digits, so you get no extra 0
in front.
Also, %x
is for int, but you have a long. Try %08lx
instead.
GUID is Microsoft's implementation of the UUID standard.
Per Wikipedia:
The term GUID usually refers to Microsoft's implementation of the Universally Unique Identifier (UUID) standard.
An updated quote from that same Wikipedia article:
RFC 4122 itself states that UUIDs "are also known as GUIDs". All this suggests that "GUID", while originally referring to a variant of UUID used by Microsoft, has become simply an alternative name for UUID…
What you're looking for is 'outerHTML', but wee need a fallback coz it's not compatible with old browsers.
var getString = (function() {
var DIV = document.createElement("div");
if ('outerHTML' in DIV)
return function(node) {
return node.outerHTML;
};
return function(node) {
var div = DIV.cloneNode();
div.appendChild(node.cloneNode(true));
return div.innerHTML;
};
})();
// getString(el) == "<p>Test</p>"
You'll find my jQuery plugin here: Get selected element's outer HTML
Also worth trying is the readchar library, which is in part based on the ActiveState recipe mentioned in other answers.
Installation:
pip install readchar
Usage:
import readchar
print("Reading a char:")
print(repr(readchar.readchar()))
print("Reading a key:")
print(repr(readchar.readkey()))
Tested on Windows and Linux with Python 2.7.
On Windows, only keys which map to letters or ASCII control codes are supported (Backspace, Enter, Esc, Tab, Ctrl+letter). On GNU/Linux (depending on exact terminal, perhaps?) you also get Insert, Delete, Pg Up, Pg Dn, Home, End and F n keys... but then, there's issues separating these special keys from an Esc.
Caveat: Like with most (all?) answers in here, signal keys like Ctrl+C, Ctrl+D and Ctrl+Z are caught and returned (as '\x03'
, '\x04'
and '\x1a'
respectively); your program can be come difficult to abort.
String.split()
can also accept a regular expression:
input.split(/[ ,]+/);
This particular regex splits on a sequence of one or more commas or spaces, so that e.g. multiple consecutive spaces or a comma+space sequence do not produce empty elements in the results.
Another possibility is to use regular expressions which is what Perl is famous for:
if ($mystring =~ /s1\.domain\.com/) {
print qq("$mystring" contains "s1.domain.com"\n);
}
The backslashes are needed because a .
can match any character. You can get around this by using the \Q
and \E
operators.
my $substring = "s1.domain.com";
if ($mystring =~ /\Q$substring\E/) {
print qq("$mystring" contains "$substring"\n);
}
Or, you can do as eugene y stated and use the index function.
Just a word of warning: Index returns a -1
when it can't find a match instead of an undef
or 0
.
Thus, this is an error:
my $substring = "s1.domain.com";
if (not index($mystring, $substr)) {
print qq("$mystring" doesn't contains "$substring"\n";
}
This will be wrong if s1.domain.com
is at the beginning of your string. I've personally been burned on this more than once.
A simple EXISTS clause is cleanest
select *
from table1 t1
WHERE
EXISTS
(
Select * --or 1. No difference...
From CRM_VCM_CURRENT_LEAD_STATUS Ex
Where Lead_Key = :_Lead_Key
-- correlation here...
AND
t1.CM_PLAN_ID = Ex.CM_PLAN_ID AND t1.CM_PLAN_ID = Ex.Individual_ID
)
If you have multiple rows in the correlation then a JOIN gives multiple rows in the output, so you'd need distinct. Which usually makes the EXISTS more efficient.
Note SELECT *
with a JOIN would also include columns from the row limiting tables
Do you want to this code?
public static enum FieldIndex {
HDB_TRX_ID, //TRX ID
HDB_SYS_ID //SYSTEM ID
}
public String print(ArrayList<String> itemName){
return itemName.get(FieldIndex.HDB_TRX_ID.ordinal());
}
First go to Wamp->Apache->Service->Test Port 80
If its being user by Microsoft HTTPAPI / 2.0
Then the solution is to manually stop the service named web deployment agent service
If you have Microsoft Sql Server installed, even though the IIS service is disabled, it keeps a web service named httpapi2.0 running.
I was able to use
return View::make('myviewfolder.myview', compact('view1','view2','view3'));
I don't know if it's because I am using PHP 5.5 it works great :)
Add this key in plist file...Everything will be alright..
<key>ITSAppUsesNonExemptEncryption</key>
<false/>
Just paste before </dict></plist>
You can use the sequence method list.extend
to extend the list by multiple values from any kind of iterable, being it another list or any other thing that provides a sequence of values.
>>> lst = [1, 2]
>>> lst.append(3)
>>> lst.append(4)
>>> lst
[1, 2, 3, 4]
>>> lst.extend([5, 6, 7])
>>> lst.extend((8, 9, 10))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> lst.extend(range(11, 14))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
So you can use list.append()
to append a single value, and list.extend()
to append multiple values.
Below works for me if your exe depend on some dll or certain dependency then you need to set directory path. As mention below exePath mean folder where exe placed along with it's references files.
Exe application creating any temporaray file so it will create in folder mention in processBuilder.directory(...)
**
ProcessBuilder processBuilder = new ProcessBuilder(arguments);
processBuilder.redirectOutput(Redirect.PIPE);
processBuilder.directory(new File(exePath));
process = processBuilder.start();
int waitFlag = process.waitFor();// Wait to finish application execution.
if (waitFlag == 0) {
...
int returnVal = process.exitValue();
}
**
I think the only cookie you need is JSESSIONID=xxx..
Also NEVER share your cookies, becasuse someone may access your personal data that way. Specially when the cookies are session. These cookies will stop working once you logout the site.
According to the api docs, doing:
dataFrame1.except(dataFrame2)
will return a new DataFrame containing rows in dataFrame1 but not in dataframe2.
Why using selector
as the root tag? selector
is used for applying multiple alternate drawables for different states of the view, so in this case, there is no need for selector
.
Try the following code.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Background Color -->
<solid android:color="#ffffff" />
<!-- Border Color -->
<stroke android:width="1dp" android:color="#ff9900" />
<!-- Round Corners -->
<corners android:radius="5dp" />
</shape>
Also It's worth mentioning that all color entries support alpha channel as well, meaning that you can have transparent or semi-transparent colors. For example #RRGGBBAA
.
Back in the day (and I'm not saying it's a good idea), we'd set the first element and then:
memcpy (&element [1], &element [0], sizeof (element)-sizeof (element [0]);
Not even sure it would work any more (that would depend on the implementation of memcpy) but it works by repeatedly copying the initial element to the next - even works for arrays of structures.
The previous posts information is correct, but it does not have details on how to link containers, which should be connected as "external_links".
Hope this example make more clear to you:
Suppose you have app1/docker-compose.yml, with two services (svc11 and svc12), and app2/docker-compose.yml with two more services (svc21 and svc22) and suppose you need to connect in a crossed fashion:
svc11 needs to connect to svc22's container
So the configuration should be like this:
this is app1/docker-compose.yml:
version: '2'
services:
svc11:
container_name: container11
[..]
networks:
- default # this network
- app2_default # external network
external_links:
- container22:container22
[..]
svc12:
container_name: container12
[..]
networks:
default: # this network (app1)
driver: bridge
app2_default: # external network (app2)
external: true
this is app2/docker-compose.yml:
version: '2'
services:
svc21:
container_name: container21
[..]
networks:
- default # this network (app2)
- app1_default # external network (app1)
external_links:
- container11:container11
[..]
svc22:
container_name: container22
[..]
networks:
default: # this network (app2)
driver: bridge
app1_default: # external network (app1)
external: true
Vijet Badigannavar's answer is correct but using ColorStateList
is usually complicated and he didn't tell us how to do it. Since we often focus on changing View
's color in normal and pressed state, I'm going to add more details:
If you want to change FAB
's color in normal state, you can just write
mFab.setBackgroundTintList(ColorStateList.valueOf(your color in int));
If you want to change FAB
's color in pressed state, thanks for Design Support Library 22.2.1, you can just write
mFab.setRippleColor(your color in int);
By setting this attribute, when you long-pressed the FAB
, a ripple with your color will appear at your touch point and reveal into whole surface of FAB
. Please notice that it won't change FAB
's color in normal state. Below API 21(Lollipop), there is no ripple effect but FAB
's color will still change when you're pressing it.
Finally, if you want to implement more complex effect for states, then you should dig deeply into ColorStateList
, here is a SO question discussing it: How do I create ColorStateList programmatically?.
UPDATE:
Thanks for @Kaitlyn's comment. To remove stroke of FAB using backgroundTint as its color, you can set app:borderWidth="0dp"
in your xml.
To add the contents of one list to another list which already exists, you can use:
targetList.AddRange(sourceList);
If you're just wanting to create a new copy of the list, see Lasse's answer.
you could load next clip in the onend event like that
<script type="text/javascript">
var nextVideo = "path/of/next/video.mp4";
var videoPlayer = document.getElementById('videoPlayer');
videoPlayer.onended = function(){
videoPlayer.src = nextVideo;
}
</script>
<video id="videoPlayer" src="path/of/current/video.mp4" autoplay autobuffer controls />
More information here
It's also possible to customise your bootstrap build by using:
http://twitter.github.com/bootstrap/customize.html
All the plugins are included by default.
if you need to increase reserved memory, there are VM parameters -Xms and -Xmx, usage e.g. -Xms512m -Xmx512m . There is also parameter -XX:MaxPermSize=256m which changes memory reserved for permanent generation
If your application runs as windows service, in Control panels -> Administration tools -> Services you can add some run parameters to your service
I was trying to make my module from magaplaza hello world tutorial, but something went wrong. I imported code of this module https://github.com/astorm/magento2-hello-world from github and it worked. from that module, i created it a categories subcategories ajax select drop downs Module. After installing it in aap/code directory of your magento2 installation follow this URL.. http://www.example.com/hello_mvvm/hello/world You can download its code from here https://github.com/sanaullahAhmad/Magento2_cat_subcat_ajax_select_dropdowns and place it in your aap/code folder. than run these commands...
php bin/magento setup:update
php bin/magento setup:static-content:deploy -f
php bin/magento c:c
Now you can check module functionality with following URL http://{{www.example.com}}/hello_mvvm/hello/world
You must be installing the latest version of php mysql
in my case I am install php7.1-mysql
Try this
sudo apt-get install php7.1-mysql
I am using the latest version of laravel
You need to convert the string to date using the to_date()
function
SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31-Dec-2014','DD-MON-YYYY');
OR
SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31 Dec 2014','DD MON YYYY');
OR
SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('2014-12-31','yyyy-MM-dd');
This will work only if OrderDate
is stored in Date format
. If it is Varchar
you should apply to_date()
func on that column also like
SELECT * FROM OrderArchive
WHERE to_date(OrderDate,'yyyy-Mm-dd') <= to_date('2014-12-31','yyyy-MM-dd');
Here is how you can do it:
std::string & trim(std::string & str)
{
return ltrim(rtrim(str));
}
And the supportive functions are implemeted as:
std::string & ltrim(std::string & str)
{
auto it2 = std::find_if( str.begin() , str.end() , [](char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
str.erase( str.begin() , it2);
return str;
}
std::string & rtrim(std::string & str)
{
auto it1 = std::find_if( str.rbegin() , str.rend() , [](char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
str.erase( it1.base() , str.end() );
return str;
}
And once you've all these in place, you can write this as well:
std::string trim_copy(std::string const & str)
{
auto s = str;
return ltrim(rtrim(s));
}
Try this
Best option is to disable sorting and just feed data with desired sort order (from database or other source). Try to add this to your 'datatable': "bSort": false
Refer to the Flask API document for flask.url_for()
Other sample snippets of usage for linking js or css to your template are below.
<script src="{{ url_for('static', filename='jquery.min.js') }}"></script>
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
If you mean using a literal, you simply have to create a binary string:
insert into Files (FileId, FileData) values (1, 0x010203040506)
And you will have a record with a six byte value for the FileData field.
You indicate in the comments that you want to just specify the file name, which you can't do with SQL Server 2000 (or any other version that I am aware of).
You would need a CLR stored procedure to do this in SQL Server 2005/2008 or an extended stored procedure (but I'd avoid that at all costs unless you have to) which takes the filename and then inserts the data (or returns the byte string, but that can possibly be quite long).
In regards to the question of only being able to get data from a SP/query, I would say the answer is yes, because if you give SQL Server the ability to read files from the file system, what do you do when you aren't connected through Windows Authentication, what user is used to determine the rights? If you are running the service as an admin (God forbid) then you can have an elevation of rights which shouldn't be allowed.
In my case, I needed an input button to have a line break before it.
I applied the following style to the button and it worked:
clear:both;
There are many ways to run javascript in Visual Studio Code.
If you use Node, then I recommend use the standard debugger in VSC.
I normally create a dummy file, like test.js where I do external tests.
In your folder where you have your code, you create a folder called ".vscode" and create a file called "launch.json"
In this file you paste the following and save. Now you have two options to test your code.
When you choose "Nodemon Test File" you need to put your code to test in test.js.
To install nodemon and more info on how to debug with nodemon in VSC I recommend to read this article, which explain in more detail the second part on the launch.json file and how to debug in ExpressJS.
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Nodemon Test File",
"runtimeExecutable": "nodemon",
"program": "${workspaceFolder}/test.js",
"restart": true,
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
},
{
"type": "node",
"request": "attach",
"name": "Node: Nodemon",
"processId": "${command:PickProcess}",
"restart": true,
"protocol": "inspector",
},
]
}
call: getStackTraceAsString(sqlEx)
public String getStackTraceAsString(Exception exc)
{
String stackTrace = "*** Error in getStackTraceAsString()";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream( baos );
exc.printStackTrace(ps);
try {
stackTrace = baos.toString( "UTF8" ); // charsetName e.g. ISO-8859-1
}
catch( UnsupportedEncodingException ex )
{
Logger.getLogger(sss.class.getName()).log(Level.SEVERE, null, ex);
}
ps.close();
try {
baos.close();
}
catch( IOException ex )
{
Logger.getLogger(sss.class.getName()).log(Level.SEVERE, null, ex);
}
return stackTrace;
}
add all type inputs to FormData
const formData = new FormData();
for (let key in form) {
Array.isArray(form[key])
? form[key].forEach(value => formData.append(key + '[]', value))
: formData.append(key, form[key]) ;
}
try it , but first be sure what is you response console.log(response) on ajax success from server
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var form=$("#myForm");
$("#smt").click(function(){
$.ajax({
type:"POST",
url:form.attr("action"),
data:form.serialize(),
success: function(response){
if(response === 1){
//load chech.php file
} else {
//show error
}
}
});
});
});
You should be able to use CSS (http://docs.jquery.com/CSS/css#name). You may have to be more specific such as "padding-left" or "margin-top".
Example:
CSS
a, a:link, a:hover, a:visited, a:active {color:black;margin-top:10px;text-decoration: none;}
JS
$("a").css("margin-top");
The result is 10px.
If you want to get the integer value, you can do the following:
parseInt($("a").css("margin-top"))
If you get that error message (Peer authentication failed for user (PG::Error)
) when running unit tests, make sure the test database exists.
You can use Create USer to create a user
CREATE LOGIN sam
WITH PASSWORD = '340$Uuxwp7Mcxo7Khy';
USE AdventureWorks;
CREATE USER sam FOR LOGIN sam;
GO
and to Grant (Read-only access) you can use the following
GRANT SELECT TO sam
Hope that helps.
Just to answer the add()
vs offer()
question (since the other one is perfectly answered imo, and this might not be):
According to JavaDoc on interface Queue, "The offer method inserts an element if possible, otherwise returning false. This differs from the Collection.add method, which can fail to add an element only by throwing an unchecked exception. The offer method is designed for use when failure is a normal, rather than exceptional occurrence, for example, in fixed-capacity (or "bounded") queues."
That means if you can add the element (which should always be the case in a PriorityQueue), they work exactly the same. But if you can't add the element, offer()
will give you a nice and pretty false
return, while add()
throws a nasty unchecked exception that you don't want in your code. If failure to add means code is working as intended and/or it is something you'll check normally, use offer()
. If failure to add means something is broken, use add()
and handle the resulting exception thrown according to the Collection interface's specifications.
They are both implemented this way to fullfill the contract on the Queue interface that specifies offer()
fails by returning a false
(method preferred in capacity-restricted queues) and also maintain the contract on the Collection interface that specifies add()
always fails by throwing an exception.
Anyway, hope that clarifies at least that part of the question.
In Java, Dates are internally represented in UTC milliseconds since the epoch (so timezones are not taken into account, that's why you get the same results, as getTime()
gives you the mentioned milliseconds).
In your solution:
Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long gmtTime = cSchedStartCal.getTime().getTime();
long timezoneAlteredTime = gmtTime + TimeZone.getTimeZone("Asia/Calcutta").getRawOffset();
Calendar cSchedStartCal1 = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
cSchedStartCal1.setTimeInMillis(timezoneAlteredTime);
you just add the offset from GMT to the specified timezone ("Asia/Calcutta" in your example) in milliseconds, so this should work fine.
Another possible solution would be to utilise the static fields of the Calendar
class:
//instantiates a calendar using the current time in the specified timezone
Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
//change the timezone
cSchedStartCal.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
//get the current hour of the day in the new timezone
cSchedStartCal.get(Calendar.HOUR_OF_DAY);
Refer to stackoverflow.com/questions/7695859/ for a more in-depth explanation.
With a list comprehension:
a = [x - 13 for x in a]
Use LocalDate
from java.time, the modern Java date and time API, for a date
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MMMM d, u", Locale.ENGLISH);
LocalDate date = LocalDate.parse("June 27, 2007", dateFormatter);
System.out.println(date);
Output:
2007-06-27
As others have said already, remember to specify an English-speaking locale when your string is in English. A LocalDate
is a date without time of day, so a lot better suitable for the date from your string than the old Date
class. Despite its name a Date
does not represent a date but a point in time that falls on at least two different dates in different time zones of the world.
Only if you need an old-fashioned Date
for an API that you cannot afford to upgrade to java.time just now, convert like this:
Instant startOfDay = date.atStartOfDay(ZoneId.systemDefault()).toInstant();
Date oldfashionedDate = Date.from(startOfDay);
System.out.println(oldfashionedDate);
Output in my time zone:
Wed Jun 27 00:00:00 CEST 2007
Oracle tutorial: Date Time explaining how to use java.time.
You should really post:
Here is my code, which works:
import socket, sys
def alert(msg):
print >>sys.stderr, msg
sys.exit(1)
(family, socktype, proto, garbage, address) = \
socket.getaddrinfo("::1", "http")[0] # Use only the first tuple
s = socket.socket(family, socktype, proto)
try:
s.connect(address)
except Exception, e:
alert("Something's wrong with %s. Exception type is %s" % (address, e))
When the server listens, I get nothing (this is normal), when it doesn't, I get the expected message:
Something's wrong with ('::1', 80, 0, 0). Exception type is (111, 'Connection refused')
In C++ and C switches only work on integer types. Use an if else ladder instead. C++ could obviously have implemented some sort of swich statement for strings - I guess nobody thought it worthwhile, and I agree with them.
The best approach would depend on how you plan to arrange those components. A few example scenarios that come to mind right now:
<Filters />
is a child component of <List />
<Filters />
and <List />
are children of a parent component<Filters />
and <List />
live in separate root components entirely.There may be other scenarios that I'm not thinking of. If yours doesn't fit within these, then let me know. Here are some very rough examples of how I've been handling the first two scenarios:
You could pass a handler from <List />
to <Filters />
, which could then be called on the onChange
event to filter the list with the current value.
/** @jsx React.DOM */
var Filters = React.createClass({
handleFilterChange: function() {
var value = this.refs.filterInput.getDOMNode().value;
this.props.updateFilter(value);
},
render: function() {
return <input type="text" ref="filterInput" onChange={this.handleFilterChange} placeholder="Filter" />;
}
});
var List = React.createClass({
getInitialState: function() {
return {
listItems: ['Chicago', 'New York', 'Tokyo', 'London', 'San Francisco', 'Amsterdam', 'Hong Kong'],
nameFilter: ''
};
},
handleFilterUpdate: function(filterValue) {
this.setState({
nameFilter: filterValue
});
},
render: function() {
var displayedItems = this.state.listItems.filter(function(item) {
var match = item.toLowerCase().indexOf(this.state.nameFilter.toLowerCase());
return (match !== -1);
}.bind(this));
var content;
if (displayedItems.length > 0) {
var items = displayedItems.map(function(item) {
return <li>{item}</li>;
});
content = <ul>{items}</ul>
} else {
content = <p>No items matching this filter</p>;
}
return (
<div>
<Filters updateFilter={this.handleFilterUpdate} />
<h4>Results</h4>
{content}
</div>
);
}
});
React.renderComponent(<List />, document.body);
Similar to scenario #1, but the parent component will be the one passing down the handler function to <Filters />
, and will pass the filtered list to <List />
. I like this method better since it decouples the <List />
from the <Filters />
.
/** @jsx React.DOM */
var Filters = React.createClass({
handleFilterChange: function() {
var value = this.refs.filterInput.getDOMNode().value;
this.props.updateFilter(value);
},
render: function() {
return <input type="text" ref="filterInput" onChange={this.handleFilterChange} placeholder="Filter" />;
}
});
var List = React.createClass({
render: function() {
var content;
if (this.props.items.length > 0) {
var items = this.props.items.map(function(item) {
return <li>{item}</li>;
});
content = <ul>{items}</ul>
} else {
content = <p>No items matching this filter</p>;
}
return (
<div className="results">
<h4>Results</h4>
{content}
</div>
);
}
});
var ListContainer = React.createClass({
getInitialState: function() {
return {
listItems: ['Chicago', 'New York', 'Tokyo', 'London', 'San Francisco', 'Amsterdam', 'Hong Kong'],
nameFilter: ''
};
},
handleFilterUpdate: function(filterValue) {
this.setState({
nameFilter: filterValue
});
},
render: function() {
var displayedItems = this.state.listItems.filter(function(item) {
var match = item.toLowerCase().indexOf(this.state.nameFilter.toLowerCase());
return (match !== -1);
}.bind(this));
return (
<div>
<Filters updateFilter={this.handleFilterUpdate} />
<List items={displayedItems} />
</div>
);
}
});
React.renderComponent(<ListContainer />, document.body);
When the components can't communicate between any sort of parent-child relationship, the documentation recommends setting up a global event system.
You can use that style of comment across multiple lines (which exists also in HTML)
<detail>
<band height="20">
<!--
Hello,
I am a multi-line XML comment
<staticText>
<reportElement x="180" y="0" width="200" height="20"/>
<text><![CDATA[Hello World!]]></text>
</staticText>
-->
</band>
</detail>
You could use only delegate which is best for callback functions:
public class ServerRequest
{
public delegate void CallBackFunction(string input);
public void DoRequest(string request, CallBackFunction callback)
{
// do stuff....
callback(request);
}
}
and consume this like below:
public class Class1
{
private void btn_click(object sender, EventArgs e)
{
ServerRequest sr = new ServerRequest();
var callback = new ServerRequest.CallBackFunction(CallbackFunc);
sr.DoRequest("myrequest",callback);
}
void CallbackFunc(string something)
{
}
}
If you mean that you want to enable the submit after the user has typed at least one character, then you need to attach a key event that will check it for you.
Something like:
$("#fbss").keypress(function() {
if($(this).val().length > 1) {
// Enable submit button
} else {
// Disable submit button
}
});
The simple way to fill the shape with the Radius is:
(view.getBackground()).setColorFilter(Color.parseColor("#FFDE03"), PorterDuff.Mode.SRC_IN);
Here we go... just copy the code to a module, it's ready to use
Private Type hashtable
key As Variant
value As Variant
End Type
Private GetErrMsg As String
Private Function CreateHashTable(htable() As hashtable) As Boolean
GetErrMsg = ""
On Error GoTo CreateErr
ReDim htable(0)
CreateHashTable = True
Exit Function
CreateErr:
CreateHashTable = False
GetErrMsg = Err.Description
End Function
Private Function AddValue(htable() As hashtable, key As Variant, value As Variant) As Long
GetErrMsg = ""
On Error GoTo AddErr
Dim idx As Long
idx = UBound(htable) + 1
Dim htVal As hashtable
htVal.key = key
htVal.value = value
Dim i As Long
For i = 1 To UBound(htable)
If htable(i).key = key Then Err.Raise 9999, , "Key [" & CStr(key) & "] is not unique"
Next i
ReDim Preserve htable(idx)
htable(idx) = htVal
AddValue = idx
Exit Function
AddErr:
AddValue = 0
GetErrMsg = Err.Description
End Function
Private Function RemoveValue(htable() As hashtable, key As Variant) As Boolean
GetErrMsg = ""
On Error GoTo RemoveErr
Dim i As Long, idx As Long
Dim htTemp() As hashtable
idx = 0
For i = 1 To UBound(htable)
If htable(i).key <> key And IsEmpty(htable(i).key) = False Then
ReDim Preserve htTemp(idx)
AddValue htTemp, htable(i).key, htable(i).value
idx = idx + 1
End If
Next i
If UBound(htable) = UBound(htTemp) Then Err.Raise 9998, , "Key [" & CStr(key) & "] not found"
htable = htTemp
RemoveValue = True
Exit Function
RemoveErr:
RemoveValue = False
GetErrMsg = Err.Description
End Function
Private Function GetValue(htable() As hashtable, key As Variant) As Variant
GetErrMsg = ""
On Error GoTo GetValueErr
Dim found As Boolean
found = False
For i = 1 To UBound(htable)
If htable(i).key = key And IsEmpty(htable(i).key) = False Then
GetValue = htable(i).value
Exit Function
End If
Next i
Err.Raise 9997, , "Key [" & CStr(key) & "] not found"
Exit Function
GetValueErr:
GetValue = ""
GetErrMsg = Err.Description
End Function
Private Function GetValueCount(htable() As hashtable) As Long
GetErrMsg = ""
On Error GoTo GetValueCountErr
GetValueCount = UBound(htable)
Exit Function
GetValueCountErr:
GetValueCount = 0
GetErrMsg = Err.Description
End Function
To use in your VB(A) App:
Public Sub Test()
Dim hashtbl() As hashtable
Debug.Print "Create Hashtable: " & CreateHashTable(hashtbl)
Debug.Print ""
Debug.Print "ID Test Add V1: " & AddValue(hashtbl, "Hallo_0", "Testwert 0")
Debug.Print "ID Test Add V2: " & AddValue(hashtbl, "Hallo_0", "Testwert 0")
Debug.Print "ID Test 1 Add V1: " & AddValue(hashtbl, "Hallo.1", "Testwert 1")
Debug.Print "ID Test 2 Add V1: " & AddValue(hashtbl, "Hallo-2", "Testwert 2")
Debug.Print "ID Test 3 Add V1: " & AddValue(hashtbl, "Hallo 3", "Testwert 3")
Debug.Print ""
Debug.Print "Test 1 Removed V1: " & RemoveValue(hashtbl, "Hallo_1")
Debug.Print "Test 1 Removed V2: " & RemoveValue(hashtbl, "Hallo_1")
Debug.Print "Test 2 Removed V1: " & RemoveValue(hashtbl, "Hallo-2")
Debug.Print ""
Debug.Print "Value Test 3: " & CStr(GetValue(hashtbl, "Hallo 3"))
Debug.Print "Value Test 1: " & CStr(GetValue(hashtbl, "Hallo_1"))
Debug.Print ""
Debug.Print "Hashtable Content:"
For i = 1 To UBound(hashtbl)
Debug.Print CStr(i) & ": " & CStr(hashtbl(i).key) & " - " & CStr(hashtbl(i).value)
Next i
Debug.Print ""
Debug.Print "Count: " & CStr(GetValueCount(hashtbl))
End Sub
Use the following to convert uint8 array to base64 encoded string
function arrayBufferToBase64(buffer) {
var binary = '';
var bytes = [].slice.call(new Uint8Array(buffer));
bytes.forEach((b) => binary += String.fromCharCode(b));
return window.btoa(binary);
};
Rather simple:
Key = i.ToString("D2");
D
stands for "decimal number", 2
for the number of digits to print.
Pipe them through sort
and uniq
. This removes all duplicates.
uniq -d
gives only the duplicates, uniq -u
gives only the unique ones (strips duplicates).
.prop('disabled')
will return a Boolean:
var isDisabled = $('textbox').prop('disabled');
Here's the fiddle: http://jsfiddle.net/unhjM/
If you remember which branch was checked out before (e.g. master
) you could simply
git checkout master
to get out of detached HEAD state.
Generally speaking: git checkout <branchname>
will get you out of that.
If you don't remember the last branch name, try
git checkout -
This also tries to check out your last checked out branch.
tag_story.splice(tag_story.indexOf(id_tag), 1);
Using a UI Framework would be a lot cleaner (and involve fewer components). Here is an example using wxPython:
import wx
import os
class MyForm(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Launch Scripts")
panel = wx.Panel(self, wx.ID_ANY)
sizer = wx.BoxSizer(wx.VERTICAL)
buttonA = wx.Button(panel, id=wx.ID_ANY, label="App A", name="MYSCRIPT")
buttonB = wx.Button(panel, id=wx.ID_ANY, label="App B", name="MYOtherSCRIPT")
buttonC = wx.Button(panel, id=wx.ID_ANY, label="App C", name="SomeDifferentScript")
buttons = [buttonA, buttonB, buttonC]
for button in buttons:
self.buildButtons(button, sizer)
panel.SetSizer(sizer)
def buildButtons(self, btn, sizer):
btn.Bind(wx.EVT_BUTTON, self.onButton)
sizer.Add(btn, 0, wx.ALL, 5)
def onButton(self, event):
"""
This method is fired when its corresponding button is pressed, taking the script from it's name
"""
button = event.GetEventObject()
os.system('python {}.py'.format(button.GetName()))
button_id = event.GetId()
button_by_id = self.FindWindowById(button_id)
print "The button you pressed was labeled: " + button_by_id.GetLabel()
print "The button's name is " + button_by_id.GetName()
# Run the program
if __name__ == "__main__":
app = wx.App(False)
frame = MyForm()
frame.Show()
app.MainLoop()
I haven't tested this yet, and I'm sure there are cleaner ways of launching a python script form a python script, but the idea I think will still hold. Good luck!
To generate an area where you can specify a description for the function and each parameter for the function, type the following on the line before your function and hit Enter:
C#: ///
VB: '''
See Recommended Tags for Documentation Comments (C# Programming Guide) for more info on the structured content you can include in these comments.
After Command + Shift + B, the project works fine.
foreach($_POST as $key=>$value)
{
if(empty(trim($value))
echo "$key input required of value ";
}
public class Producto {
int idProducto;
String nombre;
Double precio;
public Producto(int idProducto, String nombre, Double precio) {
this.idProducto = idProducto;
this.nombre = nombre;
this.precio = precio;
}
public int getIdProducto() {
return idProducto;
}
public void setIdProducto(int idProducto) {
this.idProducto = idProducto;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public Double getPrecio() {
return precio;
}
public void setPrecio(Double precio) {
this.precio = precio;
}
public String toJSON(){
JSONObject jsonObject= new JSONObject();
try {
jsonObject.put("id", getIdProducto());
jsonObject.put("nombre", getNombre());
jsonObject.put("precio", getPrecio());
return jsonObject.toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
You can simply add @HostBinding('class') class = 'someClass';
inside your @Component class.
Example:
@Component({
selector: 'body',
template: 'app-element'
})
export class App implements OnInit {
@HostBinding('class') class = 'someClass';
constructor() {}
ngOnInit() {}
}
Enabling Developer mode by tapping on Build Number 7 times worked for me.
I had the same error. In my case I am using Netbeans 7.1.2, I am posting this because maybe someone end up here same as I did.
I tried to configure the proxy options from the GUI, but the documentation says that maven doesn't read those. So I checked the NetBeans FAQ here :
What mainly you have to do is create (if it does not exist) a settings.xml under
user.home/.m2/settings.xml
if you don't have it you can copy from
netbeans.home/java/maven/conf/settings.xml
then uncomment if you already have it otherwise just fill this section:
<proxies>
<proxy>
<active>true</active>
<host>myproxy.host.net</host>
<port>80</port>
</proxy>
</proxies>
you have to check your proxy configuration and replace it there
For adding background icon always before text when length of text is not known in advance.
.create:before{
content: "";
display: inline-block;
background: #ccc url(arrow.png) no-repeat;
width: 10px;background-size: contain;
height: 10px;
}
to check input and get confirm by check box ,use this script...
$(document).on("change", ".inputClass", function () {
if($(this).is(':checked')){
confirm_message = $(this).data('confirm');
var confirm_status = confirm(confirm_message);
if (confirm_status == true) {
//doing somethings...
}
}});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label> check action </lable>
<input class="inputClass" type="checkbox" data-confirm="are u sure to do ...?" >
_x000D_
complete.cases
gives TRUE
when all values in a row are not NA
DF[!complete.cases(DF), ]
Another option would be to use a keyed data.table
:
library(data.table)
setDT(dt, key = 'fct')[J(vc)] # or: setDT(dt, key = 'fct')[.(vc)]
which results in:
fct X
1: a 2
2: a 7
3: a 1
4: c 3
5: c 5
6: c 9
7: c 2
8: c 4
What this does:
setDT(dt, key = 'fct')
transforms the data.frame
to a data.table
(which is an enhanced form of a data.frame
) with the fct
column set as key.vc
vector with [J(vc)]
.NOTE: when the key is a factor/character variable, you can also use setDT(dt, key = 'fct')[vc]
but that won't work when vc
is a numeric vector. When vc
is a numeric vector and is not wrapped in J()
or .()
, vc
will work as a rowindex.
A more detailed explanation of the concept of keys and subsetting can be found in the vignette Keys and fast binary search based subset.
An alternative as suggested by @Frank in the comments:
setDT(dt)[J(vc), on=.(fct)]
When vc
contains values that are not present in dt
, you'll need to add nomatch = 0
:
setDT(dt, key = 'fct')[J(vc), nomatch = 0]
or:
setDT(dt)[J(vc), on=.(fct), nomatch = 0]
Geany is a great lightweight editor -- like Notepad++ for Linux, only better. I find this, combined with a few shell scripts and symlinks for linking modules into a web source tree, make developing on Linux easy and fun.
Use GetLength(), rather than Length.
int rowsOrHeight = ary.GetLength(0);
int colsOrWidth = ary.GetLength(1);
A couple of examples:
infix fun Double.f(fmt: String) = "%$fmt".format(this)
infix fun Double.f(fmt: Float) = "%${if (fmt < 1) fmt + 1 else fmt}f".format(this)
val pi = 3.14159265358979323
println("""pi = ${pi f ".2f"}""")
println("pi = ${pi f .2f}")
I had facing the same problem, I really need to send a key from my jsp to java script, It spend around 4h or more of my day to solve it.
I include this tag on my JavaScript/JSP:
$scope.sucessMessage = function (){ _x000D_
var message = ($scope.messages.sucess).format($scope.portfolio.name,$scope.portfolio.id);_x000D_
$scope.inforMessage = message;_x000D_
alert(message); _x000D_
}_x000D_
_x000D_
_x000D_
String.prototype.format = function() {_x000D_
var formatted = this;_x000D_
for( var arg in arguments ) {_x000D_
formatted = formatted.replace("{" + arg + "}", arguments[arg]);_x000D_
}_x000D_
return formatted;_x000D_
};
_x000D_
<!-- Messages definition -->_x000D_
<input type="hidden" name="sucess" ng-init="messages.sucess='<fmt:message key='portfolio.create.sucessMessage' />'" >_x000D_
_x000D_
<!-- Message showed affter insert -->_x000D_
<div class="alert alert-info" ng-show="(inforMessage.length > 0)">_x000D_
{{inforMessage}}_x000D_
</div>_x000D_
_x000D_
<!-- properties_x000D_
portfolio.create.sucessMessage=Portf\u00f3lio {0} criado com sucesso! ID={1}. -->
_x000D_
The result was: Portfólio 1 criado com sucesso! ID=3.
Best Regards
I think this should do it.
declare @x int;
select @x = max(id) from table_name;
select * from where id = @x;
set a style for the image
<asp:Image ID="Image1" runat="server" style="max-height:1000px;max-width:900px;height:auto;width:auto;" />
To test a scenario with a void method like
void testMeWell() throws SomeException {..}
to not throw an exception:
Junit5
assertDoesNotThrow(() -> {
testMeWell();
});
Update to Android Studio 3.0.1 which treats these as warnings. Android 3.0 was treating such warnings as errors and hence causing the gradle sync operation to fail.
In Tomcat 6, the CLASSPATH in your environment is ignored. In setclasspath.bat you'll see
set CLASSPATH=%JAVA_HOME%\lib\tools.jar
then in catalina.bat, it's used like so
%_EXECJAVA% %JAVA_OPTS% %CATALINA_OPTS% %DEBUG_OPTS%
-Djava.endorsed.dirs="%JAVA_ENDORSED_DIRS%" -classpath "%CLASSPATH%"
-Dcatalina.base="%CATALINA_BASE%" -Dcatalina.home="%CATALINA_HOME%"
-Djava.io.tmpdir="%CATALINA_TMPDIR%" %MAINCLASS% %CMD_LINE_ARGS% %ACTION%
I don't see any other vars that are included, so I think you're stuck with editing setclasspath.bat and changing how CLASSPATH is built. For Tomcat 6.0.20, this change was on like 74 of setclasspath.bat
set CLASSPATH=C:\app_config\java_app;%JAVA_HOME%\lib\tools.jar
The most possible reason for it not to find the file is the path having spaces in. For example, it won't find "explorer /select,c:\space space\space.txt".
Just add double quotes before and after the path, like;
explorer /select,"c:\space space\space.txt"
or do the same in C# with
System.Diagnostics.Process.Start("explorer.exe","/select,\"c:\space space\space.txt\"");
An alternative answer that uses today()
method to calculate current date and then subtracts one using timedelta()
. Rest of the steps remain the same.
https://docs.python.org/3.7/library/datetime.html#timedelta-objects
from datetime import date, timedelta
today = date.today()
yesterday = today - timedelta(days = 1)
print(today)
print(yesterday)
Output:
2019-06-14
2019-06-13
I have Tried something like this and its works fine;
this is the html part :
<table class="dd" width="100%" id="data">
<tr>
<td>Year</td>
<td>:</td>
<td><select name="year1" id="year1" >
<option value="2012">2012</option>
<option value="2011">2011</option>
</select></td>
<td>Month</td>
<td>:</td>
<td width="17%"><select name="month1" id="month1">
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select></td>
<td width="7%">Week</td>
<td width="3%">:</td>
<td width="17%"><select name="week1" id="week1" >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select></td>
<td width="8%"> </td>
<td colspan="2"> </td>
</tr>
<tr>
<td>Actual</td>
<td>:</td>
<td width="17%"><input name="actual1" id="actual1" type="text" /></td>
<td width="7%">Max</td>
<td width="3%">:</td>
<td><input name="max1" id="max1" type="text" /></td>
<td>Target</td>
<td>:</td>
<td><input name="target1" id="target1" type="text" /></td>
</tr>
this is Javascript part;
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type='text/javascript'>
//<![CDATA[
$(document).ready(function() {
var currentItem = 1;
$('#addnew').click(function(){
currentItem++;
$('#items').val(currentItem);
var strToAdd = '<tr><td>Year</td><td>:</td><td><select name="year'+currentItem+'" id="year'+currentItem+'" ><option value="2012">2012</option><option value="2011">2011</option></select></td><td>Month</td><td>:</td><td width="17%"><select name="month'+currentItem+'" id="month'+currentItem+'"><option value="1">January</option><option value="2">February</option><option value="3">March</option><option value="4">April</option><option value="5">May</option><option value="6">June</option><option value="7">July</option><option value="8">August</option><option value="9">September</option><option value="10">October</option><option value="11">November</option><option value="12">December</option></select></td><td width="7%">Week</td><td width="3%">:</td><td width="17%"><select name="week'+currentItem+'" id="week'+currentItem+'" ><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option></select></td><td width="8%"></td><td colspan="2"></td></tr><tr><td>Actual</td><td>:</td><td width="17%"><input name="actual'+currentItem+'" id="actual'+currentItem+'" type="text" /></td><td width="7%">Max</td> <td width="3%">:</td><td><input name="max'+currentItem+'" id ="max'+currentItem+'"type="text" /></td><td>Target</td><td>:</td><td><input name="target'+currentItem+'" id="target'+currentItem+'" type="text" /></td></tr>';
$('#data').append(strToAdd);
});
});
//]]>
</script>
Finaly PHP submit part:
for( $i = 1; $i <= $count; $i++ )
{
$year = $_POST['year'.$i];
$month = $_POST['month'.$i];
$week = $_POST['week'.$i];
$actual = $_POST['actual'.$i];
$max = $_POST['max'.$i];
$target = $_POST['target'.$i];
$extreme = $_POST['extreme'.$i];
$que = "insert INTO table_name(id,year,month,week,actual,max,target) VALUES ('".$_POST['type']."','".$year."','".$month."','".$week."','".$actual."','".$max."','".$target."')";
mysql_query($que);
}
you can find more details via Dynamic table row inserter
React hook - useRef
const MyComponent = ({myRef}) => {
const handleClick = () => alert('hello world')
myRef.current.handleClick = handleClick
return (<button onClick={handleClick}>Original Button</button>)
}
MyComponent.defaultProps = {
myRef: {current: {}}
}
const MyParentComponent = () => {
const myRef = React.useRef({})
return (
<>
<MyComponent
myRef={myRef}
/>
<button onClick={myRef.current.handleClick}>
Additional Button
</button>
</>
)
}
Good Luck...
The Declarative model for Jenkins Pipelines has a restricted subset of syntax that it allows in the stage
blocks - see the syntax guide for more info. You can bypass that restriction by wrapping your steps in a script { ... }
block, but as a result, you'll lose validation of syntax, parameters, etc within the script
block.
You can do it programmatically like
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editTextField.getWindowToken(), 0);
or set android:windowSoftInputMode="stateHidden"
in <activity tag
inside AndroidManifest.xml
I had a similar issue reading the serial output from a digital scale. I was reading [3:12] out of a 18 characters long output string.
In my case sometimes there is a null character "\x00" (NUL) which magically appears in the scale's reply string and is not printed.
I was getting the error:
> ' 0.00'
> 3 0 fast loop, delta = 10.0 weight = 0.0
> ' 0.00'
> 1 800 fast loop, delta = 10.0 weight = 0.0
> ' 0.00'
> 6 0 fast loop, delta = 10.0 weight = 0.0
> ' 0\x00.0'
> Traceback (most recent call last):
> File "measure_weight_speed.py", line 172, in start
> valueScale = float(answer_string)
> ValueError: invalid literal for float(): 0
After some research I wrote few lines of code that work in my case.
replyScale = scale_port.read(18)
answer = replyScale[3:12]
answer_decode = answer.replace("\x00", "")
answer_strip = str(answer_decode.strip())
print(repr(answer_strip))
valueScale = float(answer_strip)
The answers in these posts helped:
Old topic, but never clearly answered. I've been working on similar as well, and found the solution:
The pipe (|) in this code sample from Austin isn't the delimiter, but to pipe the ForEach-Object, so if you want to use it as delimiter, you need to do this:
Import-Csv H:\Programs\scripts\SomeText.csv -delimiter "|" |`
ForEach-Object {
$Name += $_.Name
$Phone += $_."Phone Number"
}
Spent a good 15 minutes on this myself before I understood what was going on. Hope the answer helps the next person reading this avoid the wasted minutes! (Sorry for expanding on your comment Austin)
You need httpclient.jar and httpcore.jar. You can download them from here.
http://archive.apache.org/dist/httpcomponents/httpclient/binary/
You could use a negative look-ahead assertion:
^(?!tbd_).+
Or a negative look-behind assertion:
(^.{1,3}$|^.{4}(?<!tbd_).*)
Or just plain old character sets and alternations:
^([^t]|t($|[^b]|b($|[^d]|d($|[^_])))).*
git branch -a | grep remotes/*
WCF = Windows Communication Foundation is used to build service-oriented applications. WPF = Windows Presentation Foundation is used to write platform-independent applications.
I've been using the JWT authentication. Works just fine in my application.
There is an authentication method that will require the user credentials. This method validates the credentials and returns an access token in case of success.
This token must be sent to every other method in my Web API in the header of the request.
It's pretty easy to implement, and very easy to test.
As Simon says above, using drawImage shouldn't work. But, using the canvg library and:
var c = document.getElementById('canvas');
var ctx = c.getContext('2d');
ctx.drawSvg(SVG_XML_OR_PATH_TO_SVG, dx, dy, dw, dh);
This comes from the link Simon provides above, which has a number of other suggestions and points out that you want to either link to, or download canvg.js and rgbcolor.js. These allow you to manipulate and load an SVG, either via URL or using inline SVG code between svg tags, within JavaScript functions.
The zip()
function in Python 3 returns an iterator. That is the reason why when you print test1
you get - <zip object at 0x1007a06c8>
. From documentation -
Make an iterator that aggregates elements from each of the iterables.
But once you do - list(test1)
- you have exhausted the iterator. So after that anytime you do list(test1)
would only result in empty list.
In case of test2
, you have already created the list once, test2
is a list, and hence it will always be that list.
For future readers, "Still Reachable" might mean you forgot to close something like a file. While it doesn't seem that way in the original question, you should always make sure you've done that.
Setting android:clipToPadding="false" in the top relative layout has solved the problem.
As eaon21 and monkey said, source map files basically turn minified code into its unminified version for debugging.
You can find the .map files here. Just add them into the same directory as the minified js files and it'll stop complaining. The reason they get fetched is the
/*
//@ sourceMappingURL=angular.min.js.map
*/
at the end of angular.min.js. If you don't want to add the .map files you can remove those lines and it'll stop the fetch attempt, but if you plan on debugging it's always good to keep the source maps linked.
XML pretty print for python looks pretty good for this task. (Appropriately named, too.)
An alternative is to use pyXML, which has a PrettyPrint function.
Another way is to simply pass the json string as a dict to the constructor of your object. For example your object is:
class Payload(object):
def __init__(self, action, method, data, *args, **kwargs):
self.action = action
self.method = method
self.data = data
And the following two lines of python code will construct it:
j = json.loads(yourJsonString)
payload = Payload(**j)
Basically, we first create a generic json object from the json string. Then, we pass the generic json object as a dict to the constructor of the Payload class. The constructor of Payload class interprets the dict as keyword arguments and sets all the appropriate fields.
1 byte may hold 1 character. For Example: Refer Ascii values for each character & convert into binary. This is how it works.
value 255 is stored as (11111111) base 2. Visit this link for knowing more about binary conversion. http://acc6.its.brooklyn.cuny.edu/~gurwitz/core5/nav2tool.html
Size of Tiny Int = 1 Byte ( -128 to 127)
Int = 4 Bytes (-2147483648 to 2147483647)
class MyApp2 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
appBarTheme: AppBarTheme(
elevation: 0,
color: Colors.blueAccent,
)
),
title: 'Welcome to flutter ',
home: HomePage()
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int number = 0;
void _increment(){
setState(() {
number ++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blueAccent,
appBar: AppBar(
title: Text('MyApp2'),
leading: Icon(Icons.menu),
// backgroundColor: Colors.blueAccent,
),
body: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(200.0),
topRight: Radius.circular(200)
),
color: Colors.white,
),
)
);
}
}
Here is an example of how I did this. This gets the index at the for each loop. Hope this helps.
public class CheckForEachLoop {
public static void main(String[] args) {
String[] months = new String[] { "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST",
"SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" };
for (String s : months) {
if (s == months[2]) { // location where you can change
doSomethingWith(s); // however many times s and months
// doSomethingWith(s) will be completed and
// added together instead of counter
}
}
System.out.println(s);
}
}
getline
runnable example
getline
was mentioned on this answer but here is an example.
It is POSIX 7, allocates memory for us, and reuses the allocated buffer on a loop nicely.
Pointer newbs, read this: Why is the first argument of getline a pointer to pointer "char**" instead of "char*"?
main.c
#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char *line = NULL;
size_t len = 0;
ssize_t read = 0;
while (1) {
puts("enter a line");
read = getline(&line, &len, stdin);
if (read == -1)
break;
printf("line = %s", line);
printf("line length = %zu\n", read);
puts("");
}
free(line);
return 0;
}
Compile and run:
gcc -ggdb3 -O0 -std=c99 -Wall -Wextra -pedantic -o main.out main.c
./main.out
Outcome: this shows on therminal:
enter a line
Then if you type:
asdf
and press enter, this shows up:
line = asdf
line length = 5
followed by another:
enter a line
Or from a pipe to stdin:
printf 'asdf\nqwer\n' | ./main.out
gives:
enter a line
line = asdf
line length = 5
enter a line
line = qwer
line length = 5
enter a line
Tested on Ubuntu 20.04.
glibc implementation
No POSIX? Maybe you want to look at the glibc 2.23 implementation.
It resolves to getdelim
, which is a simple POSIX superset of getline
with an arbitrary line terminator.
It doubles the allocated memory whenever increase is needed, and looks thread-safe.
It requires some macro expansion, but you're unlikely to do much better.
I had to add "Current" using .NET 4.5:
HttpContext.Current.Server.ScriptTimeout = 300;
Cohesion in software engineering, as in real life, is how much the elements consisting a whole(in our case let's say a class) can be said that they actually belong together. Thus, it is a measure of how strongly related each piece of functionality expressed by the source code of a software module is.
One way of looking at cohesion in terms of OO is if the methods in the class are using any of the private attributes.
Now the discussion is bigger than this but High Cohesion (or the cohesion's best type - the functional cohesion) is when parts of a module are grouped because they all contribute to a single well-defined task of the module.
Coupling in simple words, is how much one component (again, imagine a class, although not necessarily) knows about the inner workings or inner elements of another one, i.e. how much knowledge it has of the other component.
Loose coupling is a method of interconnecting the components in a system or network so that those components, depend on each other to the least extent practically possible…
I wrote a blog post about this. It discusses all this in much detail, with examples etc. It also explains the benefits of why you should follow these principles.
You could just write it out in multiline like this,
$ cat dict.go
package main
import "fmt"
func main() {
items := map[string]interface{}{
"foo": map[string]int{
"strength": 10,
"age": 2000,
},
"bar": map[string]int{
"strength": 20,
"age": 1000,
},
}
for key, value := range items {
fmt.Println("[", key, "] has items:")
for k,v := range value.(map[string]int) {
fmt.Println("\t-->", k, ":", v)
}
}
}
And the output:
$ go run dict.go
[ foo ] has items:
--> strength : 10
--> age : 2000
[ bar ] has items:
--> strength : 20
--> age : 1000
I think this is what you want:
/grand/parent/child[@id="#grand"]
There are two types of WITH clauses:
Here is the FizzBuzz in SQL form, using a WITH common table expression (CTE).
;WITH mil AS (
SELECT TOP 1000000 ROW_NUMBER() OVER ( ORDER BY c.column_id ) [n]
FROM master.sys.all_columns as c
CROSS JOIN master.sys.all_columns as c2
)
SELECT CASE WHEN n % 3 = 0 THEN
CASE WHEN n % 5 = 0 THEN 'FizzBuzz' ELSE 'Fizz' END
WHEN n % 5 = 0 THEN 'Buzz'
ELSE CAST(n AS char(6))
END + CHAR(13)
FROM mil
Here is a select statement also using a WITH clause
SELECT * FROM orders WITH (NOLOCK) where order_id = 123
You can get some information :
Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production
Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'.
Mocks are what we are talking about here: objects pre-programmed with expectations which form a specification of the calls they are expected to receive.
Fake: We acquire or build a very lightweight implementation of the same functionality as provided by a component that the SUT depends on and instruct the SUT to use it instead of the real.
Stub : This implementation is configured to respond to calls from the SUT with the values (or exceptions) that will exercise the Untested Code (see Production Bugs on page X) within the SUT. A key indication for using a Test Stub is having Untested Code caused by the inability to control the indirect inputs of the SUT
Mock Object that implements the same interface as an object on which the SUT (System Under Test) depends. We can use a Mock Object as an observation point when we need to do Behavior Verification to avoid having an Untested Requirement (see Production Bugs on page X) caused by an inability to observe side-effects of invoking methods on the SUT.
I try to simplify by using : Mock and Stub. I use Mock when it's an object that returns a value that is set to the tested class. I use Stub to mimic an Interface or Abstract class to be tested. In fact, it doesn't really matter what you call it, they are all classes that aren't used in production, and are used as utility classes for testing.
Single line comments start with a hash symbol, everything to the right of the #
will be ignored:
# Comment Here
In PowerShell 2.0 and above multi-line block comments can be used:
<#
Multi
Line
#>
You could use block comments to embed comment text within a command:
Get-Content -Path <# configuration file #> C:\config.ini
Note: Because PowerShell supports Tab Completion you need to be careful about copying and pasting Space + TAB
before comments.
Replace 123 with number of commits your branch has diverged from origin.
git reset HEAD~123 && git reset && git checkout . && git clean -fd && git pull
Piggy backing on @MikkaS answer for Mongo Client v3.x, I just needed the async / await format, which looks slightly modified as this:
const myFunc = async () => {
// Prepping here...
// Connect
let client = await MongoClient.connect('mongodb://localhost');
let db = await client.db();
// Run the query
let cursor = await db.collection('customers').find({});
// Do whatever you want on the result.
}
Simple Insert/Select sp's work great until the row count exceeds 1 mil. I've watched tempdb file explode trying to insert/select 20 mil + rows. The simplest solution is SSIS setting the batch row size buffer to 5000 and commit size buffer to 1000.
Since the syntaxes are equivalent (in MySQL anyhow), I prefer the INSERT INTO table SET x=1, y=2
syntax, since it is easier to modify and easier to catch errors in the statement, especially when inserting lots of columns. If you have to insert 10 or 15 or more columns, it's really easy to mix something up using the (x, y) VALUES (1,2)
syntax, in my opinion.
If portability between different SQL standards is an issue, then maybe INSERT INTO table (x, y) VALUES (1,2)
would be preferred.
And if you want to insert multiple records in a single query, it doesn't seem like the INSERT INTO ... SET
syntax will work, whereas the other one will. But in most practical cases, you're looping through a set of records to do inserts anyhow, though there could be some cases where maybe constructing one large query to insert a bunch of rows into a table in one query, vs. a query for each row, might have a performance improvement. Really don't know.
The lazy-init="default"
setting on a bean only refers to what is set by the default-lazy-init
attribute of the enclosing beans element. The implicit default value of default-lazy-init
is false
.
If there is no lazy-init
attribute specified on a bean, it's always eagerly instantiated.
If, like me, you landed here with:
Here is what worked for me, utilizing one of the above answers and expanding it:
-- up
ALTER TABLE myoldtable ADD COLUMN newcolumn TEXT;
ALTER TABLE myoldtable ADD CONSTRAINT myoldtable_oldcolumn_newcolumn_key UNIQUE (oldcolumn, newcolumn);
---
ALTER TABLE myoldtable DROP CONSTRAINT myoldtable_oldcolumn_newcolumn_key;
ALTER TABLE myoldtable DROP COLUMN newcolumn;
-- down
It's stored in the process (shell) and since you've exported it, any processes that process spawns.
Doing the above doesn't store it anywhere in the filesystem like /etc/profile. You have to put it there explicitly for that to happen.
ls -l --block-size=M will give you a long format listing (needed to actually see the file size) and round file sizes up to the nearest MiB.
If you want MB (10^6 bytes) rather than MiB (2^20 bytes) units, use --block-size=MB instead.
If you don't want the M suffix attached to the file size, you can use something like --block-size=1M. Thanks Stéphane Chazelas for suggesting this.
This is described in the man page for ls; man ls and search for SIZE. It allows for units other than MB/MiB as well, and from the looks of it (I didn't try that) arbitrary block sizes as well (so you could see the file size as number of 412-byte blocks, if you want to).
Note that the --block-size parameter is a GNU extension on top of the Open Group's ls, so this may not work if you don't have a GNU userland (which most Linux installations do). The ls from GNU coreutils 8.5 does support --block-size as described above.
you can do it on terminal, either:
apachectl -M
apache2ctl -M
taken from 2daygeek
list1a=list[:5]
list1b=list[5:]
I think that what you're after is DESCRIBE
DESCRIBE table;
You can also use SHOW TABLES
SHOW TABLES;
to get a list of the tables in your database.
I did what @rayid-ali said, except I'm on a Windows 10 machine so I left out the sudo. That is, I did the following:
python3 -m pip install bs4
and it worked like a pycharm. Worked like a charm anyway.
every minute:
* * * * * /path/to/php /var/www/html/a.php
every 24hours (every midnight):
0 0 * * * /path/to/php /var/www/html/reset.php
See this reference for how crontab works: http://adminschoice.com/crontab-quick-reference, and this handy tool to build cron jobx: http://www.htmlbasix.com/crontab.shtml
I just discovered that the 1.2.3 version of Steven Levithan's date.format.js does just what I want. It allows you to supply a format string for a JavaScript date and will convert from local time to UTC. Here's the code I'm using now:
// JavaScript dates don't like hyphens!
var rectifiedDateText = dateText.replace(/-/g, "/");
var d = new Date(rectifiedDateText);
// Using a predefined mask from date.format.js.
var convertedDate = dateFormat(d, 'isoUtcDateTime');
It is not in a text field as asked but wrapping separate text elements into a view would give the desired output. This can be used if you don't want to add another library into your project just for styling a few texts.
<View style={{flexDirection: 'row'}}>
<Text style={{fontWeight: '700', marginRight: 5}}>Contact Type:</Text>
<Text>{data.type}</Text>
</View>
Would result as follows
It depends what specific .NET technologies you're using. The Mono Project provides an Apache module (mod_mono) for running ASP.NET sites, and from what I gather it works well.
Mono doesn't support all the .NET APIs, though - notably WPF (and possibly WCF too, I can't remember) - but it does provide good support for much else of the framework.
If you're starting from scratch and particularly want to target non-Windows servers, then ensuring your project works with Mono would be a good goal to aim for. However, if you need particular APIs or language features that are not supported by Mono, then you will need to use a Windows server for deployment. It's a design-time/architectural choice that should make up front.
Create Dynamic angular variables from results
angular.forEach(results, function (value, key) {
if (key != null) {
$parse(key).assign($scope, value);
}
});
ps. don't forget to pass in the $parse attribute into your controller's function