"\n" = new line
'\n' = \n
"\t" = tab
'\t' = \t
print("{0}{1}{2}".format(a, b, c))
encodeURIComponent works fine for me. we can give the url like this in ajax call.The code shown below:
$.ajax({
cache: false,
type: "POST",
url: "http://atandra.mivamerchantdev.com//mm5/json.mvc?Store_Code=ATA&Function=Module&Module_Code=thub_connector&Module_Function=THUB_Request",
data: "strChannelName=" + $('#txtupdstorename').val() + "&ServiceUrl=" + encodeURIComponent($('#txtupdserviceurl').val()),
dataType: "HTML",
success: function (data) {
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
Collapse to definitions
CTRL + M, O
Expand all outlining
CTRL + M, X
Expand or collapse everything
CTRL + M, L
This also works with other languages like TypeScript and JavaScript
rails s -e production
This will run the server with RAILS_ENV
= 'production'
.
Apart from this you have to set the assets path in production.rb
config.serve_static_assets = true
Without this your assets will not be loaded.
Here is a quick and simple solution using PowerShell:
powershell.exe -nologo -noprofile -command "& { $shell = New-Object -COM Shell.Application; $target = $shell.NameSpace('C:\extractToThisDirectory'); $zip = $shell.NameSpace('C:\extractThis.zip'); $target.CopyHere($zip.Items(), 16); }"
This uses the built-in extract functionality of the Explorer and will also show the typical extract progress window. The second parameter 16
to CopyHere
answers all questions with yes.
Python compiles the .py
and saves files as .pyc
so it can reference them in subsequent invocations.
There's no harm in deleting them, but they will save compilation time if you're doing lots of processing.
Set the "long" type of id instead of java.lang.Integer. And add getters and setters to your fields.
You can make this happen with less typing. First, change the way your push works:
git config --global push.default current
This will infer the origin my_branch
part, thus you can do:
git push -u
Which will both create the remote branch with the same name and track it.
From the code that you have provided, not knowing the language that you are programming in. The variable capital
is null. When you are trying to read the property length, the system cant as it is trying to deference a null variable. You need to define capital
.
On Windows:-
Go to File -> Settings.
And open the 'Build,Execution,Deployment'
. Then open the
Build Tools -> Gradle
Then uncheck -> Offline work on the right.
Click the OK button.
Then Rebuild the Project.
On Mac OS:-
go to Android Studio -> Preferences, and the rest is the same. OR follow steps given in the image
[
I wrote a Haskell program called splitter that does exactly this: have a read through my release blog post.
You can use the program as follows:
$ cat somefile | splitter 16224-16482
And that is all that there is to it. You will need Haskell to install it. Just:
$ cabal install splitter
And you are done. I hope that you find this program useful.
Here's a way to do it using command-line Groovy:
groovy -e 'new File(".").eachFileMatch(~/fgh.*/) {it.renameTo(it.name.replaceFirst("fgh", "jkl"))}'
z-index
is also very important. Sometimes it will work but you just won't see it. Try setting it to some very high number just to be sure. Also don't always put top: 0
but try something higher in case it's hidden somewhere (under a toolbar).
// Java 8
int vInt = Integer.parseUnsignedInt("4294967295");
System.out.println(vInt); // -1
String sInt = Integer.toUnsignedString(vInt);
System.out.println(sInt); // 4294967295
long vLong = Long.parseUnsignedLong("18446744073709551615");
System.out.println(vLong); // -1
String sLong = Long.toUnsignedString(vLong);
System.out.println(sLong); // 18446744073709551615
// Guava 18.0
int vIntGu = UnsignedInts.parseUnsignedInt(UnsignedInteger.MAX_VALUE.toString());
System.out.println(vIntGu); // -1
String sIntGu = UnsignedInts.toString(vIntGu);
System.out.println(sIntGu); // 4294967295
long vLongGu = UnsignedLongs.parseUnsignedLong("18446744073709551615");
System.out.println(vLongGu); // -1
String sLongGu = UnsignedLongs.toString(vLongGu);
System.out.println(sLongGu); // 18446744073709551615
/**
Integer - Max range
Signed: From -2,147,483,648 to 2,147,483,647, from -(2^31) to 2^31 – 1
Unsigned: From 0 to 4,294,967,295 which equals 2^32 - 1
Long - Max range
Signed: From -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, from -(2^63) to 2^63 - 1
Unsigned: From 0 to 18,446,744,073,709,551,615 which equals 2^64 – 1
*/
Each node is named uniquely and knows who it is connected to. The List of connections allows for a Node to be connected to an arbitrary number of other nodes.
public class Node {
public String name;
public List<Edge> connections;
}
Each connection is directed, has a start and an end, and is weighted.
public class Edge {
public Node start;
public Node end;
public double weight;
}
A graph is just your collection of nodes. Instead of List<Node>
consider Map<String, Node>
for fast lookup by name.
public class Graph {
List<Node> nodes;
}
Step-by-step:
use-gulp
which
uses(require
s) node_modules
like gulp
and gulp-util
.gulp-util
lib and test it locally with your use-gulp
project... gulp-util
project on github\bitbucket etc.cd use-gulp/node_modules
gulp-util
as gulp-util-dev
: git clone https://.../gulp-util.git gulp-util-dev
npm install
to ensure dependencies of gulp-util-dev
are available.gulp-util
as gulp-util-dev
. In your use-gulp
project, you can now replace: require('gulp-util')...;
call with : require('gulp-util-dev')
to test your changes you made to gulp-util-dev
No one seems to have mentioned about the negative infinity explicitly, so I think I should add it.
For negative infinity:
-math.inf
For positive infinity (just for the sake of completeness):
math.inf
You can use the $$
variable.
In the case of DSE (DataStax Cassandra & Spark) The following location needs to be added to PYTHONPATH
export PYTHONPATH=/usr/share/dse/resources/spark/python:$PYTHONPATH
Then use the dse pyspark to get the modules in path.
dse pyspark
i think the problem is that there is no data in the success-function because the request breaks up with an 401 error in your case and thus has no success.
if you use
$.ajax({
url: "https://app.asana.com/-/api/0.1/workspaces/",
type: 'GET',
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
there will be your 401 code i think (this link says so)
Verify your code with JSLint. It will usually find a ton of small errors, so the warning "JSLint may hurt your feelings" is pretty spot on. =)
I'm using:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
class Program
{
static void Main(string[] args)
{
const string DEFAULT_NAMESPACE = "http://www.something.org/schema";
var serializer = new XmlSerializer(typeof(Person), DEFAULT_NAMESPACE);
var namespaces = new XmlSerializerNamespaces();
namespaces.Add("", DEFAULT_NAMESPACE);
using (var stream = new MemoryStream())
{
var someone = new Person
{
FirstName = "Donald",
LastName = "Duck"
};
serializer.Serialize(stream, someone, namespaces);
stream.Position = 0;
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
}
}
To get the following XML:
<?xml version="1.0"?>
<Person xmlns="http://www.something.org/schema">
<FirstName>Donald</FirstName>
<LastName>Duck</LastName>
</Person>
If you don't want the namespace, just set DEFAULT_NAMESPACE to "".
console.log(` moment('2019-09-01', 'YYYY-MM-DD').isValid()? ` +moment('2019-09-01', 'YYYY-MM-DD').isValid())
console.log(` moment('2019-22-01', 'YYYY-DD-MM').isValid()? ` +moment('2019-22-01', 'YYYY-DD-MM').isValid())
console.log(` moment('2019-22-22', 'YYYY-DD-MM').isValid()? ` +moment('2019-22-22', 'YYYY-DD-MM').isValid())
console.log(` moment('undefined', 'YYYY-DD-MM').isValid()? ` +moment('undefined', 'YYYY-DD-MM').isValid())
moment('2019-09-01', 'YYYY-MM-DD').isValid()? true
moment('2019-22-01', 'YYYY-DD-MM').isValid()? true
moment('2019-22-22', 'YYYY-DD-MM').isValid()? false
moment('undefined', 'YYYY-DD-MM').isValid()? false
For Debian/Ubuntu or Fedora, you can probably use the other answers. But if you don't have files under /etc/default/docker
or /etc/sysconfig/docker
, and your system is running systemd, you may want to follow this answer by h3nrik. I am using Arch, and this works for me.
Basically, you need to configure systemd to read the new docker image location as an environment variable, and pass that environment variable into the Docker daemon execution script.
For completeness, here is h3nrick's answer:
Do you have a /lib/systemd/system/docker.service
file?
If so, edit it so that the Docker service uses the usual /etc/default/docker
as an environment file: EnvironmentFile=-/etc/default/docker
.
In the /etc/default/docker
file then add DOCKER_OPTS="-g /home/rseixas/Programs/Docker/images"
.
At the end just do a systemctl daemon-reload && systemctl restart docker
.
For further information please also have a look at the documentation.
Use set:
yourList = new ArrayList<Blog>(new LinkedHashSet<Blog>(yourList));
This will create list without duplicates and the element order will be as in original list.
Just do not forget to implement hashCode()
and equals(
) for your class Blog.
According to the documentation since Symfony 2.1 simply use this shortcut :
$user = $this->getUser();
The above is still working on Symfony 3.2 and is a shortcut for this :
$user = $this->get('security.token_storage')->getToken()->getUser();
The
security.token_storage
service was introduced in Symfony 2.6. Prior to Symfony 2.6, you had to use thegetToken()
method of thesecurity.context
service.
Example : And if you want directly the username :
$username = $this->getUser()->getUsername();
The user will be an object and the class of that object will depend on your user provider.
@user544079
Even though it is very old and irrelevant now, I am replying to help people like me! it should be like this:
<form method="post" action="mailto:$emailID?subject=$MySubject &message= $MyMessageText">
Here $emailID, $MySubject, $MyMessageText are variables which you assign from a FORM or a DATABASE Table or just you can assign values in your code itself. Alternatively you can put the code like this (normally it is not used):
<form method="post" action="mailto:[email protected]?subject=New Registration Alert &message= New Registration requires your approval">
I had the same error, but for me, it was attributed to having a database and a table that were named the same. When I added the ADO .NET Entity Object to my project, it misgenerated what I wanted in my database context file:
// Table
public virtual DbSet<OBJ> OBJs { get; set; }
which should've been:
public virtual DbSet<OBJ> OBJ { get; set; }
And
// Database?
public object OBJ { get; internal set; }
which I actually didn't really need, so I commented it out.
I was trying to pull in my table like this, in my controller, when I got my error:
protected Model1 db = new Model1();
public ActionResult Index()
{
var obj =
from p in db.OBJ
orderby p.OBJ_ID descending
select p;
return View(obj);
}
I corrected my database context and all was fine, after that.
Suppose you need only x:target/classes in your classpath. Then you just add this folder to your classpath and %IDEA%\lib\idea_rt.jar. Now it will work. That's it.
As far as I can tell, chrome doesn't work properly if you are referencing localhost (say, you're developing a site locally)
This works:
var windowObjectReference;
var strWindowFeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes";
function openRequestedPopup() {
windowObjectReference = window.open("http://www.cnn.com/", "CNN_WindowName", strWindowFeatures);
}
This does not work
var windowObjectReference;
var strWindowFeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes";
function openRequestedPopup() {
windowObjectReference = window.open("http://localhost/webappFolder/MapViewer.do", "CNN_WindowName", strWindowFeatures);
}
This also does not work, when loaded from http://localhost/webappFolder/Landing.do
var windowObjectReference;
var strWindowFeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes";
function openRequestedPopup() {
windowObjectReference = window.open("/webappFolder/MapViewer.do", "CNN_WindowName", strWindowFeatures);
}
I find most of the other answers lacking as they assume that any returned string must be the IP, but doesn't really check for it. This is my solution that I'm currently using. It will only return a valid IP or null if none is found.
public class WhatsMyIp
{
public static IPAddress PublicIp { get; private set; }
static WhatsMyIp()
{
PublicIp = GetMyIp();
}
public static IPAddress GetMyIp()
{
List<string> services = new List<string>()
{
"https://ipv4.icanhazip.com",
"https://api.ipify.org",
"https://ipinfo.io/ip",
"https://checkip.amazonaws.com",
"https://wtfismyip.com/text",
"http://icanhazip.com"
};
using (var webclient = new WebClient())
foreach (var service in services)
{
try { return IPAddress.Parse(webclient.DownloadString(service)); } catch { }
}
return null;
}
}
If you reconfigure IIS7 to use your new location, then there's no problem. Just test that the new location is working, before deleting the old location.
Change IIS7 Inetpub path
- Open %windir%\system32\inetsrv\config\applicationhost.config and search for
%SystemDrive%\inetpub\wwwroot
- Change the path.
You could also use promises in this way:
some_3secs_function(this.some_value).then(function(){
some_5secs_function(this.some_other_value).then(function(){
some_8secs_function(this.some_other_other_value);
});
});
You would have to make some_value
global in order to access it from inside the .then
Alternatively, from the outer function you could return the value the inner function would use, like so:
one(some_value).then(function(return_of_one){
two(return_of_one).then(function(return_of_two){
three(return_of_two);
});
});
Since async/await is widely available now, this is the way to accomplish the same:
async function run(){
await $('#art1').animate({'width':'1000px'},1000,'linear').promise()
await $('#art2').animate({'width':'1000px'},1000,'linear').promise()
await $('#art3').animate({'width':'1000px'},1000,'linear').promise()
}
Which is basically "promisifying" your functions (if they're not already asynchronous), and then awaiting them
This is more a workaround than a real solution. You can create a new object test_data
with another column name:
left_join("names<-"(test_data, "name"), kantrowitz, by = "name")
name gender
1 john M
2 bill either
3 madison M
4 abby either
5 zzz <NA>
It's easy to copy a folder in a batch file.
@echo off
set src_folder = c:\whatever\*.*
set dst_folder = c:\foo
xcopy /S/E/U %src_folder% %dst_folder%
And you can add that batch file to your Windows login script pretty easily (assuming you have admin rights on the machine). Just go to the "User Manager" control panel, choose properties for your user, choose profile and set a logon script.
How you get to the user manager control panel depends on which version of Windows you run. But right clicking on My Computer and choosing manage and then choosing Local users and groups works for most versions.
The only sticky bit is "when the folder is updated". This sounds like a folder watcher, which you can't do in a batch file, but you can do pretty easily with .NET.
No shadow and no rounded borders in the bar
You are using an image so the easiest solution is row your boat with the flow,
You cannot give heights manually,yes you can but make sure it gets enough space to show your full image view there
android:layout_height="wrap_content"
for SeekBar
I am no good with Photoshop but I managed to edit a background one for a test
seekbar_brown_to_show_progress.png
<SeekBar
android:splitTrack="false" // for unwanted white space in thumb
android:id="@+id/seekBar_luminosite"
android:layout_width="250dp" // use your own size
android:layout_height="wrap_content"
android:minHeight="10dp"
android:minWidth="15dp"
android:maxHeight="15dp"
android:maxWidth="15dp"
android:progress="50"
android:progressDrawable="@drawable/custom_seekbar_progress"
android:thumb="@drawable/custom_thumb" />
custom_seekbar_progress.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@android:id/background"
android:drawable="@drawable/seekbar" />
<item android:id="@android:id/progress">
<clip android:drawable="@drawable/seekbar_brown_to_show_progress" />
</item>
</layer-list>
custom_thumb.xml is same as yours
Finally android:splitTrack="false"
will remove the unwanted white space in your thumb
Let's have a look at the output :
There is no binary conversion built into the java.util.Formatter, I would advise you to either use String.replace to replace space character with zeros, as in:
String.format("%16s", Integer.toBinaryString(1)).replace(" ", "0")
Or implement your own logic to convert integers to binary representation with added left padding somewhere along the lines given in this so. Or if you really need to pass numbers to format, you can convert your binary representation to BigInteger and then format that with leading zeros, but this is very costly at runtime, as in:
String.format("%016d", new BigInteger(Integer.toBinaryString(1)))
//Perform some task and update UI immediately.
DispatchQueue.global(qos: .userInitiated).async {
// Call your function here
DispatchQueue.main.async {
// Update UI
self.tableView.reloadData()
}
}
//To call or execute function after some time
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
//Here call your function
}
//If you want to do changes in UI use this
DispatchQueue.main.async(execute: {
//Update UI
self.tableView.reloadData()
})
File myFile = new File(uri.toString());
myFile.getAbsolutePath()
should return u the correct path
EDIT
As @Tron suggested the working code is
File myFile = new File(uri.getPath());
myFile.getAbsolutePath()
try this script:
with open("data.json") as f:
data = json.load(f)
data["id"] = 134
json.dump(data, open("data.json", "w"), indent = 4)
the result is:
{
"name":"mynamme",
"id":134
}
Just the arrangement is different, You can solve the problem by converting the "data" type to a list, then arranging it as you wish, then returning it and saving the file, like that:
index_add = 0
with open("data.json") as f:
data = json.load(f)
data_li = [[k, v] for k, v in data.items()]
data_li.insert(index_add, ["id", 134])
data = {data_li[i][0]:data_li[i][1] for i in range(0, len(data_li))}
json.dump(data, open("data.json", "w"), indent = 4)
the result is:
{
"id":134,
"name":"myname"
}
you can add if condition in order not to repeat the key, just change it, like that:
index_add = 0
n_k = "id"
n_v = 134
with open("data.json") as f:
data = json.load(f)
if n_k in data:
data[n_k] = n_v
else:
data_li = [[k, v] for k, v in data.items()]
data_li.insert(index_add, [n_k, n_v])
data = {data_li[i][0]:data_li[i][1] for i in range(0, len(data_li))}
json.dump(data, open("data.json", "w"), indent = 4)
The first four functions you list will work on vectors as well, with the exception that lower_wick needs to be adapted. Something like this,
def lower_wick_vec(o, l, c):
min_oc = numpy.where(o > c, c, o)
return min_oc - l
where o, l and c are vectors. You could do it this way instead which just takes the df as input and avoid using numpy, although it will be much slower:
def lower_wick_df(df):
min_oc = df[['Open', 'Close']].min(axis=1)
return min_oc - l
The other three will work on columns or vectors just as they are. Then you can finish off with
def is_hammer(df):
lw = lower_wick_at_least_twice_real_body(df["Open"], df["Low"], df["Close"])
cl = closed_in_top_half_of_range(df["High"], df["Low"], df["Close"])
return cl & lw
Bit operators can perform set logic on boolean vectors, &
for and
, |
for or
etc. This is enough to completely vectorize the sample calculations you gave and should be relatively fast. You could probably speed up even more by temporarily working with the numpy arrays underlying the data while performing these calculations.
For the second part, I would recommend introducing a column indicating the pattern for each row and writing a family of functions which deal with each pattern. Then groupby the pattern and apply the appropriate function to each group.
If you're using autofs
then the expansion might actually be coming from /etc/auto.home
(or similar for your distro). For example, my /etc/auto.master
looks like:
/home2 auto.home --timeout 60
and /etc/auto.home
looks like:
mgalgs -rw,noquota,intr space:/space/mgalgs
In my case, I had to do the following while running with Junit5
@SpringBootTest(classes = {abc.class}) @ExtendWith(SpringExtension.class
Here abc.class was the class that was being tested
Try this:
var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));
This should return true
.
UPDATED: Added isNaN
check to handle the case commented by Julian H. Lam
Even the .png
file without transparency the error persists.
The solution was to change the .png
file to a .jpg
file.
I have made a PHP script which is designed to import large database dumps which have been generated by phpmyadmin. It's called PETMI and you can download it here [project page] [gitlab page]. It has been tested with a 1GB database.
Changing the ng-src
value is actually very simple. Like this:
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
</head>
<body>
<img ng-src="{{img_url}}">
<button ng-click="img_url = 'https://farm4.staticflickr.com/3261/2801924702_ffbdeda927_d.jpg'">Click</button>
</body>
</html>
Here is a jsFiddle of a working example: http://jsfiddle.net/Hx7B9/2/
My solution was to use a short nickname (less than 31 characters) and then write the entire name in cell 0.
Try this in your .htaccess:
.htaccess
ErrorDocument 404 http://example.com/404/
ErrorDocument 500 http://example.com/500/
# or map them to one error document:
# ErrorDocument 404 /pages/errors/error_redirect.php
# ErrorDocument 500 /pages/errors/error_redirect.php
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} ^/404/$
RewriteRule ^(.*)$ /pages/errors/404.php [L]
RewriteCond %{REQUEST_URI} ^/500/$
RewriteRule ^(.*)$ /pages/errors/500.php [L]
# or map them to one error document:
#RewriteCond %{REQUEST_URI} ^/404/$ [OR]
#RewriteCond %{REQUEST_URI} ^/500/$
#RewriteRule ^(.*)$ /pages/errors/error_redirect.php [L]
The ErrorDocument
redirects all 404s to a specific URL, all 500s to another url (replace with your domain).
The Rewrite rules map that URL to your actual 404.php script. The RewriteCond regular expressions can be made more generic if you want, but I think you have to explicitly define all ErrorDocument codes you want to override.
Local Redirect:
Change .htaccess ErrorDocument to a file that exists (must exist, or you'll get an error):
ErrorDocument 404 /pages/errors/404_redirect.php
404_redirect.php
<?php
header('Location: /404/');
exit;
?>
Redirect based on error number
Looks like you'll need to specify an ErrorDocument
line in .htaccess for every error you want to redirect (see: Apache ErrorDocument and Apache Custom Error). The .htaccess example above has multiple examples in it. You can use the following as the generic redirect script to replace 404_redirect.php above.
error_redirect.php
<?php
$error_url = $_SERVER["REDIRECT_STATUS"] . '/';
$error_path = $error_url . '.php';
if ( ! file_exists($error_path)) {
// this is the default error if a specific error page is not found
$error_url = '404/';
}
header('Location: ' . $error_url);
exit;
?>
The click handler that you are trying to trigger is most likely also attached via $(document).ready()
. What is probably happening is that you are triggering the event before the handler is attached. The solution is to use setTimeout
:
$("document").ready(function() {
setTimeout(function() {
$("ul.galleria li:first-child img").trigger('click');
},10);
});
A delay of 10ms will cause the function to run immediately after all the $(document).ready()
handlers have been called.
OR you check if the element is ready:
$("document").ready(function() {
$("ul.galleria li:first-child img").ready(function() {
$(this).click();
});
});
This might help you!!
This Dynamically changes the background just IOS does
.myBox {
width: 750px;
height: 500px;
border: rgba(0, 0, 0, 0.5) 1px solid;
background-color: #ffffff;
}
.blurBg {
width: 100%;
height: 100%;
overflow: hidden;
z-index: 0;
}
.blurBg img {
-webkit-filter: blur(50px);
margin-top: -150px;
margin-left: -150px;
width: 150%;
opacity: 0.6;
}
How can I get the item name "Mon, Tue, etc" when I already have the item value "0, 1, etc."
On some older C code (quite some time ago), I found code analogous to:
std::string weekEnumToStr(int n)
{
std::string s("unknown");
switch (n)
{
case 0: { s = "Mon"; } break;
case 1: { s = "Tue"; } break;
case 2: { s = "Wed"; } break;
case 3: { s = "Thu"; } break;
case 4: { s = "Fri"; } break;
case 5: { s = "Sat"; } break;
case 6: { s = "Sun"; } break;
}
return s;
}
Con: This establishes a "pathological dependency" between the enumeration values and the function... meaning if you change the enum you must change the function to match. I suppose this is true even for a std::map.
I vaguely remember we found a utility to generate the function code from the enum code. The enum table length had grown to several hundred ... and at some point it is maybe a sound choice to write code to write code.
Note -
in an embedded system enhancement effort, my team replaced many tables (100+?) of null-terminated-strings used to map enum int values to their text strings.
The problem with the tables was that a value out of range was often not noticed because many of these tables were gathered into one region of code / memory, such that a value out-of-range reached past the named table end(s) and returned a null-terminated-string from some subsequent table.
Using the function-with-switch statement also allowed us to add an assert in the default clause of the switch. The asserts found several more coding errors during test, and our asserts were tied into a static-ram-system-log our field techs could search.
You can do it specifying the characters you want to remove:
string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');
Alternatively, to change all characters except numbers and letters, try:
string = string.replace(/[^a-zA-Z0-9]/g, '');
Late to the party, but... why not just this.hasAttribute("name")
?
Refer This
Here I have taken Adil Malik's answer and fixed the 3 issues I identified with it.
/**
* Adds or updates a URL parameter.
*
* @param {string} url the URL to modify
* @param {string} param the name of the parameter
* @param {string} paramVal the new value for the parameter
* @return {string} the updated URL
*/
self.setParameter = function (url, param, paramVal){
// http://stackoverflow.com/a/10997390/2391566
var parts = url.split('?');
var baseUrl = parts[0];
var oldQueryString = parts[1];
var newParameters = [];
if (oldQueryString) {
var oldParameters = oldQueryString.split('&');
for (var i = 0; i < oldParameters.length; i++) {
if(oldParameters[i].split('=')[0] != param) {
newParameters.push(oldParameters[i]);
}
}
}
if (paramVal !== '' && paramVal !== null && typeof paramVal !== 'undefined') {
newParameters.push(param + '=' + encodeURI(paramVal));
}
if (newParameters.length > 0) {
return baseUrl + '?' + newParameters.join('&');
} else {
return baseUrl;
}
}
In some cases - when not so many columns - useful the WINDOW functions FIRST_VALUE() and LAST_VALUE().
SELECT
FIRST_VALUE(timestamp) over (ORDER BY timestamp ASC) as created_dt,
LAST_VALUE(timestamp) over (ORDER BY timestamp ASC) as last_update_dt,
LAST_VALUE(action) over (ORDER BY timestamp ASC) as last_action
FROM events
This query sort data only once.
It can be used for getting fisrt and last rows by some ID
SELECT DISTINCT
order_id,
FIRST_VALUE(timestamp) over (PARTITION BY order_id ORDER BY timestamp ASC) as created_dt,
LAST_VALUE(timestamp) over (PARTITION BY order_id ORDER BY timestamp ASC) as last_update_dt,
LAST_VALUE(action) over (PARTITION BY order_id ORDER BY timestamp ASC) as last_action
FROM events as x
I read all the existing answers and found that my (xUnit) tests weren't being discovered because I had removed 'unused' references and more specifically, xunit.execution.desktop
. Re-installing the xUnit package fixed the issue in my case.
Merely to add even more clarification to other good answers:
Basing on the premise that an abstraction of processing (a CPU as a quite imaginable example) is able to run an only task at the same instant,
Concurrency is a story about the very abstraction of processing: it can switch between different tasks.
Parallelism is a story about we have more than one abstractions of processing (for example our CPU has multiple cores). So it's the cause of our system's ability to do several tasks at the same time (literally). But nothing is said here about the particular abstractions of processing (are they concurrent or not).
The emphasis here is on what these stories about.
So be aware when you are reading the accepted answer:
Concurrency is when two or more tasks can start, run, and complete in overlapping time periods.
Strickly speaking, one can conclude based on that definition that parallelism presupposes concurrency per se.
You are looking for the command scandir.
$path = '/tmp';
$files = scandir($path);
Following code will remove .
and ..
from the returned array from scandir
:
$files = array_diff(scandir($path), array('.', '..'));
If you are using a git server inside a private network and are using a self-signed certificate or a certificate over an IP address ; you may also simply use the git global config to disable the ssl checks:
git config --global http.sslverify "false"
You can use the setupFiles
feature of the Jest configuration. As the documentation said that,
A list of paths to modules that run some code to configure or set up the testing environment. Each setupFile will be run once per test file. Since every test runs in its own environment, these scripts will be executed in the testing environment immediately before executing the test code itself.
npm install dotenv
dotenv that uses to access environment variable.
Create your .env
file to the root directory of your application and add this line into it:
#.env
APP_PORT=8080
Create your custom module file as its name being someModuleForTest.js and add this line into it:
// someModuleForTest.js
require("dotenv").config()
Update your jest.config.js
file like this:
module.exports = {
setupFiles: ["./someModuleForTest"]
}
You can access an environment variable within all test blocks.
test("Some test name", () => {
expect(process.env.APP_PORT).toBe("8080")
})
If you want to fix quickly, Forward Engineer again and check "Generate DROP SCHEMA" option and proceed.
I assume the database doesn't contain data, so dropping it won't affect.
Yes visual studio 2012 express has built in opengl library. the headers are in the folder C:\Program Files\Windows Kits\8.0\Include\um\gl and the lib files are in folder C:\Program Files\Windows Kits\8.0\Lib\win8\um\x86 & C:\Program Files\Windows Kits\8.0\Lib\win8\um\x64. but the problem is integrating the glut with the existing one.. i downloaded the library from http://www.xmission.com/~nate/glut/glut-3.7.6-bin.zip.. and deployed the files into .....\gl and ....\lib\win8\um\x32 and the dll to %system%/windows folders respectively.. Hope so this will solve the problem...
I had problems with using m2eclipse (i.e. it did not appear to be installed at all) but I develop a project using IAM - maven plugin for eclipse supported by Eclipse Foundation (or hosted or something like that).
I had sometimes problems as sometimes some strange error appeared for project (it couldn't move something) but simple command (run from eclipse as task or from console) + refresh (F5
) solved all problems:
mvn clean
However please note that I created project in eclipse. However I modified pom.xml
by hand.
There are a couple of ways to address your problem, however this is probably the most straightforward:
Your main
method is static, so it does not have access to instance members (isLeapYear
field and isLeapYear
method. One approach to rectify this is to make both the field and the method static as well:
static boolean isLeapYear;
/* (snip) */
public static boolean isLeapYear(int year)
{
/* (snip) */
}
Lastly, you're not actually calling your isLeapYear
method (which is why you're not seeing any results). Add this line after int year = kboard.nextInt();
:
isLeapYear(year);
That should be a start. There are some other best practices you could follow but for now just focus on getting your code to work; you can refactor later.
The basic problem while migrating from MySQL I faced was, I thought of the term database
to be same in PostgreSQL also, but it is not. So if we are going to switch the database from our application or pgAdmin
, the result would not be as expected.
As in my case, we have separate schemas (Considering PostgreSQL terminology here.) for each customer and separate admin schema. So in application, I have to switch between schemas.
For this, we can use the SET search_path
command. This does switch the current schema to the specified schema name for the current session.
example:
SET search_path = different_schema_name;
This changes the current_schema to the specified schema for the session. To change it permanently, we have to make changes in postgresql.conf
file.
I came across lot of posts searching for the same - "Mongodb Joins" and alternatives or equivalents. So my answer would help many other who are like me. This is the answer I would be looking for.
I am using Mongoose with Express framework. There is a functionality called Population
in place of joins.
As mentioned in Mongoose docs.
There are no joins in MongoDB but sometimes we still want references to documents in other collections. This is where population comes in.
This StackOverflow answer shows a simple example on how to use it.
If you are using TortoiseSVN client then you can follow the below steps
Right-click in the source directory and then click on SVN Relocate
After that, you need to change the URL to what you want, click ok, it will be taking a few seconds.
If you wanna do with a button click and not the other way. You can do it by adding location.href
to your button. Here is how I'm using
<button class="btn btn-lg btn-primary" id="submit" onclick="location.href ='/dashboard'" >Go To Dashboard</button>
The button above uses bootstrap classes for styling. Without styling, the simplest code would be
<button onclick="location.href ='/dashboard'" >Go To Dashboard</button>
The /dashboard
is my JSP page, If you are using extension too then used /dashboard.jsp
Set the Maximise property to False.
if the page have one <a>
It Works,but,many <a>
,have to use var href = $(this).attr('href');
Install nmap,
sudo apt-get install nmap
then
nmap -sP 192.168.1.*
or more commonly
nmap -sn 192.168.1.0/24
will scan the entire .1 to .254 range
This does a simple ping scan in the entire subnet to see which hosts are online.
Yup...since Java 5: http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html
This happened to me yesterday. What happened was that when I added the device Xcode included it in the wrong profile by default. This is easier to fix now that Apple has updated the provisioning portal:
Now it should work.
I wanted to post an answer that there is a case where the variable won't be found.
Cyclical imports may break the module behavior.
For example:
first.py
import second
var = 1
second.py
import first
print(first.var) # will throw an error because the order of execution happens before var gets declared.
main.py
import first
On this is example it should be obvious, but in a large code-base, this can be really confusing.
Have a look at the ReadAsset.java from API samples that come with the SDK.
try {
InputStream is = getAssets().open("read_asset.txt");
// We guarantee that the available method returns the total
// size of the asset... of course, this does mean that a single
// asset can't be more than 2 gigs.
int size = is.available();
// Read the entire asset into a local byte buffer.
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
// Convert the buffer into a string.
String text = new String(buffer);
// Finally stick the string into the text view.
TextView tv = (TextView)findViewById(R.id.text);
tv.setText(text);
} catch (IOException e) {
// Should never happen!
throw new RuntimeException(e);
}
If you don't have an array but you are trying to use your observable like an array even though it's a stream of objects, this won't work natively. I show how to fix this below assuming you only care about adding objects to the observable, not deleting them.
If you are trying to use an observable whose source is of type BehaviorSubject, change it to ReplaySubject then in your component subscribe to it like this:
this.messages$ = this.chatService.messages$.pipe(scan((acc, val) => [...acc, val], []));
<div class="message-list" *ngFor="let item of messages$ | async">
Here is a solution for those, who want to remove it from the database with Entity Framework:
prods.RemoveWhere(s => s.ID == 1);
And the extension method itself:
using System;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
namespace LivaNova.NGPDM.Client.Services.Data.Extensions
{
public static class DbSetExtensions
{
public static void RemoveWhere<TEntity>(this DbSet<TEntity> entities, Expression<Func<TEntity, bool>> predicate) where TEntity : class
{
var records = entities
.Where(predicate)
.ToList();
if (records.Count > 0)
entities.RemoveRange(records);
}
}
}
P.S. This simulates the method RemoveAll()
that's not available for DB sets of the entity framework.
There're several open-source libraries which allow console table formatting, ranging from simple (like the code samples in the answers here) to more advanced.
Judging by NuGet stats, the most popular library for formatting tables is ConsoleTable. Tables are constructed like this (from the readme file):
var table = new ConsoleTable("one", "two", "three");
table.AddRow(1, 2, 3)
.AddRow("this line should be longer", "yes it is", "oh");
Tables can be formatted using one of the predefined styles. It'll look like this:
--------------------------------------------------
| one | two | three |
--------------------------------------------------
| 1 | 2 | 3 |
--------------------------------------------------
| this line should be longer | yes it is | oh |
--------------------------------------------------
This library expects single-line cells with no formatting.
There're a couple of libraries based on ConsoleTable with slightly extended feature sets, like more line styles.
If you need more complex formatting, you can use CsConsoleFormat.† Here's a table generated from a process list (from a sample project):
new Grid { Stroke = StrokeHeader, StrokeColor = DarkGray }
.AddColumns(
new Column { Width = GridLength.Auto },
new Column { Width = GridLength.Auto, MaxWidth = 20 },
new Column { Width = GridLength.Star(1) },
new Column { Width = GridLength.Auto }
)
.AddChildren(
new Cell { Stroke = StrokeHeader, Color = White }
.AddChildren("Id"),
new Cell { Stroke = StrokeHeader, Color = White }
.AddChildren("Name"),
new Cell { Stroke = StrokeHeader, Color = White }
.AddChildren("Main Window Title"),
new Cell { Stroke = StrokeHeader, Color = White }
.AddChildren("Private Memory"),
processes.Select(process => new[] {
new Cell { Stroke = StrokeRight }
.AddChildren(process.Id),
new Cell { Stroke = StrokeRight, Color = Yellow, TextWrap = TextWrapping.NoWrap }
.AddChildren(process.ProcessName),
new Cell { Stroke = StrokeRight, Color = White, TextWrap = TextWrapping.NoWrap }
.AddChildren(process.MainWindowTitle),
new Cell { Stroke = LineThickness.None, Align = HorizontalAlignment.Right }
.AddChildren(process.PrivateMemorySize64.ToString("n0")),
})
)
The end result will look like this:
It supports any kind of table lines (several included and customizable), multi-line cells with word wrap, colors, columns growing based on content or percentage, text alignment etc.
† CsConsoleFormat was developed by me.
I don't think this is possible, but afaik the resolution of module names is up to module loaders so there might a loader implementation that does support this.
Until then, you could use an intermediate "module file" at lib/things/index.js
that just contains
export * from 'ThingA';
export * from 'ThingB';
export * from 'ThingC';
and it would allow you to do
import {ThingA, ThingB, ThingC} from 'lib/things';
With SQL Developer 4.x, the language option is to be added to ..\sqldeveloper\bin\sqldeveloper.conf
, rather than ..\sqldeveloper\bin\ide.conf
:
# ----- MODIFICATION BEGIN -----
AddVMOption -Duser.language=en
# ----- MODIFICATION END -----
Using only "native" Windows utilities, try the following, where "516" is the process ID that you want the image name for:
for /f "delims=," %a in ( 'tasklist /fi "PID eq 516" /nh /fo:csv' ) do ( echo %~a )
for /f %a in ( 'tasklist /fi "PID eq 516" ^| findstr "516"' ) do ( echo %a )
Or you could use wmic (the Windows Management Instrumentation Command-line tool) and get the full path to the executable:
wmic process where processId=516 get name
wmic process where processId=516 get ExecutablePath
Or you could download Microsoft PsTools, or specifically download just the pslist utility, and use PsList:
for /f %a in ( 'pslist 516 ^| findstr "516"' ) do ( echo %a )
There is an ordered set (possible new link) recipe for this which is referred to from the Python 2 Documentation. This runs on Py2.6 or later and 3.0 or later without any modifications. The interface is almost exactly the same as a normal set, except that initialisation should be done with a list.
OrderedSet([1, 2, 3])
This is a MutableSet, so the signature for .union
doesn't match that of set, but since it includes __or__
something similar can easily be added:
@staticmethod
def union(*sets):
union = OrderedSet()
union.union(*sets)
return union
def union(self, *sets):
for set in sets:
self |= set
In project P1 make the class public (if it isn't already). Then add a project reference (rather than a file reference, a mistake I've come across occasionally) to P2. Add a using statement in P2 at the correct place and start using the class from P1.
(To mention this: The alternative to making the class public would be to make P2 a friend to P1. This is, however, unlikely to be the answer you are after as it would have some consequences. So stick with the above suggestion.)
Use :
instead of =
see the example below that gives an error
app.post('/mews', (req, res) => {
if (isValidMew(req.body)) {
// insert into db
const mew = {
name = filter.clean(req.body.name.toString()),
content = filter.clean(req.body.content.toString()),
created: new Date()
};
That gives Syntex Error: invalid shorthand proprty initializer.
Then i replace =
with :
that's solve this error.
app.post('/mews', (req, res) => {
if (isValidMew(req.body)) {
// insert into db
const mew = {
name: filter.clean(req.body.name.toString()),
content: filter.clean(req.body.content.toString()),
created: new Date()
};
You can use Dictonary to map Assume Milk,Butter,Chesse are group A (ListA) Water,Beer,Wine are group B
Dictonary<string,List<string>>) dataMap;
dataMap.add("A",ListA);
dataMap.add("B",ListB);
At View , you can foreach Keys in dataMap and process your action
Of course. The whole idea of abstract classes is that they can contain some behaviour or data which you require all sub-classes to contain. Think of the simple example of WheeledVehicle - it should have a numWheels member variable. You want all sub classes to have this variable. Remember that abstract classes are a very useful feature when developing APIs, as they can ensure that people who extend your API won't break it.
http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.remoteendpoint.aspx
You can then call the IPEndPoint..::.Address method to retrieve the remote IPAddress, and the IPEndPoint..::.Port method to retrieve the remote port number.
More from the link (fixed up alot heh):
Socket s;
IPEndPoint remoteIpEndPoint = s.RemoteEndPoint as IPEndPoint;
IPEndPoint localIpEndPoint = s.LocalEndPoint as IPEndPoint;
if (remoteIpEndPoint != null)
{
// Using the RemoteEndPoint property.
Console.WriteLine("I am connected to " + remoteIpEndPoint.Address + "on port number " + remoteIpEndPoint.Port);
}
if (localIpEndPoint != null)
{
// Using the LocalEndPoint property.
Console.WriteLine("My local IpAddress is :" + localIpEndPoint.Address + "I am connected on port number " + localIpEndPoint.Port);
}
I found a tool "webchk” written in Python. Returns a status code for a list of urls. https://pypi.org/project/webchk/
Output looks like this:
? webchk -i ./dxieu.txt | grep '200'
http://salesforce-case-status.dxi.eu/login ... 200 OK (0.108)
https://support.dxi.eu/hc/en-gb ... 200 OK (0.389)
https://support.dxi.eu/hc/en-gb ... 200 OK (0.401)
Hope that helps!
With async actions (timers, ajax) you can override the property isDefaultPrevented
like this:
$('a').click(function(evt){
e.preventDefault();
// in async handler (ajax/timer) do these actions:
setTimeout(function(){
// override prevented flag to prevent jquery from discarding event
evt.isDefaultPrevented = function(){ return false; }
// retrigger with the exactly same event data
$(this).trigger(evt);
}, 1000);
}
This is most complete way of retriggering the event with the exactly same data.
string newString = url.Substring(18, (url.LastIndexOf(".") - 18))
event.returnValue = false
Use it when handling the event or in the function your event handler calls.
It works in Internet Explorer and Opera at least.
I've tried everything suggested here but didn't work for me. So in case I can help anyone with a similar issue, every single tutorial I've checked is not updated to work with version 4.
Here is what I've done to make it work
import React from 'react';
import App from './App';
import ReactDOM from 'react-dom';
import {
HashRouter,
Route
} from 'react-router-dom';
ReactDOM.render((
<HashRouter>
<div>
<Route path="/" render={()=><App items={temasArray}/>}/>
</div>
</HashRouter >
), document.getElementById('root'));
That's the only way I have managed to make it work without any errors or warnings.
In case you want to pass props to your component for me the easiest way is this one:
<Route path="/" render={()=><App items={temasArray}/>}/>
Here's a code implementation of @tatarize's answer, using PIXI.js. I have a viewport looking at part of a very big image (e.g. google maps style).
$canvasContainer.on('wheel', function (ev) {
var scaleDelta = 0.02;
var currentScale = imageContainer.scale.x;
var nextScale = currentScale + scaleDelta;
var offsetX = -(mousePosOnImage.x * scaleDelta);
var offsetY = -(mousePosOnImage.y * scaleDelta);
imageContainer.position.x += offsetX;
imageContainer.position.y += offsetY;
imageContainer.scale.set(nextScale);
renderer.render(stage);
});
$canvasContainer
is my html container.imageContainer
is my PIXI container that has the image in it.mousePosOnImage
is the mouse position relative to the entire image (not just the view port).Here's how I got the mouse position:
imageContainer.on('mousemove', _.bind(function(ev) {
mousePosOnImage = ev.data.getLocalPosition(imageContainer);
mousePosOnViewport.x = ev.data.originalEvent.offsetX;
mousePosOnViewport.y = ev.data.originalEvent.offsetY;
},self));
#include <iostream>
#include <sstream>
std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;
while(std::getline(ss, token, ',')) {
std::cout << token << '\n';
}
abc
def
ghi
This is just an add-on to the solution in case you want to compute not only unique values but other aggregate functions:
df.groupby(['group']).agg(['min','max','count','nunique'])
Hope you find it useful
Having trouble with a button onclick event in jsfiddle?
If so see Onclick event not firing on jsfiddle.net
It's not working since April of 2018 because Google decided to give greater control of playback to users. You just need to add &mute=1 to your URL. Autoplay Policy Changes
<iframe id="existing-iframe-example"
width="640" height="360"
src="https://www.youtube.com/embed/-SFcIUEvNOQ?autoplay=1&mute=1&enablejsapi=1"
frameborder="0"
style="border: solid 4px #37474F"
></iframe>
Update :
Audio/Video Updates in Chrome 73
Google said : Now that Progressive Web Apps (PWAs) are available on all desktop platforms, we are extending the rule that we had on mobile to desktop: autoplay with sound is now allowed for installed PWAs. Note that it only applies to pages in the scope of the web app manifest. https://developers.google.com/web/updates/2019/02/chrome-73-media-updates#autoplay-pwa
Enums created in the way you did are compiled into an object that stores both forward (name -> value)
and reverse (value -> name)
mappings. As we can observe from this chrome devtools screenshot:
Here is an example of how dual mapping works and how to cast from one to another:
enum Color{
Red, Green
}
// To Number
var greenNr: number = Color['Green'];
console.log(greenNr); // logs 1
// To String
var greenString: string = Color[Color['Green']]; // or Color[Color[1]
console.log(greenString); // logs Green
// In your example
// recieve as Color.green instead of the string green
var green: string = Color[Color.Green];
// obtain the enum number value which corresponds to the Color.green property
var color: Color = (<any>Color)[green];
console.log(color); // logs 1
Just develop a normal app and then add a couple of lines to the app's manifest file.
First you need to add the following attribute to your activity:
android:launchMode="singleTask"
Then add two categories to the intent filter :
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.HOME" />
The result could look something like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dummy.app"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.dummy.app.MainActivity"
android:launchMode="singleTask"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</activity>
</application>
</manifest>
It's that simple!
Today I found the same issue on a Error reporting app. I don't want to resort to HTML, to allow outlook to display the messages I had to do (assuming StringBuilder sb):
sb.Append(" \r\n\r\n").Append("Exception Time:" + DateTime.UtcNow.ToString());
I have just got this issue recently, and here is my solution
var labels = ["001", "002", "003", "004", "005", "006", "007"];
var data = [20, 59, 80, 81, 56, 55, 40];
for (var i = 0, len = labels.length; i < len; i++) {
background_colors.push(getRandomColor());// I use @Benjamin method here
}
var barChartData = {
labels: labels,
datasets: [{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
backgroundColor: background_colors,
data: data
}]
};
String a ="dgfa";
char [] c = a.toCharArray();
Arrays.sort(c);
return new String(c);
Note that this will not work as expected if it is a mixed case String (It'll put uppercase before lowercase). You can pass a comparator to the Sort method to change that.
You can find the last column of table and then fill the cell by looping throught it.
Sub test()
Dim lastCol As Long, i As Integer
lastCol = Range("AZ1").End(xlToLeft).Column
For i = 1 To lastCol
Cells(1, i).Value = "PHEV"
Next
End Sub
(function poll() {
setTimeout(function() {
//
var search = {}
search["ssn"] = "831-33-6049";
search["first"] = "Harve";
search["last"] = "Veum";
search["gender"] = "M";
search["street"] = "5017 Ottis Tunnel Apt. 176";
search["city"] = "Shamrock";
search["state"] = "OK";
search["zip"] = "74068";
search["lat"] = "35.9124";
search["long"] = "-96.578";
search["city_pop"] = "111";
search["job"] = "Higher education careers adviser";
search["dob"] = "1995-08-14";
search["acct_num"] = "11220423";
search["profile"] = "millenials.json";
search["transnum"] = "9999999";
search["transdate"] = $("#datepicker").val();
search["category"] = $("#category").val();
search["amt"] = $("#amt").val();
search["row_key"] = "831-33-6049_9999999";
$.ajax({
type : "POST",
headers : {
contentType : "application/json"
},
contentType : "application/json",
url : "/stream_more",
data : JSON.stringify(search),
dataType : 'json',
complete : poll,
cache : false,
timeout : 600000,
success : function(data) {
//
//alert('jax')
console.log("SUCCESS : ", data);
//$("#btn-search").prop("disabled", false);
// $('#feedback').html("");
for (var i = 0; i < data.length; i++) {
//
$('#feedback').prepend(
'<tr><td>' + data[i].ssn + '</td><td>'
+ data[i].transdate + '</td><td>'
+ data[i].category + '</td><td>'
+ data[i].amt + '</td><td>'
+ data[i].purch_prob + '</td><td>'
+ data[i].offer + '</td></tr>').html();
}
},
error : function(e) {
//alert("error" + e);
var json = "<h4>Ajax Response</h4><pre>" + e.responseText
+ "</pre>";
$('#feedback').html(json);
console.log("ERROR : ", e);
$("#btn-search").prop("disabled", false);
}
});
}, 3000);
})();
git diff master --compact-summary
Output is:
src/app/components/common/sidebar/toolbar/toolbar.component.html | 2 +-
src/app/components/common/sidebar/toolbar/toolbar.component.scss | 2 --
This is exactly what you need. Same format as when you making commit or pulling new commits from remote.
PS: That's wired that nobody answered this way.
Using the library Datejs you can accomplish this quite elegantly, with its toString
format specifiers: http://jsfiddle.net/TeRnM/1/.
var date = new Date(1324339200000);
date.toString("MMM dd"); // "Dec 20"
No. Extension methods require an instance variable (value) for an object. You can however, write a static wrapper around the ConfigurationManager
interface. If you implement the wrapper, you don't need an extension method since you can just add the method directly.
public static class ConfigurationManagerWrapper
{
public static ConfigurationSection GetSection( string name )
{
return ConfigurationManager.GetSection( name );
}
.....
public static ConfigurationSection GetWidgetSection()
{
return GetSection( "widgets" );
}
}
In MVVM (wich makes a lot of things a lot easier - you should try it) you would have two properties in your ViewModel Text
that is bound to your TextBox and you would have an ICommand
property Apply
(or similar) that is bound to the button:
<Button Command="Apply">Apply</Button>
The ICommand
interface has a Method CanExecute
that is where you return true
if (!string.IsNullOrWhiteSpace(this.Text)
. The rest is done by WPF for you (enabling/disabling, executing the actual command on click).
The linked article explains it in detail.
The easiest and most universal approach would be to just use the regex Linebreak matcher
\R
which matches Any Unicode linebreak sequence
:
Pattern NEWLINE = Pattern.compile("\\R")
String lines[] = NEWLINE.split(input)
@see https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/regex/Pattern.html
Here is a simple and more update format of getting the data:
$now = new \DateTime('now');
$month = $now->format('m');
$year = $now->format('Y');
This is a part of the android OS. Here is the actual version of the defined XML file.
simple_list_item_1:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="?android:attr/listItemFirstLineStyle"
android:paddingTop="2dip"
android:paddingBottom="3dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
simple_list_item_2:
<TwoLineListItem xmlns:android="http://schemas.android.com/apk/res/android"
android:paddingTop="2dip"
android:paddingBottom="2dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView android:id="@android:id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="?android:attr/listItemFirstLineStyle"/>
<TextView android:id="@android:id/text2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@android:id/text1"
style="?android:attr/listItemSecondLineStyle" />
</TwoLineListItem>
it's very easy, you just grant the /tmp folder as 777 permission. just type:
chmod -R 777 /tmp
My favorite method for doing this is to write it out as a batch script to combine both user variables and system variables into a single backup file like so, create an environment-backup.bat
file and put in it:
@echo off
:: RegEdit can only export into a single file at a time, so create two temporary files.
regedit /e "%CD%\environment-backup1.reg" "HKEY_CURRENT_USER\Environment"
regedit /e "%CD%\environment-backup2.reg" "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
:: Concatenate into a single file and remove temporary files.
type "%CD%\environment-backup1.reg" "%CD%\environment-backup2.reg" > environment-backup.reg
del "%CD%\environment-backup1.reg"
del "%CD%\environment-backup2.reg"
This creates environment-backup.reg
which you can use to re-import existing environment variables. This will add & override new variables, but not delete existing ones :)
update from one table to another table on id matched
UPDATE
TABLE1 t1,
TABLE2 t2
SET
t1.column_name = t2.column_name
WHERE
t1.id = t2.id;
In Swift:
override func viewDidLoad() {
super.viewDidLoad()
// We set the table view header.
let cellTableViewHeader = tableView.dequeueReusableCellWithIdentifier(TableViewController.tableViewHeaderCustomCellIdentifier) as! UITableViewCell
cellTableViewHeader.frame = CGRectMake(0, 0, self.tableView.bounds.width, self.heightCache[TableViewController.tableViewHeaderCustomCellIdentifier]!)
self.tableView.tableHeaderView = cellTableViewHeader
// We set the table view footer, just know that it will also remove extra cells from tableview.
let cellTableViewFooter = tableView.dequeueReusableCellWithIdentifier(TableViewController.tableViewFooterCustomCellIdentifier) as! UITableViewCell
cellTableViewFooter.frame = CGRectMake(0, 0, self.tableView.bounds.width, self.heightCache[TableViewController.tableViewFooterCustomCellIdentifier]!)
self.tableView.tableFooterView = cellTableViewFooter
}
Ok, based on what you said, i'm using this:
var DecimalSeparator = Number("1.2").toLocaleString().substr(1,1);
var AmountWithCommas = Amount.toLocaleString();
var arParts = String(AmountWithCommas).split(DecimalSeparator);
var intPart = arParts[0];
var decPart = (arParts.length > 1 ? arParts[1] : '');
decPart = (decPart + '00').substr(0,2);
return '£ ' + intPart + DecimalSeparator + decPart;
I'm open to improvement suggestions (i'd prefer not to include YUI just to do this :-) ) I already know I should be detecting the "." instead of just using it as the decimal separator...
You can use Bundle to get data :
Bundle extras = intent.getExtras();
String data = extras.getString("data"); // use your key
And again you can opass this data to next activity :
Intent intent = new Intent(this, next_Activity.class);
intent.putExtra("data", data);
startActivity(intent);
Use this.getClass().getCanonicalName()
to get the full class name.
Note that a package / class name ("a.b.C") is different from the path of the .class files (a/b/C.class), and that using the package name / class name to derive a path is typically bad practice. Sets of class files / packages can be in multiple different class paths, which can be directories or jar files.
I believe using --no-index
is what you're looking for:
git diff [<options>] --no-index [--] <path> <path>
as mentioned in the git manual:
This form is to compare the given two paths on the filesystem. You can omit the
--no-index
option when running the command in a working tree controlled by Git and at least one of the paths points outside the working tree, or when running the command outside a working tree controlled by Git.
Use a Bundle
. Here's an example:
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);
Bundle has put methods for lots of data types. See this
Then in your Fragment
, retrieve the data (e.g. in onCreate()
method) with:
Bundle bundle = this.getArguments();
if (bundle != null) {
int myInt = bundle.getInt(key, defaultValue);
}
Best practices :
Contrary to what you may think, the favicon can be of any size and of any image type. Follow this link for details.
Not putting a link to your favicon can slow down the page load.
In a django project, suppose the path to your favicon is :
myapp/static/icons/favicon.png
in your django templates (preferably in the base template), add this line to head of the page :
<link rel="shortcut icon" href="{% static 'icons/favicon.png' %}">
Note :
We suppose, the static settings are well configured in settings.py.
I create my own solution without label
input[type=checkbox] {_x000D_
position: relative;_x000D_
cursor: pointer;_x000D_
}_x000D_
input[type=checkbox]:before {_x000D_
content: "";_x000D_
display: block;_x000D_
position: absolute;_x000D_
width: 16px;_x000D_
height: 16px;_x000D_
top: 0;_x000D_
left: 0;_x000D_
border: 2px solid #555555;_x000D_
border-radius: 3px;_x000D_
background-color: white;_x000D_
}_x000D_
input[type=checkbox]:checked:after {_x000D_
content: "";_x000D_
display: block;_x000D_
width: 5px;_x000D_
height: 10px;_x000D_
border: solid black;_x000D_
border-width: 0 2px 2px 0;_x000D_
-webkit-transform: rotate(45deg);_x000D_
-ms-transform: rotate(45deg);_x000D_
transform: rotate(45deg);_x000D_
position: absolute;_x000D_
top: 2px;_x000D_
left: 6px;_x000D_
}
_x000D_
<input type="checkbox" name="a">_x000D_
<input type="checkbox" name="a">_x000D_
<input type="checkbox" name="a">_x000D_
<input type="checkbox" name="a">
_x000D_
input[type=checkbox] {_x000D_
position: relative;_x000D_
cursor: pointer;_x000D_
}_x000D_
input[type=checkbox]:before {_x000D_
content: "";_x000D_
display: block;_x000D_
position: absolute;_x000D_
width: 20px;_x000D_
height: 20px;_x000D_
top: 0;_x000D_
left: 0;_x000D_
background-color:#e9e9e9;_x000D_
}_x000D_
input[type=checkbox]:checked:before {_x000D_
content: "";_x000D_
display: block;_x000D_
position: absolute;_x000D_
width: 20px;_x000D_
height: 20px;_x000D_
top: 0;_x000D_
left: 0;_x000D_
background-color:#1E80EF;_x000D_
}_x000D_
input[type=checkbox]:checked:after {_x000D_
content: "";_x000D_
display: block;_x000D_
width: 5px;_x000D_
height: 10px;_x000D_
border: solid white;_x000D_
border-width: 0 2px 2px 0;_x000D_
-webkit-transform: rotate(45deg);_x000D_
-ms-transform: rotate(45deg);_x000D_
transform: rotate(45deg);_x000D_
position: absolute;_x000D_
top: 2px;_x000D_
left: 6px;_x000D_
}
_x000D_
<input type="checkbox" name="a">_x000D_
<input type="checkbox" name="a">_x000D_
<input type="checkbox" name="a">_x000D_
<input type="checkbox" name="a">
_x000D_
It's worth the buck to apply for the Apple developer program. You will be able to use ad-hoc provisioning to distribute your app to testers and test devices. You're allowed to add 100 ad-hoc provisioning devices to your developer program.
The above answers are partially correct, but with "tel://" there is only one issue. After the call has ended, it will return to the homescreen, not to our app. So better to use "telprompt://", it will return to the app.
var url:NSURL = NSURL(string: "telprompt://1234567891")!
UIApplication.sharedApplication().openURL(url)
Personally, I would use the following function:
var arrayContains = function(array, toMatch) {
var arrayAsString = array.toString();
return (arrayAsString.indexOf(','+toMatch+',') >-1);
}
The "toString()" method will always use commas to separate the values. Will only really work with primitive types.
You need a back inserter to copy into vectors:
std::copy(str.c_str(), str.c_str()+str.length(), back_inserter(data));
This might be too late for your work, but here is how I did it. I want something run everyday at 1AM - I believe this is similar to what you are doing. Here is how I did it:
CREATE EVENT event_name
ON SCHEDULE
EVERY 1 DAY
STARTS (TIMESTAMP(CURRENT_DATE) + INTERVAL 1 DAY + INTERVAL 1 HOUR)
DO
# Your awesome query
I was looking for an example that had default kwargs using type annotation:
def test_var_kwarg(a: str, b: str='B', c: str='', **kwargs) -> str:
return ' '.join([a, b, c, str(kwargs)])
example:
>>> print(test_var_kwarg('A', c='okay'))
A B okay {}
>>> d = {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', c='c', b='b', **d))
a b c {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', 'b', 'c'))
a b c {}
What Tyler Rinker says is correct:
AQ2 <- airquality
AQ2[is.na(AQ2)] <- 0
will do just this.
What you are originally doing is that you are taking from airquality
all those rows (cases) that are complete. So, all the cases that do not have any NA's in them, and keep only those.
Here is an implementation that I find very versatile:
In [1]: import pandas as pd
In [2]: df = pd.DataFrame([[0, 'the', 'quick', 'brown'],
...: [1, 'fox', 'jumps', 'over'],
...: [2, 'the', 'lazy', 'dog']],
...: columns=['c0', 'c1', 'c2', 'c3'])
In [3]: def str_join(df, sep, *cols):
...: from functools import reduce
...: return reduce(lambda x, y: x.astype(str).str.cat(y.astype(str), sep=sep),
...: [df[col] for col in cols])
...:
In [4]: df['cat'] = str_join(df, '-', 'c0', 'c1', 'c2', 'c3')
In [5]: df
Out[5]:
c0 c1 c2 c3 cat
0 0 the quick brown 0-the-quick-brown
1 1 fox jumps over 1-fox-jumps-over
2 2 the lazy dog 2-the-lazy-dog
If you are looking to style a file input element, look at open file dialog box in javascript. If you are looking to grab the files associated with a file input element, you must do something like this:
inputElement.onchange = function(event) {
var fileList = inputElement.files;
//TODO do something with fileList.
}
See this MDN article for more info on the FileList
type.
Note that the code above will only work in browsers that support the File API. For IE9 and earlier, for example, you only have access to the file name. The input element has no files
property in non-File API browsers.
What about:
#region Using Statements
using System;
using System.Xml;
#endregion
class Program {
static void Main( string[ ] args ) {
XmlDocument doc = new XmlDocument( );
//(1) the xml declaration is recommended, but not mandatory
XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration( "1.0", "UTF-8", null );
XmlElement root = doc.DocumentElement;
doc.InsertBefore( xmlDeclaration, root );
//(2) string.Empty makes cleaner code
XmlElement element1 = doc.CreateElement( string.Empty, "body", string.Empty );
doc.AppendChild( element1 );
XmlElement element2 = doc.CreateElement( string.Empty, "level1", string.Empty );
element1.AppendChild( element2 );
XmlElement element3 = doc.CreateElement( string.Empty, "level2", string.Empty );
XmlText text1 = doc.CreateTextNode( "text" );
element3.AppendChild( text1 );
element2.AppendChild( element3 );
XmlElement element4 = doc.CreateElement( string.Empty, "level2", string.Empty );
XmlText text2 = doc.CreateTextNode( "other text" );
element4.AppendChild( text2 );
element2.AppendChild( element4 );
doc.Save( "D:\\document.xml" );
}
}
(1) Does a valid XML file require an xml declaration?
(2) What is the difference between String.Empty and “” (empty string)?
The result is:
<?xml version="1.0" encoding="UTF-8"?>
<body>
<level1>
<level2>text</level2>
<level2>other text</level2>
</level1>
</body>
But I recommend you to use LINQ to XML which is simpler and more readable like here:
#region Using Statements
using System;
using System.Xml.Linq;
#endregion
class Program {
static void Main( string[ ] args ) {
XDocument doc = new XDocument( new XElement( "body",
new XElement( "level1",
new XElement( "level2", "text" ),
new XElement( "level2", "other text" ) ) ) );
doc.Save( "D:\\document.xml" );
}
}
This command is for start the development server :
npm run dev
Where this command is for the production build :
npm run build
Make sure to look and go inside the generated folder called 'dist'.
Then start push all those files to your server.
Depends what you mean by a pattern. If you're thinking Person/Company/Transaction/Product and such, then yes - there are a lot of generic database schemas already available.
If you're thinking Factory, Singleton... then no - you don't need any of these as they're too low level for DB programming.
If you're thinking database object naming, then it's under the category of conventions, not design per se.
BTW, S.Lott, one-to-many and many-to-many relationships aren't "patterns". They're the basic building blocks of the relational model.
Using paxdiablo excellent solution I wrote a little bit more sophisticated batch script, which uses drive letter as the incoming argument and checks if drive exists on a tricky (but not beauty) way:
@echo off
setlocal enableextensions enabledelayedexpansion
set chkfile=drivechk.tmp
if "%1" == "" goto :usage
set drive=%1
set drive=%drive:\=%
set drive=%drive::=%
dir %drive%:>nul 2>%chkfile%
for %%? in (%chkfile%) do (
set chksize=%%~z?
)
if %chksize% neq 0 (
more %chkfile%
del %chkfile%
goto :eof
)
del %chkfile%
for /f "tokens=3" %%a in ('dir %drive%:\') do (
set bytesfree=%%a
)
set bytesfree=%bytesfree:,=%
echo %bytesfree% byte(s) free on volume %drive%:
endlocal
goto :eof
:usage
echo.
echo usage: freedisk ^<driveletter^> (eg.: freedisk c)
note1: you may type simple letter (eg. x) or may use x: or x:\ format as drive letter in the argument
note2: script will display stderr from %chkfile% only if the size bigger than 0
note3: I saved this script as freedisk.cmd (see usage)
If older browser support is a must, so you can't go with multiple backgrounds or gradients, you're probably going to want to do something like this on a spare div
element:
#background {
position: fixed;
top: 0;
left: 0;
width: 50%;
height: 100%;
background-color: pink;
}
Example: http://jsfiddle.net/PLfLW/1704/
The solution uses an extra fixed div that fills half the screen. Since it's fixed, it will remain in position even when your users scroll. You may have to fiddle with some z-indexes later, to make sure your other elements are above the background div, but it shouldn't be too complex.
If you have issues, just make sure the rest of your content has a z-index higher than the background element and you should be good to go.
If newer browsers are your only concern, there are a couple other methods you can use:
Linear Gradient:
This is definitely the easiest solution. You can use a linear-gradient in the background property of the body for a variety of effects.
body {
height: 100%;
background: linear-gradient(90deg, #FFC0CB 50%, #00FFFF 50%);
}
This causes a hard cutoff at 50% for each color, so there isn't a "gradient" as the name implies. Try experimenting with the "50%" piece of the style to see the different effects you can achieve.
Example: http://jsfiddle.net/v14m59pq/2/
Multiple Backgrounds with background-size:
You can apply a background color to the html
element, and then apply a background-image to the body
element and use the background-size
property to set it to 50% of the page width. This results in a similar effect, though would really only be used over gradients if you happen to be using an image or two.
html {
height: 100%;
background-color: cyan;
}
body {
height: 100%;
background-image: url('http://i.imgur.com/9HMnxKs.png');
background-repeat: repeat-y;
background-size: 50% auto;
}
Example: http://jsfiddle.net/6vhshyxg/2/
EXTRA NOTE: Notice that both the html
and body
elements are set to height: 100%
in the latter examples. This is to make sure that even if your content is smaller than the page, the background will be at least the height of the user's viewport. Without the explicit height, the background effect will only go down as far as your page content. It's also just a good practice in general.
you could do:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def rgb_to_gray(img):
grayImage = np.zeros(img.shape)
R = np.array(img[:, :, 0])
G = np.array(img[:, :, 1])
B = np.array(img[:, :, 2])
R = (R *.299)
G = (G *.587)
B = (B *.114)
Avg = (R+G+B)
grayImage = img
for i in range(3):
grayImage[:,:,i] = Avg
return grayImage
image = mpimg.imread("your_image.png")
grayImage = rgb_to_gray(image)
plt.imshow(grayImage)
plt.show()
You don't necessarily have to create a Spring project. Almost all Java web applications have he same project structure. In almost every project I create, I automatically add these source folder:
src/main/webapp isn't actually a source folder. The web.xml file under src/main/webapp/WEB-INF will allow you to run your java application on any Java enabled web server (Tomcat, Jetty, etc.). I typically add the Jetty Plugin to my POM (assuming you use Maven), and launch the web app in development using mvn clean jetty:run.
That method can't return true
. That's the point of Long.MAX_VALUE
. It would be really confusing if its name were... false. Then it should be just called Long.SOME_FAIRLY_LARGE_VALUE
and have literally zero reasonable uses. Just use Android's isUserAGoat
, or you may roll your own function that always returns false
.
Note that a long
in memory takes a fixed number of bytes. From Oracle:
long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int.
As you may know from basic computer science or discrete math, there are 2^64 possible values for a long, since it is 64 bits. And as you know from discrete math or number theory or common sense, if there's only finitely many possibilities, one of them has to be the largest. That would be Long.MAX_VALUE
. So you are asking something similar to "is there an integer that's >0 and < 1?" Mathematically nonsensical.
If you actually need this for something for real then use BigInteger
class.
You reference a Linux distribution, so you need to install the readline development libraries
On Debian based platforms, like Ubuntu, you can run:
sudo apt-get install libreadline-dev
and that should install the correct headers in the correct places,.
If you use a platform with yum
, like SUSE, then the command should be:
yum install readline-devel
Take Pods-resources.sh from project path and paste in Terminal
sudo chmod a+x "Pods-resources.sh file path here"
Example Usage:
sudo chmod a+x "/Users/path/Desktop-path/My Work-path/Pods/Pods-resources.sh"
Give the buttons a value attribute and then retrieve the values using this:
$("button").click(function(){
var value=$(this).attr("value");
});
Perhaps you could try to use the of
method of the Observable
class:
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
public fetchModel(uuid: string = undefined): Observable<string> {
if(!uuid) {
return Observable.of(new TestModel()).map(o => JSON.stringify(o));
}
else {
return this.http.get("http://localhost:8080/myapp/api/model/" + uuid)
.map(res => res.text());
}
}
If you want a "editable grid" i.e. a table like structure that allows you to make any of the rows a form, use CSS that mimics the TABLE tag's layout: display:table
, display:table-row
, and display:table-cell
.
There is no need to wrap your whole table in a form and no need to create a separate form and table for each apparent row of your table.
Try this instead:
<style>
DIV.table
{
display:table;
}
FORM.tr, DIV.tr
{
display:table-row;
}
SPAN.td
{
display:table-cell;
}
</style>
...
<div class="table">
<form class="tr" method="post" action="blah.html">
<span class="td"><input type="text"/></span>
<span class="td"><input type="text"/></span>
</form>
<div class="tr">
<span class="td">(cell data)</span>
<span class="td">(cell data)</span>
</div>
...
</div>
The problem with wrapping the whole TABLE in a FORM is that any and all form elements will be sent on submit (maybe that is desired but probably not). This method allows you to define a form for each "row" and send only that row of data on submit.
The problem with wrapping a FORM tag around a TR tag (or TR around a FORM) is that it's invalid HTML. The FORM will still allow submit as usual but at this point the DOM is broken. Note: Try getting the child elements of your FORM or TR with JavaScript, it can lead to unexpected results.
Note that IE7 doesn't support these CSS table styles and IE8 will need a doctype declaration to get it into "standards" mode: (try this one or something equivalent)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Any other browser that supports display:table, display:table-row and display:table-cell should display your css data table the same as it would if you were using the TABLE, TR and TD tags. Most of them do.
Note that you can also mimic THEAD, TBODY, TFOOT by wrapping your row groups in another DIV with display: table-header-group
, table-row-group
and table-footer-group
respectively.
NOTE: The only thing you cannot do with this method is colspan.
Check out this illustration: http://jsfiddle.net/ZRQPP/
It should work fine. Don't use tuple
, list
or other special names as a variable name. It's probably what's causing your problem.
>>> l = [4,5,6]
>>> tuple(l)
(4, 5, 6)
>>> tuple = 'whoops' # Don't do this
>>> tuple(l)
TypeError: 'tuple' object is not callable
here's a in-space rotate method, by java, only for square. for non-square 2d array, you will have to create new array anyway.
private void rotateInSpace(int[][] arr) {
int z = arr.length;
for (int i = 0; i < z / 2; i++) {
for (int j = 0; j < (z / 2 + z % 2); j++) {
int x = i, y = j;
int temp = arr[x][y];
for (int k = 0; k < 4; k++) {
int temptemp = arr[y][z - x - 1];
arr[y][z - x - 1] = temp;
temp = temptemp;
int tempX = y;
y = z - x - 1;
x = tempX;
}
}
}
}
code to rotate any size 2d array by creating new array:
private int[][] rotate(int[][] arr) {
int width = arr[0].length;
int depth = arr.length;
int[][] re = new int[width][depth];
for (int i = 0; i < depth; i++) {
for (int j = 0; j < width; j++) {
re[j][depth - i - 1] = arr[i][j];
}
}
return re;
}
According to the manual, in CPython id()
is the actual memory address of the variable. If you want it in hex format, call hex()
on it.
x = 5
print hex(id(x))
this will print the memory address of x.
You can tweak the settings of the code formatting. I always turn off all extra line breaks, and then it works fine for how I format the code.
If you tweak the settings as close as you can to your preference, that should leave you minimal work whenever you use refactoring.
The task can be solved using the following piece of code, [0:28] being interval where the name is being held, while [29:34] contains the actual pid.
import os
program_pid = 0
program_name = "notepad.exe"
task_manager_lines = os.popen("tasklist").readlines()
for line in task_manager_lines:
try:
if str(line[0:28]) == program_name + (28 - len(program_name) * ' ': #so it includes the whitespaces
program_pid = int(line[29:34])
break
except:
pass
print(program_pid)
I found an issue with Diagram and Schema in SQL-Server 2016 that could be useful to the subject. I was editing diagram (related to, and with lot of tables of, the "sales" schema) and added a new table, BUT forgot to declare it schema, so it was with the default "dbo". Then when I returned to, and opened up, the schema "sales" and tried to add an existent table... Bluf! THAT Triggered exactly the same error described in that thread. I even tried the workaround (drag the table) but it didn't work. Suddenly I noticed that the schema was incorrect, I updated it, tried again, and Eureka! the problem was immediately away... Regards.
You could also write up your own user functions to handle dates in the format you choose. SQLite has a fairly simple method for writing your own user functions. For example, I wrote a few to add time durations together.
You will need to enable the feature in the Windows Features control panel:
@Yijie; Check the link maybe that's you want http://jsfiddle.net/sandeep/NCkL4/7/
EDIT:
http://jsfiddle.net/sandeep/NCkL4/8/
OR SEE THE FOLLOWING SNIPPET
#parent{_x000D_
overflow:hidden;_x000D_
background:yellow;_x000D_
position:relative;_x000D_
display:table;_x000D_
}_x000D_
.left{_x000D_
display:table-cell;_x000D_
}_x000D_
.right{_x000D_
background:red;_x000D_
width:50px;_x000D_
height:100%;_x000D_
display:table-cell;_x000D_
}_x000D_
body{_x000D_
margin:0;_x000D_
padding:0;_x000D_
}
_x000D_
<div id="parent">_x000D_
<div class="left">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>_x000D_
<div class="right">fixed</div>_x000D_
</div>
_x000D_
Use transform;
<style type="text/css">
#mydiv {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
Javascript Solution :
var left = (screen.width / 2) - (530 / 2);
var top = (screen.height / 2) - (500 / 2);
var _url = 'PopupListRepair.aspx';
window.open(_url, self, "width=530px,height=500px,status=yes,resizable=no,toolbar=no,menubar=no,left=" + left + ",top=" + top + ",scrollbars=no");
I use this function in all my js projects
You call it: hideAndResetModals("#IdModalDialog")
You define if:
function hideAndResetModals(modalID)
{
$(modalID).modal('hide');
clearValidation(modalID); //You implement it if you need it. If not, you can remote this line
$(modalID).on('hidden.bs.modal', function ()
{
$(modalID).find('form').trigger('reset');
});
}
You can't do it in PHP. PHP supports "include", but you can't even do that inside of a class definition. Not a lot of great options here.
This doesn't answer your question directly, but you may be interested in "Namespaces", a terribly ugly\syntax\hacked\on\top\of PHP OOP: http://www.php.net/manual/en/language.namespaces.rationale.php
Eclipse is a runtime environment for plugins. Virtually everything you see in Eclipse is the result of plugins installed on Eclipse, rather than Eclipse itself.
The .project
file is maintained by the core Eclipse platform, and its goal is to describe the project from a generic, plugin-independent Eclipse view. What's the project's name? what other projects in the workspace does it refer to? What are the builders that are used in order to build the project? (remember, the concept of "build" doesn't pertain specifically to Java projects, but also to other types of projects)
The .classpath
file is maintained by Eclipse's JDT feature (feature = set of plugins). JDT holds multiple such "meta" files in the project (see the .settings
directory inside the project); the .classpath
file is just one of them. Specifically, the .classpath
file contains information that the JDT feature needs in order to properly compile the project: the project's source folders (that is, what to compile); the output folders (where to compile to); and classpath entries (such as other projects in the workspace, arbitrary JAR files on the file system, and so forth).
Blindly copying such files from one machine to another may be risky. For example, if arbitrary JAR files are placed on the classpath (that is, JAR files that are located outside the workspace and are referred-to by absolute path naming), the .classpath
file is rendered non-portable and must be modified in order to be portable. There are certain best practices that can be followed to guarantee .classpath
file portability.
While there are no "official guidelines" I follow the principle of KISS and DRY. Make the overloaded constructors as simple as possible, and the simplest way is that they only call this(...). That way you only need to check and handle the parameters once and only once.
public class Simple {
public Simple() {
this(null);
}
public Simple(Resource r) {
this(r, null);
}
public Simple(Resource r1, Resource r2) {
// Guard statements, initialize resources or throw exceptions if
// the resources are wrong
if (r1 == null) {
r1 = new Resource();
}
if (r2 == null) {
r2 = new Resource();
}
// do whatever with resources
}
}
From a unit testing standpoint, it'll become easy to test the class since you can put in the resources into it. If the class has many resources (or collaborators as some OO-geeks call it), consider one of these two things:
public class SimpleParams {
Resource r1;
Resource r2;
// Imagine there are setters and getters here but I'm too lazy
// to write it out. you can make it the parameter class
// "immutable" if you don't have setters and only set the
// resources through the SimpleParams constructor
}
The constructor in Simple only either needs to split the SimpleParams
parameter:
public Simple(SimpleParams params) {
this(params.getR1(), params.getR2());
}
…or make SimpleParams
an attribute:
public Simple(Resource r1, Resource r2) {
this(new SimpleParams(r1, r2));
}
public Simple(SimpleParams params) {
this.params = params;
}
Make a factory class that initializes the resources for you, which is favorable if initializing the resources is a bit difficult:
public interface ResourceFactory {
public Resource createR1();
public Resource createR2();
}
The constructor is then done in the same manner as with the parameter class:
public Simple(ResourceFactory factory) {
this(factory.createR1(), factory.createR2());
}
Yeah... you can mix and match both ways depending on what is easier for you at the time. Parameter classes and simple factory classes are pretty much the same thing considering the Simple
class that they're used the same way.
Python 3.4 introduced the pathlib
module into the standard library, which provides an object oriented approach to handle filesystem paths. The is_dir()
and exists()
methods of a Path
object can be used to answer the question:
In [1]: from pathlib import Path
In [2]: p = Path('/usr')
In [3]: p.exists()
Out[3]: True
In [4]: p.is_dir()
Out[4]: True
Paths (and strings) can be joined together with the /
operator:
In [5]: q = p / 'bin' / 'vim'
In [6]: q
Out[6]: PosixPath('/usr/bin/vim')
In [7]: q.exists()
Out[7]: True
In [8]: q.is_dir()
Out[8]: False
Pathlib is also available on Python 2.7 via the pathlib2 module on PyPi.
I guess this will help you.
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = jsonObj.length();
for(int i=0; i<length; i++) {
JSONObject jsonObj = ja_data.getJSONObject(i);
Toast.makeText(this, jsonObj.getString("Name"), Toast.LENGTH_LONG).show();
// getting inner array Ingredients
JSONArray ja = jsonObj.getJSONArray("Ingredients");
int len = ja.length();
ArrayList<String> Ingredients_names = new ArrayList<>();
for(int j=0; j<len; j++) {
JSONObject json = ja.getJSONObject(j);
Ingredients_names.add(json.getString("name"));
}
}
There are two ways. the first is to completely refresh the page using typical form submission
//your_page.php
<?php
$saveSuccess = null;
$saveMessage = null;
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// if form has been posted process data
// you dont need the addContact function you jsut need to put it in a new array
// and it doesnt make sense in this context so jsut do it here
// then used json_decode and json_decode to read/save your json in
// saveContact()
$data = array(
'fullname' = $_POST['fullname'],
'email' => $_POST['email'],
'phone' => $_POST['phone']
);
// always return true if you save the contact data ok or false if it fails
if(($saveSuccess = saveContact($data)) {
$saveMessage = 'Your submission has been saved!';
} else {
$saveMessage = 'There was a problem saving your submission.';
}
}
?>
<!-- your other html -->
<?php if($saveSuccess !== null): ?>
<p class="flash_message"><?php echo $saveMessage ?></p>
<?php endif; ?>
<form action="your_page.php" method="post">
<fieldset>
<legend>Add New Contact</legend>
<input type="text" name="fullname" placeholder="First name and last name" required /> <br />
<input type="email" name="email" placeholder="[email protected]" required /> <br />
<input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
<input type="submit" name="submit" class="button" value="Add Contact" onClick="" />
<input type="button" name="cancel" class="button" value="Reset" />
</fieldset>
</form>
<!-- the rest of your HTML -->
The second way would be to use AJAX. to do that youll want to completely seprate the form processing into a separate file:
// process.php
$response = array();
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// if form has been posted process data
// you dont need the addContact function you jsut need to put it in a new array
// and it doesnt make sense in this context so jsut do it here
// then used json_decode and json_decode to read/save your json in
// saveContact()
$data = array(
'fullname' => $_POST['fullname'],
'email' => $_POST['email'],
'phone' => $_POST['phone']
);
// always return true if you save the contact data ok or false if it fails
$response['status'] = saveContact($data) ? 'success' : 'error';
$response['message'] = $response['status']
? 'Your submission has been saved!'
: 'There was a problem saving your submission.';
header('Content-type: application/json');
echo json_encode($response);
exit;
}
?>
And then in your html/js
<form id="add_contact" action="process.php" method="post">
<fieldset>
<legend>Add New Contact</legend>
<input type="text" name="fullname" placeholder="First name and last name" required /> <br />
<input type="email" name="email" placeholder="[email protected]" required /> <br />
<input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
<input id="add_contact_submit" type="submit" name="submit" class="button" value="Add Contact" onClick="" />
<input type="button" name="cancel" class="button" value="Reset" />
</fieldset>
</form>
<script type="text/javascript">
$(function(){
$('#add_contact_submit').click(function(e){
e.preventDefault();
$form = $(this).closest('form');
// if you need to then wrap this ajax call in conditional logic
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
dataType: 'json',
success: function(responseJson) {
$form.before("<p>"+responseJson.message+"</p>");
},
error: function() {
$form.before("<p>There was an error processing your request.</p>");
}
});
});
});
</script>
In short, services set to Automatic will start during the boot process, while services set to start as Delayed will start shortly after boot.
Starting your service Delayed improves the boot performance of your server and has security benefits which are outlined in the article Adriano linked to in the comments.
Update: "shortly after boot" is actually 2 minutes after the last "automatic" service has started, by default. This can be configured by a registry key, according to Windows Internals and other sources (3,4).
The registry keys of interest (At least in some versions of windows) are:
HKLM\SYSTEM\CurrentControlSet\services\<service name>\DelayedAutostart
will have the value 1
if delayed, 0
if not.HKLM\SYSTEM\CurrentControlSet\services\AutoStartDelay
or HKLM\SYSTEM\CurrentControlSet\Control\AutoStartDelay
(on Windows 10): decimal number of seconds to wait, may need to create this one. Applies globally to all Delayed services.You can also use within your HTML code:
ng-init="card.description = 12345"
It is not recommended by Angular, and as mentioned above you should use exclusively your controller.
But it works :)
cp -r ls -A | grep -v "Excluded_File_or_folder"
../$target_location -v
scala> val arr = Array("Hello","World")
arr: Array[java.lang.String] = Array(Hello, World)
import operator
sorted_x = sorted(x, key=operator.attrgetter('score'))
if you want to sort x in-place, you can also:
x.sort(key=operator.attrgetter('score'))
Indeed, the compiler doesn't know how to convert this anonymous type (the new { x.ServerName, x.ProcessID, x.Username }
part) to a PInfo object.
var dataset = entities.processlists
.Where(x => x.environmentID == environmentid && x.ProcessName == processname && x.RemoteIP == remoteip && x.CommandLine == commandlinepart)
.Select(x => new { x.ServerName, x.ProcessID, x.Username }).ToList();
This gives you a list of objects (of anonymous type) you can use afterwards, but you can't return that or pass that to another method.
If your PInfo object has the right properties, it can be like this :
var dataset = entities.processlists
.Where(x => x.environmentID == environmentid && x.ProcessName == processname && x.RemoteIP == remoteip && x.CommandLine == commandlinepart)
.Select(x => new PInfo
{
ServerName = x.ServerName,
ProcessID = x.ProcessID,
UserName = x.Username
}).ToList();
Assuming that PInfo has at least those three properties.
Both query allow you to fetch only the wanted columns, but using an existing type (like in the second query) allows you to send this data to other parts of your app.
This trick could be what you are looking for. It is a kind of simple operator overload.
You can then use something like the suggested Infix class like this:
a = np.random.rand(3,4)
b = np.random.rand(4,3)
x = Infix(lambda x,y: np.dot(x,y))
c = a |x| b
Just adding another way for DataFrame expanded over all columns:
for column in df.columns:
df = df[df[column]!=0]
Example:
def z_score(data,count):
threshold=3
for column in data.columns:
mean = np.mean(data[column])
std = np.std(data[column])
for i in data[column]:
zscore = (i-mean)/std
if(np.abs(zscore)>threshold):
count=count+1
data = data[data[column]!=i]
return data,count
For Windows (7), the same folder is located at,
%APPDATA%\Subversion\auth
Type in the above in the Run(Win key + R) dialog box and hit Enter,
To check the existing username open the below file as a text file,
%APPDATA%\Subversion\auth\svn.simple\xxxxxxxxxx
You define var scatterSeries = [];
, and then try to parse it as a json string at console.info(JSON.parse(scatterSeries));
which obviously fails. The variable is converted to an empty string, which causes an "unexpected end of input" error when trying to parse it.
You can maintain a Map
(for fast lookup) and List
(for order) but a LinkedHashMap
may be the simplest. You can also try a SortedMap
e.g. TreeMap
, which an have any order you specify.
On app.module.ts add the following imports. There is a list of LOCALE options here.
import es from '@angular/common/locales/es';
import { registerLocaleData } from '@angular/common';
registerLocaleData(es);
Then add the provider
@NgModule({
providers: [
{ provide: LOCALE_ID, useValue: "es-ES" }, //your locale
]
})
Use pipes in html. Here is the angular documentation for this.
{{ dateObject | date: 'medium' }}
On my system the password is 'changeit'. On blank if I hit enter then it complains about short password. Hope this helps
If you pass a String argument it will count the repetition of each word
/**
* @param string
* @return map which contain the word and value as the no of repatation
*/
public Map findDuplicateString(String str) {
String[] stringArrays = str.split(" ");
Map<String, Integer> map = new HashMap<String, Integer>();
Set<String> words = new HashSet<String>(Arrays.asList(stringArrays));
int count = 0;
for (String word : words) {
for (String temp : stringArrays) {
if (word.equals(temp)) {
++count;
}
}
map.put(word, count);
count = 0;
}
return map;
}
output:
Word1=2, word2=4, word2=1,. . .
I would recommend to use this since I have the same issue which got fixed.
$('input:text').focus(
function(){
$(this).val('');
});
(For the record and before the thread disappears on the msdn forums) You can't disable the warning (at least under VS2010) because it is on the list of the warnings that can't be disabled (so /wd4099 will not work), but what you can do instead is patch link.exe (usually C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\link.exe) to remove it from said list . Sounds like a jackhammer, i know. It works though.
For instance, if you want to remove the warning for 4099, open link.exe with an hex editor, goto line 15A0 which reads 03 10 (little endian for 4099) and replace it with FF 00 (which does not exist.)
Swift 4:
In the view controller you want to hide the navigation bar from.
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.setNavigationBarHidden(true, animated: animated)
super.viewWillAppear(animated)
}
override func viewWillDisappear(_ animated: Bool) {
self.navigationController?.setNavigationBarHidden(false, animated: animated)
super.viewWillDisappear(animated)
}
I have tried to create an image to explain this in the most simple words
1) Authentication means "Are you who you say you are?"
2) Authorization means "Should you be able to do what you are trying to do?".
This is also described in the image below.
I have tried to explain it in the best terms possible, and created an image of the same.
You can post data to a url with JavaScript & Jquery something like that:
$.post("www.abc.com/details", {
json_string: JSON.stringify({name:"John", phone number:"+410000000"})
});
I forgot that I had already an unused labs
branch. Deleting it solved my problem:
git branch -d labs
git checkout -b labs/feature
Explanation:
Each name can only be a parent branch or a normal branch, not both. Thats why the branches labs
and labs/feature
can't exists both at the same time.
The reason: Branches are stored in the file system and there you also can't have a file labs
and a directory labs
at the same level.
Try this formula:
=SUBSTITUTE(TEXT(A1/B1,"?/?"),"/",":")
Result:
A B C
33 11 3:1
25 5 5:1
6 4 3:2
Explanation:
This doesn't require any special toolkits or macros. The only downside might be that the result is considered text--not a number--so you can easily use it for further calculations.
Note: as @Robin Day suggested, increase the number of question marks (?) as desired to reduce rounding (thanks Robin!).
I think some code about the cURL solution is needed here, so I will share mine (it was written mixing several sources as the PHP Manual and comments).
It does some parallel HTTP requests (domains in $aURLs
) and print the responses once each one is completed (and stored them in $done
for other possible uses).
The code is longer than needed because the realtime print part and the excess of comments, but feel free to edit the answer to improve it:
<?php
/* Strategies to avoid output buffering, ignore the block if you don't want to print the responses before every cURL is completed */
ini_set('output_buffering', 'off'); // Turn off output buffering
ini_set('zlib.output_compression', false); // Turn off PHP output compression
//Flush (send) the output buffer and turn off output buffering
ob_end_flush(); while (@ob_end_flush());
apache_setenv('no-gzip', true); //prevent apache from buffering it for deflate/gzip
ini_set('zlib.output_compression', false);
header("Content-type: text/plain"); //Remove to use HTML
ini_set('implicit_flush', true); // Implicitly flush the buffer(s)
ob_implicit_flush(true);
header('Cache-Control: no-cache'); // recommended to prevent caching of event data.
$string=''; for($i=0;$i<1000;++$i){$string.=' ';} output($string); //Safari and Internet Explorer have an internal 1K buffer.
//Here starts the program output
function output($string){
ob_start();
echo $string;
if(ob_get_level()>0) ob_flush();
ob_end_clean(); // clears buffer and closes buffering
flush();
}
function multiprint($aCurlHandles,$print=true){
global $done;
// iterate through the handles and get your content
foreach($aCurlHandles as $url=>$ch){
if(!isset($done[$url])){ //only check for unready responses
$html = curl_multi_getcontent($ch); //get the content
if($html){
$done[$url]=$html;
if($print) output("$html".PHP_EOL);
}
}
}
};
function full_curl_multi_exec($mh, &$still_running) {
do {
$rv = curl_multi_exec($mh, $still_running); //execute the handles
} while ($rv == CURLM_CALL_MULTI_PERFORM); //CURLM_CALL_MULTI_PERFORM means you should call curl_multi_exec() again because there is still data available for processing
return $rv;
}
set_time_limit(60); //Max execution time 1 minute
$aURLs = array("http://domain/script1.php","http://domain/script2.php"); // array of URLs
$done=array(); //Responses of each URL
//Initialization
$aCurlHandles = array(); // create an array for the individual curl handles
$mh = curl_multi_init(); // init the curl Multi and returns a new cURL multi handle
foreach ($aURLs as $id=>$url) { //add the handles for each url
$ch = curl_init(); // init curl, and then setup your options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // returns the result - very important
curl_setopt($ch, CURLOPT_HEADER, 0); // no headers in the output
$aCurlHandles[$url] = $ch;
curl_multi_add_handle($mh,$ch);
}
//Process
$active = null; //the number of individual handles it is currently working with
$mrc=full_curl_multi_exec($mh, $active);
//As long as there are active connections and everything looks OK…
while($active && $mrc == CURLM_OK) { //CURLM_OK means is that there is more data available, but it hasn't arrived yet.
// Wait for activity on any curl-connection and if the network socket has some data…
if($descriptions=curl_multi_select($mh,1) != -1) {//If waiting for activity on any curl_multi connection has no failures (1 second timeout)
usleep(500); //Adjust this wait to your needs
//Process the data for as long as the system tells us to keep getting it
$mrc=full_curl_multi_exec($mh, $active);
//output("Still active processes: $active".PHP_EOL);
//Printing each response once it is ready
multiprint($aCurlHandles);
}
}
//Printing all the responses at the end
//multiprint($aCurlHandles,false);
//Finalize
foreach ($aCurlHandles as $url=>$ch) {
curl_multi_remove_handle($mh, $ch); // remove the handle (assuming you are done with it);
}
curl_multi_close($mh); // close the curl multi handler
?>
In your code where you run the stored procedure you should have something like this:
SqlCommand c = new SqlCommand(...)
//...
Add such a line of code:
c.CommandTimeout = 0;
This will wait as much time as needed for the operation to complete.
Option 1 is to use display:table-cell
. You need to unfloat the Bootstrap col-* using float:none
..
.center {
display:table-cell;
vertical-align:middle;
float:none;
}
Option 2 is display:flex
to vertical align the row with flexbox:
.row.center {
display: flex;
align-items: center;
}
http://www.bootply.com/7rAuLpMCwr
Vertical centering is very different in Bootstrap 4. See this answer for Bootstrap 4 https://stackoverflow.com/a/41464397/171456
*scanf()
family of functions return the number of values converted. So you should check to make sure sscanf()
returns 1 in your case. EOF
is returned for "input failure", which means that ssacnf()
will never return EOF
.
For sscanf()
, the function has to parse the format string, and then decode an integer. atoi()
doesn't have that overhead. Both suffer from the problem that out-of-range values result in undefined behavior.
You should use strtol()
or strtoul()
functions, which provide much better error-detection and checking. They also let you know if the whole string was consumed.
If you want an int
, you can always use strtol()
, and then check the returned value to see if it lies between INT_MIN
and INT_MAX
.
Setting colspan="0"
is support only in firefox.
In other browsers we can get around it with:
// Auto calculate table colspan if set to 0
var colCount = 0;
$("td[colspan='0']").each(function(){
colCount = 0;
$(this).parents("table").find('tr').eq(0).children().each(function(){
if ($(this).attr('colspan')){
colCount += +$(this).attr('colspan');
} else {
colCount++;
}
});
$(this).attr("colspan", colCount);
});
Short answer:
In common use, space " "
, Tab "\t"
and newline "\n"
are the difference:
string.IsNullOrWhiteSpace("\t"); //true
string.IsNullOrEmpty("\t"); //false
string.IsNullOrWhiteSpace(" "); //true
string.IsNullOrEmpty(" "); //false
string.IsNullOrWhiteSpace("\n"); //true
string.IsNullOrEmpty("\n"); //false
https://dotnetfiddle.net/4hkpKM
also see this answer about: whitespace characters
Long answer:
There are also a few other white space characters, you probably never used before
https://docs.microsoft.com/en-us/dotnet/api/system.char.iswhitespace
Here is my simple implementation:
class Node:
def __init__(self):
self.data = None
self.next = None
def __str__(self):
return "Data %s: Next -> %s"%(self.data, self.next)
class LinkedList:
def __init__(self):
self.head = Node()
self.curNode = self.head
def insertNode(self, data):
node = Node()
node.data = data
node.next = None
if self.head.data == None:
self.head = node
self.curNode = node
else:
self.curNode.next = node
self.curNode = node
def printList(self):
print self.head
l = LinkedList()
l.insertNode(1)
l.insertNode(2)
l.insertNode(34)
Output:
Data 1: Next -> Data 2: Next -> Data 34: Next -> Data 4: Next -> None
Refer to here
write query with named parameter, use simple ListPreparedStatementSetter
with all parameters in sequence. Just add below snippet to convert the query in traditional form based to available parameters,
ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(namedSql);
List<Integer> parameters = new ArrayList<Integer>();
for (A a : paramBeans)
parameters.add(a.getId());
MapSqlParameterSource parameterSource = new MapSqlParameterSource();
parameterSource.addValue("placeholder1", parameters);
// create SQL with ?'s
String sql = NamedParameterUtils.substituteNamedParameters(parsedSql, parameterSource);
return sql;
Try renaming your 'proguard-rules.txt' file to 'proguard-android.txt' and remove the reference to 'proguard-rules.txt' in your gradle file. The getDefaultProguardFile(...)
call references a different default proguard file, one provided by Google and not that in your project. So remove this as well, so that here the gradle file reads:
buildTypes {
release {
runProguard true
proguardFile 'proguard-android.txt'
}
}
In the latest Chrome as of 10/26/2018, the top-rated answer no longer works, here's how it's done:
TL;DR: check if you can read/write to /dev/tty
. If no and you have used su
to open the shell, check if you have used it correctly.
I was facing the same problem but on Linux and I have found the issue. I don't have my credentials stored so I always input them on prompt:
Username for 'https://github.com': foo
Password for 'https://[email protected]':
The way how git handles http(s) connections is using /usr/lib/git-core/git-remote-https
you can see strace here:
stat("/usr/lib/git-core/git-remote-https", {st_mode=S_IFREG|0755, st_size=1366784, ...}) = 0
pipe([9, 10]) = 0
rt_sigprocmask(SIG_SETMASK, ~[RTMIN RT_1], [], 8) = 0
clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f65398bb350) = 18177
rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0
close(10) = 0
read(9, "", 8) = 0
close(9) = 0
close(5) = 0
close(8) = 0
dup(7) = 5
fcntl(5, F_GETFL) = 0 (flags O_RDONLY)
write(6, "capabilities\n", 13) = 13
fstat(5, {st_mode=S_IFIFO|0600, st_size=0, ...}) = 0
read(5, "fetch\noption\npush\ncheck-connecti"..., 4096) = 38
write(6, "option progress true\n", 21) = 21
read(5, "ok\n", 4096) = 3
write(6, "option verbosity 1\n", 19) = 19
read(5, "ok\n", 4096) = 3
stat(".git/packed-refs", {st_mode=S_IFREG|0664, st_size=675, ...}) = 0
lstat(".git/objects/10/52401742a2e9a3e8bf068b115c3818180bf19e", {st_mode=S_IFREG|0444, st_size=179, ...}) = 0
lstat(".git/objects/4e/35fa16cf8f2676600f56e9ba78cf730adc706e", {st_mode=S_IFREG|0444, st_size=178, ...}) = 0
dup(7) = 8
fcntl(8, F_GETFL) = 0 (flags O_RDONLY)
close(8) = 0
write(6, "list for-push\n", 14) = 14
read(5, fatal: could not read Username for 'https://github.com': No such device or address
"", 4096) = 0
--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=18177, si_uid=1000, si_status=128, si_utime=6, si_stime=2} ---
exit_group(128) = ?
+++ exited with 128 +++
So I tried to call it directly:
echo "list for-push" | strace /usr/lib/git-core/git-remote-https my
and the result:
poll([{fd=3, events=POLLIN|POLLPRI|POLLRDNORM|POLLRDBAND}], 1, 0) = 1 ([{fd=3, revents=POLLIN|POLLRDNORM}])
recvfrom(3, "\27\3\3\1\32", 5, 0, NULL, NULL) = 5
recvfrom(3, "\307|4Q\21\306\334\244o\237-\230\255\336\25\215D\257\227\274\r\330\314U\5\17\217T\274\262M\223"..., 282, 0, NULL, NULL) = 282
openat(AT_FDCWD, "/dev/tty", O_RDONLY) = -1 ENXIO (No such device or address)
openat(AT_FDCWD, "/usr/share/locale/locale.alias", O_RDONLY|O_CLOEXEC) = 4
fstat(4, {st_mode=S_IFREG|0644, st_size=2995, ...}) = 0
read(4, "# Locale name alias data base.\n#"..., 4096) = 2995
read(4, "", 4096) = 0
close(4) = 0
openat(AT_FDCWD, "/usr/share/locale/en_US/LC_MESSAGES/libc.mo", O_RDONLY) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/usr/share/locale/en/LC_MESSAGES/libc.mo", O_RDONLY) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/usr/share/locale-langpack/en_US/LC_MESSAGES/libc.mo", O_RDONLY) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/usr/share/locale-langpack/en/LC_MESSAGES/libc.mo", O_RDONLY) = -1 ENOENT (No such file or directory)
write(2, "fatal: could not read Username f"..., 83fatal: could not read Username for 'https://github.com': No such device or address
) = 83
exit_group(128) = ?
+++ exited with 128 +++
And here it came to me:
openat(AT_FDCWD, "/dev/tty", O_RDONLY) = -1 ENXIO (No such device or address)
...
write(2, "fatal: could not read Username f"..., 83fatal: could not read Username for 'https://github.com': No such device or address
) = 83
git-remote-https
tries to read credentials via /dev/tty
so I tested if it works:
$ echo ahoj > /dev/tty
bash: /dev/tty: No such device or address
But in another terminal:
# echo ahoj > /dev/tty
ahoj
I knew I switched to this user using su
so I exited the shell to see how and found out I used command su danman -
so I tested it again:
~# su danman -
bash: cannot set terminal process group (-1): Inappropriate ioctl for device
bash: no job control in this shell
/root$ echo ahoj > /dev/tty
bash: /dev/tty: No such device or address
I probably ignored the message and continued working but this was the reason.
When I switched using the correct su - danman
everything worked fine:
~# su - danman
danman@speedy:~$ echo ahoj > /dev/tty
ahoj
After this, git started working correctly
In addition to the other answer, I would like to point out that this reasoning is also known as the De Morgan's law. It's actually more about mathematics than programming, but it is so fundamental that every programmer should know about it.
Your problem started like this:
enabled = A and B
disabled = not ( A and B )
So far so good, but you went one step further and tried to remove the braces.
And that's a little tricky, because you have to replace the and
/&&
with an or
/||
.
not ( A and B ) = not(A) OR not(B)
Or in a more mathematical notation:
I always keep this law in mind whenever I simplify conditions or work with probabilities.
Try this style instead, it modifies the template itself. In there you can change everything you need to transparent:
<Style TargetType="{x:Type TabItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">
<Grid>
<Border Name="Border" Margin="0,0,0,0" Background="Transparent"
BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="5">
<ContentPresenter x:Name="ContentSite" VerticalAlignment="Center"
HorizontalAlignment="Center"
ContentSource="Header" Margin="12,2,12,2"
RecognizesAccessKey="True">
<ContentPresenter.LayoutTransform>
<RotateTransform Angle="270" />
</ContentPresenter.LayoutTransform>
</ContentPresenter>
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Panel.ZIndex" Value="100" />
<Setter TargetName="Border" Property="Background" Value="Red" />
<Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Border" Property="Background" Value="DarkRed" />
<Setter TargetName="Border" Property="BorderBrush" Value="Black" />
<Setter Property="Foreground" Value="DarkGray" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
What about
string s = "Hello Marco !";
s = s.Substring(0, s.Length - 2);