Pickle uses different protocols
to convert your data to a binary stream.
In python 2 there are 3 different protocols (0
, 1
, 2
) and the default is 0
.
In python 3 there are 5 different protocols (0
, 1
, 2
, 3
, 4
) and the default is 3
.
You must specify in python 3 a protocol lower than 3
in order to be able to load the data in python 2. You can specify the protocol
parameter when invoking pickle.dump
.
Looks like it could be throwing the error on the empty data row, have you tried to just make sure itemDate isn't empty before you run the CDate() function? I think this might be your problem.
If all you need to know is whether a decimal point exists in a variable then this will get the job done...
function containsDecimal( $value ) {
if ( strpos( $value, "." ) !== false ) {
return true;
}
return false;
}
This isn't a very elegant solution but it works with strings and floats.
Make sure to use !== and not != in the strpos test or you will get incorrect results.
Object-Oriented Programming is built with the understanding that the scope of variables is closely exclusive to the class object that encapsulates those variables.
The problem with creating "global variables" is that it's not industry standard for Java. It's not industry standard because it allows multiple classes to manipulate data asyncronized, if you're running a multi-threaded application, this gets a little more complicated and dangerous in terms of thread-safety. There are various other reasons why using global variables are ineffective, but if you want to avoid that, I suggest you resort to Aspect-Oriented Programming.
Aspect-Oriented Programming negates this problem by putting the parent class in charge of the scope through something called "advices", which adds additional behavior to the code without actually modifying it. It offers solutions to cross-cutting concerns, or global variable usage.
Spring is a Java framework that utilizes AOP, and while it is traditionally used for web-applications, the core application can be used universally throughout the Java framework (8.0 included). This might be a direction you want to explore more.
Double check the fields in the relationship the foreign key is defined for. SQL Server Management Studio may not have had the fields you wanted selected when you defined the relationship. This has burned me in the past.
Assume that you have multiple properties you want to convert.
public class OrigType{
public string Prop1A {get;set;}
public string Prop1B {get;set;}
}
public class TargetType{
public string Prop2A {get;set;}
public string Prop2B {get;set;}
}
var list1 = new List<OrigType>();
var list2 = new List<TargetType>();
list1.ConvertAll(x => new OrigType { Prop2A = x.Prop1A, Prop2B = x.Prop1B })
There is all you need:
expected bytes, not str
The leading b
makes your string binary.
What version of Python do you use? 2.x or 3.x?
Edit: See http://docs.python.org/release/3.0.1/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit for the gory details of strings in Python 3.x
I favor the dplyr approach.
group_by(id)
followed by either
filter(row_number()==1)
orslice(1)
orslice_head(1)
#(dplyr => 1.0)top_n(n = -1)
top_n()
internally uses the rank function.
Negative selects from the bottom of rank.In some instances arranging the ids after the group_by can be necessary.
library(dplyr)
# using filter(), top_n() or slice()
m1 <-
test %>%
group_by(id) %>%
filter(row_number()==1)
m2 <-
test %>%
group_by(id) %>%
slice(1)
m3 <-
test %>%
group_by(id) %>%
top_n(n = -1)
All three methods return the same result
# A tibble: 5 x 2
# Groups: id [5]
id string
<int> <fct>
1 1 A
2 2 B
3 3 C
4 4 D
5 5 E
Redirect aspx :
<iframe>
<script runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location","http://www.avsapansiyonlar.com/altinkum-tatil-konaklari.aspx");
}
</script>
</iframe>
You can use Newtonsoft library and use it as follows
using Newtonsoft.Json;
public class jb
{
public DateTime Date { set; get; }
public string Artist { set; get; }
public int Year { set; get; }
public string album { set; get; }
}
var jsonObject = new jb();
jsonObject.Date = DateTime.Now;
jsonObject.Album = "Me Against The World";
jsonObject.Year = 1995;
jsonObject.Artist = "2Pac";
System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(jsonObject );
NuGet references
Assume the -Project_A (produces project_a.dll) -Project_B (produces project_b.dll) and Project_B references to Project_A by NuGet packages then just copy project_a.dll , project_a.pdb to the folder Project_B/Packages. In effect that should be copied to the /bin.
Now debug Project_A. When code reaches the part where you need to call dll's method or events etc while debugging, press F11 to step into the dll's code.
File extensions do not have any bearing or impact on the content of the file. You can hold YAML content in files with any extension: .yml
, .yaml
or indeed anything else.
The (rather sparse) YAML FAQ recommends that you use .yaml
in preference to .yml
, but for historic reasons many Windows programmers are still scared of using extensions with more than three characters and so opt to use .yml
instead.
So, what really matters is what is inside the file, rather than what its extension is.
mail [-s subject] [-c ccaddress] [-b bccaddress] toaddress
-c and -b are optional.
-s : Specify subject;if subject contains spaces, use quotes.
-c : Send carbon copies to list of users seperated by comma.
-b : Send blind carbon copies to list of users seperated by comma.
Hope my answer clarifies your doubt.
The equation of a line is:
f(x) = A*x + b = y
For a segment, it is exactly the same, except that x is included on an interval I.
If you have two segments, defined as follow:
Segment1 = {(X1, Y1), (X2, Y2)}
Segment2 = {(X3, Y3), (X4, Y4)}
The abcisse Xa of the potential point of intersection (Xa,Ya) must be contained in both interval I1 and I2, defined as follow :
I1 = [min(X1,X2), max(X1,X2)]
I2 = [min(X3,X4), max(X3,X4)]
And we could say that Xa is included into :
Ia = [max( min(X1,X2), min(X3,X4) ),
min( max(X1,X2), max(X3,X4) )]
Now, we need to check that this interval Ia exists :
if (max(X1,X2) < min(X3,X4)):
return False # There is no mutual abcisses
So, we have two line formula, and a mutual interval. Your line formulas are:
f1(x) = A1*x + b1 = y
f2(x) = A2*x + b2 = y
As we got two points by segment, we are able to determine A1, A2, b1 and b2:
A1 = (Y1-Y2)/(X1-X2) # Pay attention to not dividing by zero
A2 = (Y3-Y4)/(X3-X4) # Pay attention to not dividing by zero
b1 = Y1-A1*X1 = Y2-A1*X2
b2 = Y3-A2*X3 = Y4-A2*X4
If the segments are parallel, then A1 == A2 :
if (A1 == A2):
return False # Parallel segments
A point (Xa,Ya) standing on both line must verify both formulas f1 and f2:
Ya = A1 * Xa + b1
Ya = A2 * Xa + b2
A1 * Xa + b1 = A2 * Xa + b2
Xa = (b2 - b1) / (A1 - A2) # Once again, pay attention to not dividing by zero
The last thing to do is check that Xa is included into Ia:
if ( (Xa < max( min(X1,X2), min(X3,X4) )) or
(Xa > min( max(X1,X2), max(X3,X4) )) ):
return False # intersection is out of bound
else:
return True
In addition to this, you may check at startup that two of the four provided points are not equals to avoid all that testing.
You are looking for a simple code, like this:
List<string> tagList = new List<string>(new[]
{
"A"
,"B"
,"C"
,"D"
,"E"
});
Today I find use parseInt()
is also a good and clean practice. A onChange(e)
example is below.
onChange(e){
this.setState({[e.target.id]: parseInt(e.target.value) ? parseInt(e.target.value) : ''})
}
parseInt()
would return NaN
if the parameter is not a number.parseInt('12a')
would return 12.Another point of view
First, you can declare an anonymous function:
var foo = function(msg){
alert(msg);
}
Then you call it:
foo ('Few');
Because foo = function(msg){alert(msg);} so you can replace foo as:
function(msg){
alert(msg);
} ('Few');
But you should wrap your entire anonymous function inside pair of braces to avoid syntax error of declaring function when parsing. Then we have,
(function(msg){
alert(msg);
}) ('Few');
By this way, It's easy understand for me.
A quick and easy Tidyverse solution to get a NA
count for all columns is to use summarise_all()
which I think makes a much easier to read solution than using purrr
or sapply
library(tidyverse)
# Example data
df <- tibble(col1 = c(1, 2, 3, NA),
col2 = c(NA, NA, "a", "b"))
df %>% summarise_all(~ sum(is.na(.)))
#> # A tibble: 1 x 2
#> col1 col2
#> <int> <int>
#> 1 1 2
List<Book> books_2 = new List<Book>(books_2.ToArray());
That should do exactly what you want. Demonstrated here.
By using exploits or on badly configured servers it could be possible to download your PHP source. You could however either obfuscate and/or encrypt your code (using Zend Guard, Ioncube or a similar app) if you want to make sure your source will not be readable (to be accurate, obfuscation by itself could be reversed given enough time/resources, but I haven't found an IonCube or Zend Guard decryptor yet...).
You cannot select on specific values (or types of values). You'd either make a reverse index (map numbers back to (lists of) keys) or you have to loop through all values every time.
If you are processing numbers in arbitrary order anyway, you may as well loop through all items:
for key, value in inputdict.items():
# do something with value
inputdict[key] = newvalue
otherwise I'd go with the reverse index:
from collections import defaultdict
reverse = defaultdict(list)
for key, value in inputdict.items():
reverse[value].append(key)
Now you can look up keys by value:
for key in reverse[value]:
inputdict[key] = newvalue
mv tobecopied/tobeexcluded .
cp -r tobecopied dest/
mv tobeexcluded tobecopied/
“--single-branch” switch is your answer, but it only works if you have git version 1.8.X onwards, first check
#git --version
If you already have git version 1.8.X installed then simply use "-b branch and --single branch" to clone a single branch
#git clone -b branch --single-branch git://github/repository.git
By default in Ubuntu 12.04/12.10/13.10 and Debian 7 the default git installation is for version 1.7.x only, where --single-branch is an unknown switch. In that case you need to install newer git first from a non-default ppa as below.
sudo add-apt-repository ppa:pdoes/ppa
sudo apt-get update
sudo apt-get install git
git --version
Once 1.8.X is installed now simply do:
git clone -b branch --single-branch git://github/repository.git
Git will now only download a single branch from the server.
You may use the ==
operator to compare unicode objects for equality.
>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>>
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>>
But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode
object to a str
object, like so:
>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False
See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.
Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.
I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."
Simple and better solution : %WINDIR%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe MyProject.sln I make a bat file like this %WINDIR%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe D:\GESTION-SOMECOPA\GestionCommercial\GestionCommercial.sln pause
Then I can see all errors and correct them. Because when you change the folder name (without spaces as seen above) you will have another problems. Visual Studio 2015 works fine after this.
String test = "HELLO HOW ARE YOU";
string s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(test);
The above code wont work .....
so put the below code by convert to lower then apply the function
String test = "HELLO HOW ARE YOU";
string s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(test.ToLower());
Your MyComponentComponent
should be in MyComponentModule
.
And in MyComponentModule
, you should place the MyComponentComponent
inside the "exports".
Something like this, see code below.
@NgModule({
imports: [],
exports: [MyComponentComponent],
declarations: [MyComponentComponent],
providers: [],
})
export class MyComponentModule {
}
and place the MyComponentModule
in the imports
in app.module.ts
like this (see code below).
import { MyComponentModule } from 'your/file/path';
@NgModule({
imports: [MyComponentModule]
declarations: [AppComponent],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
After doing so, the selector of your component can now be recognized by the app.
You can learn more about it here: https://angular-2-training-book.rangle.io/handout/modules/feature-modules.html
Cheers!
Your best bet would be using the RFC defined mime-type audio/mpeg
.
Following query working for me
when i have set default value of column 'NULL' then
select * from table where column IS NOT NULL
and when i have set default value nothing then
select * from table where column <>''
I combined points from several comments and answers:
find . -maxdepth 1 -type d -name .git -execdir git pull \;
select InitialPayment * MonthlyRate as MultiplyingCalculation, InitialPayment - MonthlyRate as SubtractingCalculation from Payment
Here is how i fixed it.
it will reinstall your pip within the environment and uninstall the previous version automatically.
now boom!! install whatever you like
Hope, this would be of some help.
$('input[type=checkbox]').change(function () {
if ($(this).prop("checked")) {
//do the stuff that you would do when 'checked'
return;
}
//Here do the stuff you want to do when 'unchecked'
});
In C++11 and beyond, you can use the back
member function:
char ch = myStr.back();
In C++03, std::string::back
is not available due to an oversight, but you can get around this by dereferencing the reverse_iterator
you get back from rbegin
:
char ch = *myStr.rbegin();
In both cases, be careful to make sure the string actually has at least one character in it! Otherwise, you'll get undefined behavior, which is a Bad Thing.
Hope this helps!
A variation when using xpath in Java using count():
int numberofbodies = Integer.parseInt((String) xPath.evaluate("count(/html/body)", doc));
if( numberofbodies==0) {
// body node missing
}
Script snip below creates a pause sub that displayes the pause text in a string and waits for the Enter key. z can be anything. Great if multilple user intervention required pauses are needed. I just keep it in my standard script template.
Pause("Press Enter to continue")
Sub Pause(strPause)
WScript.Echo (strPause)
z = WScript.StdIn.Read(1)
End Sub
You could try "Clean Tomcat Work Directory" or simply "Clean..". This supposed to discard all published state and republish from scratch.
It sounds like your table has no key. You should be able to simply try the INSERT
: if it’s a duplicate then the key constraint will bite and the INSERT
will fail. No worries: you just need to ensure the application doesn't see/ignores the error. When you say 'primary key' you presumably mean IDENTITY
value. That's all very well but you also need a key constraint (e.g. UNIQUE
) on your natural key.
Also, I wonder whether your procedure is doing too much. Consider having separate procedures for 'create' and 'read' actions respectively.
In general, synchronized
methods are used to protect access to resources that are accessed concurrently. When a resource that is being accessed concurrently belongs to each instance of your class, you use a synchronized
instance method; when the resource belongs to all instances (i.e. when it is in a static
variable) then you use a synchronized static
method to access it.
For example, you could make a static
factory method that keeps a "registry" of all objects that it has produced. A natural place for such registry would be a static
collection. If your factory is used from multiple threads, you need to make the factory method synchronized
(or have a synchronized
block inside the method) to protect access to the shared static
collection.
Note that using synchronized
without a specific lock object is generally not the safest choice when you are building a library to be used in code written by others. This is because malicious code could synchronize on your object or a class to block your own methods from executing. To protect your code against this, create a private "lock" object, instance or static, and synchronize on that object instead.
# Initialize using Parent
#
class MySubClass(MySuperClass):
def __init__(self):
MySuperClass.__init__(self)
Or, even better, the use of Python's built-in function, super()
(see the Python 2/Python 3 documentation for it) may be a slightly better method of calling the parent for initialization:
# Better initialize using Parent (less redundant).
#
class MySubClassBetter(MySuperClass):
def __init__(self):
super(MySubClassBetter, self).__init__()
Or, same exact thing as just above, except using the zero argument form of super()
, which only works inside a class definition:
class MySubClassBetter(MySuperClass):
def __init__(self):
super().__init__()
You should look here: https://stackoverflow.com/questions/159025/jquery-grid-recommendations
Update
The link above takes to a question that was closed and then deleted. Here are the original suggestions that were on the most voted answer:
This works:
public static void AddValue(string key, string value)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings.Add(key, value);
config.Save(ConfigurationSaveMode.Minimal);
}
Set LDFLAGS and CFLAGS when you run make:
$ LDFLAGS="-L/home/me/local/lib" CFLAGS="-I/home/me/local/include" make
If you don't want to do that a gazillion times, export these in your .bashrc (or your shell equivalent). Also set LD_LIBRARY_PATH to include /home/me/local/lib:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/me/local/lib
One liner!?
elm = ([i for i in mylist if i['name'] == 'Tom'] or [None])[0]
I had the same error. In my case I am using Netbeans 7.1.2, I am posting this because maybe someone end up here same as I did.
I tried to configure the proxy options from the GUI, but the documentation says that maven doesn't read those. So I checked the NetBeans FAQ here :
What mainly you have to do is create (if it does not exist) a settings.xml under
user.home/.m2/settings.xml
if you don't have it you can copy from
netbeans.home/java/maven/conf/settings.xml
then uncomment if you already have it otherwise just fill this section:
<proxies>
<proxy>
<active>true</active>
<host>myproxy.host.net</host>
<port>80</port>
</proxy>
</proxies>
you have to check your proxy configuration and replace it there
In httpd.conf
on /Applications/MAMP/conf/apache
, find:
<Directory />
Options Indexes FollowSymLinks
AllowOverride None
</Directory>
Replace None
with All
.
Restart MAMP servers.
I think init_js should use declare instead of local!
function scan3() {
declare -n outvar=$1 # -n makes it a nameref.
local nl=$'\x0a'
outvar="output${nl}${nl}" # two total. quotes preserve newlines
}
I have came across the very-very-same problem.
In short:
I have made a test with ALL possible (sane) combinations of the following:
Resources/public/css
) with the CSS and a "private" directory (as Resources/assets/css
).This gave me a total of 14 combinations on the same twig, and this route was launched from
thus giving 14 x 3 = 42 tests.
Additionally, all this has been tested working in a subdirectory, so there is no way to fool by giving absolute URLs because they would simply not work.
The tests were two unnamed images and then divs named from 'a' to 'f' for the CSS built FROM the public folder and named 'g to 'l' for the ones built from the internal path.
I observed the following:
Only 3 of the 14 tests were shown adequately on the three URLs. And NONE was from the "internal" folder (Resources/assets). It was a pre-requisite to have the spare CSS PUBLIC and then build with assetic FROM there.
These are the results:
Result launched with /app_dev.php/
Result launched with /app.php/
Result launched with /
So... ONLY - The second image - Div B - Div C are the allowed syntaxes.
Here there is the TWIG code:
<html>
<head>
{% stylesheets 'bundles/commondirty/css_original/container.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{# First Row: ABCDEF #}
<link href="{{ '../bundles/commondirty/css_original/a.css' }}" rel="stylesheet" type="text/css" />
<link href="{{ asset( 'bundles/commondirty/css_original/b.css' ) }}" rel="stylesheet" type="text/css" />
{% stylesheets 'bundles/commondirty/css_original/c.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets 'bundles/commondirty/css_original/d.css' %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '@CommonDirtyBundle/Resources/public/css_original/e.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '@CommonDirtyBundle/Resources/public/css_original/f.css' %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{# First Row: GHIJKL #}
<link href="{{ '../../src/Common/DirtyBundle/Resources/assets/css/g.css' }}" rel="stylesheet" type="text/css" />
<link href="{{ asset( '../src/Common/DirtyBundle/Resources/assets/css/h.css' ) }}" rel="stylesheet" type="text/css" />
{% stylesheets '../src/Common/DirtyBundle/Resources/assets/css/i.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '../src/Common/DirtyBundle/Resources/assets/css/j.css' %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '@CommonDirtyBundle/Resources/assets/css/k.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '@CommonDirtyBundle/Resources/assets/css/l.css' %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
</head>
<body>
<div class="container">
<p>
<img alt="Devil" src="../bundles/commondirty/images/devil.png">
<img alt="Devil" src="{{ asset('bundles/commondirty/images/devil.png') }}">
</p>
<p>
<div class="a">
A
</div>
<div class="b">
B
</div>
<div class="c">
C
</div>
<div class="d">
D
</div>
<div class="e">
E
</div>
<div class="f">
F
</div>
</p>
<p>
<div class="g">
G
</div>
<div class="h">
H
</div>
<div class="i">
I
</div>
<div class="j">
J
</div>
<div class="k">
K
</div>
<div class="l">
L
</div>
</p>
</div>
</body>
</html>
The container.css:
div.container
{
border: 1px solid red;
padding: 0px;
}
div.container img, div.container div
{
border: 1px solid green;
padding: 5px;
margin: 5px;
width: 64px;
height: 64px;
display: inline-block;
vertical-align: top;
}
And a.css, b.css, c.css, etc: all identical, just changing the color and the CSS selector.
.a
{
background: red url('../images/devil.png');
}
The "directories" structure is:
Directories
All this came, because I did not want the individual original files exposed to the public, specially if I wanted to play with "less" filter or "sass" or similar... I did not want my "originals" published, only the compiled one.
But there are good news. If you don't want to have the "spare CSS" in the public directories... install them not with --symlink
, but really making a copy. Once "assetic" has built the compound CSS, and you can DELETE the original CSS from the filesystem, and leave the images:
Compilation process
Note I do this for the --env=prod
environment.
Just a few final thoughts:
This desired behaviour can be achieved by having the images in "public" directory in Git or Mercurial and the "css" in the "assets" directory. That is, instead of having them in "public" as shown in the directories, imagine a, b, c... residing in the "assets" instead of "public", than have your installer/deployer (probably a Bash script) to put the CSS temporarily inside the "public" dir before assets:install
is executed, then assets:install
, then assetic:dump
, and then automating the removal of CSS from the public directory after assetic:dump
has been executed. This would achive EXACTLY the behaviour desired in the question.
Another (unknown if possible) solution would be to explore if "assets:install" can only take "public" as the source or could also take "assets" as a source to publish. That would help when installed with the --symlink
option when developing.
Additionally, if we are going to script the removal from the "public" dir, then, the need of storing them in a separate directory ("assets") disappears. They can live inside "public" in our version-control system as there will be dropped upon deploy to the public. This allows also for the --symlink
usage.
BUT ANYWAY, CAUTION NOW: As now the originals are not there anymore (rm -Rf
), there are only two solutions, not three. The working div "B" does not work anymore as it was an asset() call assuming there was the original asset. Only "C" (the compiled one) will work.
So... there is ONLY a FINAL WINNER: Div "C" allows EXACTLY what it was asked in the topic: To be compiled, respect the path to the images and do not expose the original source to the public.
The winner is C
You can use the border-radius attribute to give it a border-radius equivalent to the element's border-radius. For example:
<div style="border-radius 10px; -moz-border-radius 10px; -webkit-border-radius 10px; width: 20px; height: 20px; background: red; border: solid black 1px;"> </div>
(The reason for using the -moz and -webkit extensions is to support pre-CSS3-final versions of Gecko and Webkit.)
There are more examples on this page. As far as inserting text, you can do it but you have to be mindful of the positioning, as most browsers' box padding model still uses the outer square.
Yes, it is possible.
try:
...
except FirstException:
handle_first_one()
except SecondException:
handle_second_one()
except (ThirdException, FourthException, FifthException) as e:
handle_either_of_3rd_4th_or_5th()
except Exception:
handle_all_other_exceptions()
See: http://docs.python.org/tutorial/errors.html
The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)
This is my solution, compatible also with Python3. It does also manage border cases, but it misses utf-16 support:
def tail(filepath):
"""
@author Marco Sulla ([email protected])
@date May 31, 2016
"""
try:
filepath.is_file
fp = str(filepath)
except AttributeError:
fp = filepath
with open(fp, "rb") as f:
size = os.stat(fp).st_size
start_pos = 0 if size - 1 < 0 else size - 1
if start_pos != 0:
f.seek(start_pos)
char = f.read(1)
if char == b"\n":
start_pos -= 1
f.seek(start_pos)
if start_pos == 0:
f.seek(start_pos)
else:
char = ""
for pos in range(start_pos, -1, -1):
f.seek(pos)
char = f.read(1)
if char == b"\n":
break
return f.readline()
It's ispired by Trasp's answer and AnotherParker's comment.
Use this in your my.ini
under
[mysqldump]
user=root
password=anything
How about doing something like this? I've made it from scratch...
What I've done is used 2 tables, one for header, which will be static always, and the other table renders cells, which I've wrapped using a div
element with a fixed height, and to enable scroll, am using overflow-y: auto;
Also make sure you use table-layout: fixed;
with fixed width td
elements so that your table
doesn't break when a string without white space
is used, so inorder to break that string am using word-wrap: break-word;
.wrap {
width: 352px;
}
.wrap table {
width: 300px;
table-layout: fixed;
}
table tr td {
padding: 5px;
border: 1px solid #eee;
width: 100px;
word-wrap: break-word;
}
table.head tr td {
background: #eee;
}
.inner_table {
height: 100px;
overflow-y: auto;
}
<div class="wrap">
<table class="head">
<tr>
<td>Head 1</td>
<td>Head 1</td>
<td>Head 1</td>
</tr>
</table>
<div class="inner_table">
<table>
<tr>
<td>Body 1</td>
<td>Body 1</td>
<td>Body 1</td>
</tr>
<!-- Some more tr's -->
</table>
</div>
</div>
You may use pip
for that without using the network. See in the docs (search for "Install a particular source archive file"). Any of those should work:
pip install relative_path_to_seaborn.tar.gz
pip install absolute_path_to_seaborn.tar.gz
pip install file:///absolute_path_to_seaborn.tar.gz
Or you may uncompress the archive and use setup.py
directly with either pip
or python
:
cd directory_containing_tar.gz
tar -xvzf seaborn-0.10.1.tar.gz
pip install seaborn-0.10.1
python setup.py install
Of course, you should also download required packages and install them the same way before you proceed.
You don't have to add a .
in getElementsByClassName
, i.e.
var multibutton = angular.element(element.getElementsByClassName("multi-files"));
However, when using angular.element
, you do have to use jquery style selectors:
angular.element('.multi-files');
should do the trick.
Also, from this documentation "If jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite.""
You missed the second statement: 1) NOT LIKE A, AND 2) NOT LIKE B
SELECT word FROM table WHERE word NOT LIKE '%a%' AND word NOT LIKE '%b%'
To sort a 1D vector or a single column of data, just call the sort function and pass in your sequence.
On the other hand, the order function is necessary to sort data two-dimensional data--i.e., multiple columns of data collected in a matrix or dataframe.
Stadium Home Week Qtr Away Off Def Result Kicker Dist
751 Out PHI 14 4 NYG PHI NYG Good D.Akers 50
491 Out KC 9 1 OAK OAK KC Good S.Janikowski 32
702 Out OAK 15 4 CLE CLE OAK Good P.Dawson 37
571 Out NE 1 2 OAK OAK NE Missed S.Janikowski 43
654 Out NYG 11 2 PHI NYG PHI Good J.Feely 26
307 Out DEN 14 2 BAL DEN BAL Good J.Elam 48
492 Out KC 13 3 DEN KC DEN Good L.Tynes 34
691 Out NYJ 17 3 BUF NYJ BUF Good M.Nugent 25
164 Out CHI 13 2 GB CHI GB Good R.Gould 25
80 Out BAL 1 2 IND IND BAL Good M.Vanderjagt 20
Here is an excerpt of data for field goal attempts in the 2008 NFL season, a dataframe i've called 'fg'. suppose that these 10 data points represent all of the field goals attempted in 2008; further suppose you want to know the the distance of the longest field goal attempted that year, who kicked it, and whether it was good or not; you also want to know the second-longest, as well as the third-longest, etc.; and finally you want the shortest field goal attempt.
Well, you could just do this:
sort(fg$Dist, decreasing=T)
which returns: 50 48 43 37 34 32 26 25 25 20
That is correct, but not very useful--it does tell us the distance of the longest field goal attempt, the second-longest,...as well as the shortest; however, but that's all we know--eg, we don't know who the kicker was, whether the attempt was successful, etc. Of course, we need the entire dataframe sorted on the "Dist" column (put another way, we want to sort all of the data rows on the single attribute Dist. that would look like this:
Stadium Home Week Qtr Away Off Def Result Kicker Dist
751 Out PHI 14 4 NYG PHI NYG Good D.Akers 50
307 Out DEN 14 2 BAL DEN BAL Good J.Elam 48
571 Out NE 1 2 OAK OAK NE Missed S.Janikowski 43
702 Out OAK 15 4 CLE CLE OAK Good P.Dawson 37
492 Out KC 13 3 DEN KC DEN Good L.Tynes 34
491 Out KC 9 1 OAK OAK KC Good S.Janikowski 32
654 Out NYG 11 2 PHI NYG PHI Good J.Feely 26
691 Out NYJ 17 3 BUF NYJ BUF Good M.Nugent 25
164 Out CHI 13 2 GB CHI GB Good R.Gould 25
80 Out BAL 1 2 IND IND BAL Good M.Vanderjagt 20
This is what order does. It is 'sort' for two-dimensional data; put another way, it returns a 1D integer index comprised of the row numbers such that sorting the rows according to that vector, would give you a correct row-oriented sort on the column, Dist
Here's how it works. Above, sort was used to sort the Dist column; to sort the entire dataframe on the Dist column, we use 'order' exactly the same way as 'sort' is used above:
ndx = order(fg$Dist, decreasing=T)
(i usually bind the array returned from 'order' to the variable 'ndx', which stands for 'index', because i am going to use it as an index array to sort.)
that was step 1, here's step 2:
'ndx', what is returned by 'sort' is then used as an index array to re-order the dataframe, 'fg':
fg_sorted = fg[ndx,]
fg_sorted is the re-ordered dataframe immediately above.
In sum, 'sort' is used to create an index array (which specifies the sort order of the column you want sorted), which then is used as an index array to re-order the dataframe (or matrix).
Check out this blog post here that talks about the same thing. From what I gather, the extra time might have to do with walking up the scope chain.
If you are using command line tools, then you can also set it in the shell.
On linux, with a sh type shell, you can do for example:
export NLS_TIMESTAMP_FORMAT='DD/MON/RR HH24:MI:SSXFF'
Then you can use the command line tools and it will use the specified format:
/path/to/dbhome_1/bin/sqlldr user/pass@host:port/service control=table.ctl direct=true
RE. "Can we set this value for individual page" – MonsterMMORPG.
Yes, you can (& normally should) enclose the previous answer using the location-tag.
e.g.
...
<location path="YourWebpage.aspx">
<system.web>
<httpRuntime executionTimeout="300" maxRequestLength="29296" />
</system.web>
</location>
</configuration>
The above snippet is taken from the end of my own working web.config, which I tested yesterday - it works for me.
1) Wait for the popup balloon to appear.
2) Open a new tab.
3) Close the a new tab. The popup will be gone from the original tab.
A small Chrome extension can automate these steps:
manifest.json
{
"name": "Open and close tab",
"description": "After Chrome starts, open and close a new tab.",
"version": "1.0",
"manifest_version": 2,
"permissions": ["tabs"],
"background": {
"scripts": ["background.js"],
"persistent": false
}
}
background.js
// This runs when Chrome starts up
chrome.runtime.onStartup.addListener(function() {
// Execute the inner function after a few seconds
setTimeout(function() {
// Open new tab
chrome.tabs.create({url: "about:blank"});
// Get tab ID of newly opened tab, then close the tab
chrome.tabs.query({'currentWindow': true}, function(tabs) {
var newTabId = tabs[1].id;
chrome.tabs.remove(newTabId);
});
}, 5000);
});
With this extension installed, launch Chrome and immediately switch apps before the popup appears... a few seconds later, the popup will be gone and you won't see it when you switch back to Chrome.
sSource = StringUtils.replace(sSource, "\\/", "/")
I faced the same problem and wasn't able to fix it with the provided solution by Shamsudheen TK. Ionic somehow added transparency to my icons even if the source icon did not have any transparency at all. In the end I was able to resolve it by:
Install imagemagick (MacOS):
brew install imagemagick
Remove alpha channel from all images in resource folder:
find ./resources/ -name "*.png" -exec convert "{}" -alpha off "{}" \;
Try
/etc/init.d/tomcat stop
(maybe you have to write something after tomcat
, just press tab one time)
Edit: And you also need to do it as root.
JavaScript is single-threaded, and all the time you work on a normal synchronous code-flow execution.
Good examples of the asynchronous behavior that JavaScript can have are events (user interaction, Ajax request results, etc) and timers, basically actions that might happen at any time.
I would recommend you to give a look to the following article:
That article will help you to understand the single-threaded nature of JavaScript and how timers work internally and how asynchronous JavaScript execution works.
You can use DATEDIFF(it is a built-in function) and % (for scale calculation) and CONCAT for make result to only one column
select CONCAT('Month: ',MonthDiff,' Days: ' , DayDiff,' Minutes: ',MinuteDiff,' Seconds: ',SecondDiff) as T from
(SELECT DATEDIFF(MONTH, '2017-10-15 19:39:47' , '2017-12-31 23:59:59') % 12 as MonthDiff,
DATEDIFF(DAY, '2017-10-15 19:39:47' , '2017-12-31 23:59:59') % 30 as DayDiff,
DATEDIFF(HOUR, '2017-10-15 19:39:47' , '2017-12-31 23:59:59') % 24 as HourDiff,
DATEDIFF(MINUTE, '2017-10-15 19:39:47' , '2017-12-31 23:59:59') % 60 AS MinuteDiff,
DATEDIFF(SECOND, '2017-10-15 19:39:47' , '2017-12-31 23:59:59') % 60 AS SecondDiff) tbl
try this....
SELECT FORMAT(CAST(DOB AS DATE),'yyyyMMdd') FROM Employees;
I searched and searched and finally found that ie needs to know the map size. Set the map size to match the div size.
map = new GMap2(document.getElementById("map_canvas2"), { size: new GSize(850, 600) });
<div id="map_canvas2" style="width: 850px; height: 600px">
</div>
To convert array-like to array in efficient way we can make use of the jQuery makeArray
:
makeArray: Convert an array-like object into a true JavaScript array.
Usage:
var domArray = jQuery.makeArray(htmlCollection);
A little extra:
If you do not want to keep reference to the array object (most of the time HTMLCollections are dynamically changes so its better to copy them into another array, This example pay close attention to performance:
var domDataLength = domData.length //Better performance, no need to calculate every iteration the domArray length
var resultArray = new Array(domDataLength) // Since we know the length its improves the performance to declare the result array from the beginning.
for (var i = 0 ; i < domDataLength ; i++) {
resultArray[i] = domArray[i]; //Since we already declared the resultArray we can not make use of the more expensive push method.
}
What is array-like?
HTMLCollection is an "array-like"
object, the array-like objects are similar to array's object but missing a lot of its functionally definition:
Array-like objects look like arrays. They have various numbered elements and a length property. But that’s where the similarity stops. Array-like objects do not have any of Array’s functions, and for-in loops don’t even work!
A little risky, but you could run a curl POST command with the values from the form from the JMX console, its URL and http authentication (if required):
curl -s -X POST --user 'myuser:mypass'
--data "action=invokeOp&name=App:service=ThisServiceOp&methodIndex=3&arg0=value1&arg1=value1&submit=Invoke"
http://yourhost.domain.com/jmx-console/HtmlAdaptor
Beware: the method index may change with changes to the software. And the implementation of the web form could change.
The above is based on source of the JMX service page for the operation you want to perform:
http://yourhost.domain.com/jmx-console/HtmlAdaptor?action=inspectMBean&name=YourJMXServiceName
Source of the form:
form method="post" action="HtmlAdaptor">
<input type="hidden" name="action" value="invokeOp">
<input type="hidden" name="name" value="App:service=ThisServiceOp">
<input type="hidden" name="methodIndex" value="3">
<hr align='left' width='80'>
<h4>void ThisOperation()</h4>
<p>Operation exposed for management</p>
<table cellspacing="2" cellpadding="2" border="1">
<tr class="OperationHeader">
<th>Param</th>
<th>ParamType</th>
<th>ParamValue</th>
<th>ParamDescription</th>
</tr>
<tr>
<td>p1</td>
<td>java.lang.String</td>
<td>
<input type="text" name="arg0">
</td>
<td>(no description)</td>
</tr>
<tr>
<td>p2</td>
<td>arg1Type</td>
<td>
<input type="text" name="arg1">
</td>
<td>(no description)</td>
</tr>
</table>
<input type="submit" value="Invoke">
</form>
If you do not need to modify the substring, then you can use QStringRef
. The QStringRef
class is a read only wrapper around an existing QString
that references a substring within the existing string. This gives much better performance than creating a new QString
object to contain the sub-string. E.g.
QString myString("This is a string");
QStringRef subString(&myString, 5, 2); // subString contains "is"
If you do need to modify the substring, then left()
, mid()
and right()
will do what you need...
QString myString("This is a string");
QString subString = myString.mid(5,2); // subString contains "is"
subString.append("n't"); // subString contains "isn't"
I was searching for the same thing, my solution was this:
$('#el-id').focus().select();
The storage location of the data will be implementation dependent.
However, the meaning of static is "internal linkage". Thus, the symbol is internal to the compilation unit (foo.c, bar.c) and cannot be referenced outside that compilation unit. So, there can be no name collisions.
you can always cast any object to any type by up-casting it to Object first. in your case:
(List<Customer>)(Object)list;
you must be sure that at runtime the list contains nothing but Customer objects.
Critics say that such casting indicates something wrong with your code; you should be able to tweak your type declarations to avoid it. But Java generics is too complicated, and it is not perfect. Sometimes you just don't know if there is a pretty solution to satisfy the compiler, even though you know very well the runtime types and you know what you are trying to do is safe. In that case, just do the crude casting as needed, so you can leave work for home.
You can try the this class to displays an image read from a URL within a JFrame.
public class ShowImageFromURL {
public static void show(String urlLocation) {
Image image = null;
try {
URL url = new URL(urlLocation);
URLConnection conn = url.openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/5.0");
conn.connect();
InputStream urlStream = conn.getInputStream();
image = ImageIO.read(urlStream);
JFrame frame = new JFrame();
JLabel lblimage = new JLabel(new ImageIcon(image));
frame.getContentPane().add(lblimage, BorderLayout.CENTER);
frame.setSize(image.getWidth(null) + 50, image.getHeight(null) + 50);
frame.setVisible(true);
} catch (IOException e) {
System.out.println("Something went wrong, sorry:" + e.toString());
e.printStackTrace();
}
}
}
Ref : https://gist.github.com/aslamanver/92af3ac67406cfd116b7e4e177156926
This is a lot easier to do starting in select2 v4. You can create a new Option
, and append it to the select
element directly. See my codepen or the example below:
$(document).ready(function() {_x000D_
$("#state").select2({_x000D_
tags: true_x000D_
});_x000D_
_x000D_
$("#btn-add-state").on("click", function(){_x000D_
var newStateVal = $("#new-state").val();_x000D_
// Set the value, creating a new option if necessary_x000D_
if ($("#state").find("option[value=" + newStateVal + "]").length) {_x000D_
$("#state").val(newStateVal).trigger("change");_x000D_
} else { _x000D_
// Create the DOM option that is pre-selected by default_x000D_
var newState = new Option(newStateVal, newStateVal, true, true);_x000D_
// Append it to the select_x000D_
$("#state").append(newState).trigger('change');_x000D_
} _x000D_
}); _x000D_
});
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>_x000D_
_x000D_
_x000D_
<select id="state" class="js-example-basic-single" type="text" style="width:90%">_x000D_
<option value="AL">Alabama</option>_x000D_
<option value="WY">Wyoming</option>_x000D_
</select>_x000D_
<br>_x000D_
<br>_x000D_
<input id="new-state" type="text" />_x000D_
<button type="button" id="btn-add-state">Set state value</button>
_x000D_
Hint: try entering existing values into the text box, like "AL" or "WY". Then try adding some new values.
Use a suitable guard in the outer loop. Set the guard in the inner loop before you break.
bool exitedInner = false;
for (int i = 0; i < N && !exitedInner; ++i) {
.... some outer loop stuff
for (int j = 0; j < M; ++j) {
if (sometest) {
exitedInner = true;
break;
}
}
if (!exitedInner) {
... more outer loop stuff
}
}
Or better yet, abstract the inner loop into a method and exit the outer loop when it returns false.
for (int i = 0; i < N; ++i) {
.... some outer loop stuff
if (!doInner(i, N, M)) {
break;
}
... more outer loop stuff
}
this worked for me to solve the problem in IE8:
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=1)";
Cheers
I do not work with google android but I think you'll find it's not that hard to get this working. If you read the relevant bit of the java tutorial you'll see that a registered cookiehandler gets callbacks from the HTTP code.
So if there is no default (have you checked if CookieHandler.getDefault()
really is null?) then you can simply extend CookieHandler, implement put/get and make it work pretty much automatically. Be sure to consider concurrent access and the like if you go that route.
edit: Obviously you'd have to set an instance of your custom implementation as the default handler through CookieHandler.setDefault()
to receive the callbacks. Forgot to mention that.
TL;DR:
No, don't subscribe manually to them, don't use them in services. Use them as is shown in the documentation only to emit events in components. Don't defeat angular's abstraction.
Answer:
EventEmitter is an angular2 abstraction and its only purpose is to emit events in components. Quoting a comment from Rob Wormald
[...] EventEmitter is really an Angular abstraction, and should be used pretty much only for emitting custom Events in components. Otherwise, just use Rx as if it was any other library.
This is stated really clear in EventEmitter's documentation.
Use by directives and components to emit custom Events.
Angular2 will never guarantee us that EventEmitter will continue being an Observable. So that means refactoring our code if it changes. The only API we must access is its emit()
method. We should never subscribe manually to an EventEmitter.
All the stated above is more clear in this Ward Bell's comment (recommended to read the article, and the answer to that comment). Quoting for reference
Do NOT count on EventEmitter continuing to be an Observable!
Do NOT count on those Observable operators being there in the future!
These will be deprecated soon and probably removed before release.
Use EventEmitter only for event binding between a child and parent component. Do not subscribe to it. Do not call any of those methods. Only call
eve.emit()
His comment is in line with Rob's comment long time ago.
Simply use it to emit events from your component. Take a look a the following example.
@Component({
selector : 'child',
template : `
<button (click)="sendNotification()">Notify my parent!</button>
`
})
class Child {
@Output() notifyParent: EventEmitter<any> = new EventEmitter();
sendNotification() {
this.notifyParent.emit('Some value to send to the parent');
}
}
@Component({
selector : 'parent',
template : `
<child (notifyParent)="getNotification($event)"></child>
`
})
class Parent {
getNotification(evt) {
// Do something with the notification (evt) sent by the child!
}
}
class MyService {
@Output() myServiceEvent : EventEmitter<any> = new EventEmitter();
}
Stop right there... you're already wrong...
Hopefully these two simple examples will clarify EventEmitter's proper usage.
According to the discussion here you can directly compare two vectors using
==
if (vector1 == vector2){
//true
}
else{
//false
}
ActiveRecord stores validation errors in an array called errors
. If you have a User
model then you would access the validation errors in a given instance like so:
@user = User.create[params[:user]] # create will automatically call validators
if @user.errors.any? # If there are errors, do something
# You can iterate through all messages by attribute type and validation message
# This will be something like:
# attribute = 'name'
# message = 'cannot be left blank'
@user.errors.each do |attribute, message|
# do stuff for each error
end
# Or if you prefer, you can get the full message in single string, like so:
# message = 'Name cannot be left blank'
@users.errors.full_messages.each do |message|
# do stuff for each error
end
# To get all errors associated with a single attribute, do the following:
if @user.errors.include?(:name)
name_errors = @user.errors[:name]
if name_errors.kind_of?(Array)
name_errors.each do |error|
# do stuff for each error on the name attribute
end
else
error = name_errors
# do stuff for the one error on the name attribute.
end
end
end
Of course you can also do any of this in the views instead of the controller, should you want to just display the first error to the user or something.
You can download c4droid and then install the GCC plugin and install to your SD. From the shell I just traverse to the directory where the GCC binary is and then call it to make an on board executable.
/mnt/sdcard/Android/data/com.n0n3m4.droidc/files/gcc/bin/arm-linux-androideabi-gcc
#include<stdio.h>
int main(){
printf("hello arm!\n");
return 0;
}
hello arm!
UIImageView *imageView = [[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"MyImage.png"]]autorelease];
NSLog(@"Size of my Image => %f, %f ", [[imageView image] size].width, [[imageView image] size].height) ;
The Servlet Specification JSR-315 clearly defines the web container behavior in the service (and doGet, doPost, doPut etc.) methods (2.3.3.1 Multithreading Issues, Page 9):
A servlet container may send concurrent requests through the service method of the servlet. To handle the requests, the Servlet Developer must make adequate provisions for concurrent processing with multiple threads in the service method.
Although it is not recommended, an alternative for the Developer is to implement the SingleThreadModel interface which requires the container to guarantee that there is only one request thread at a time in the service method. A servlet container may satisfy this requirement by serializing requests on a servlet, or by maintaining a pool of servlet instances. If the servlet is part of a Web application that has been marked as distributable, the container may maintain a pool of servlet instances in each JVM that the application is distributed across.
For servlets not implementing the SingleThreadModel interface, if the service method (or methods such as doGet or doPost which are dispatched to the service method of the HttpServlet abstract class) has been defined with the synchronized keyword, the servlet container cannot use the instance pool approach, but must serialize requests through it. It is strongly recommended that Developers not synchronize the service method (or methods dispatched to it) in these circumstances because of detrimental effects on performance
How to convert date to string and to date again?
LocalDate.now().toString()
2017-01-23
…and…
LocalDate.parse( "2017-01-23" )
The Question uses troublesome old date-time classes bundled with the earliest versions of Java. Those classes are now legacy, supplanted by the java.time classes built into Java 8, Java 9, and later.
Determining today’s date requires a time zone. For any given moment the date varies around the globe by zone.
If not supplied by you, your JVM’s current default time zone is applied. That default can change at any moment during runtime, and so is unreliable. I suggest you always specify your desired/expected time zone.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate ld = LocalDate.now( z ) ;
Your desired format of YYYY-MM-DD happens to comply with the ISO 8601 standard.
That standard happens to be used by default by the java.time classes when parsing/generating strings. So you can simply call LocalDate::parse
and LocalDate::toString
without specifying a formatting pattern.
String s = ld.toString() ;
To parse:
LocalDate ld = LocalDate.parse( s ) ;
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
You could have the active class be dependent upon a boolean data value:
<th
class="initial "
v-on="click: myFilter"
v-class="{active: isActive}">
<span class="wkday">M</span>
</th>
new Vue({
el: '#my-container',
data: {
isActive: false
},
methods: {
myFilter: function() {
this.isActive = !this.isActive;
// some code to filter users
}
}
})
From http://developer.android.com/reference/android/app/Activity.html
public final void showDialog (int id) Added in API level 1
This method was deprecated in API level 13. Use the new DialogFragment class with FragmentManager instead; this is also available on older platforms through the Android compatibility package.
Simple version of showDialog(int, Bundle) that does not take any arguments. Simply calls showDialog(int, Bundle) with null arguments.
Why
How to solve?
More
You can not serialize a Python 3 'string' to bytes without explict conversion to some encoding.
outfile.write(plaintext.encode('utf-8'))
is possibly what you want. Also this works for both python 2.x and 3.x.
Usually String.Format("format", object) is preferable to object.ToString("format"). Therefore,
String.Format("{0:00000}", 15);
is preferable to,
Key = i.ToString("000000");
SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\Samples\MyApp\C#\bin\Debug\Login.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
this is working for me... Is there any way to short the path? like
SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=\bin\Debug\Login.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
In very simple terms (because the other answers are referring you to all the official design patterns anyway, so look at them for further details):
If you want to have a class which is monitored by other classes in the ecosystem of your program you say that you want the class to be observable. I.e. there might be some changes in its state which you would want to broadcast to the rest of the program.
Now, to do this we have to call some kind of method. We don't want the Observable class to be tightly coupled with the classes that are interested in observing it. It doesn't care who it is as long as it fulfils certain criteria. (Imagine it is a radio station, it doesn't care who is listening as long as they have an FM radio tuned on their frequency). To achieve that we use an interface, referred to as the Observer.
Therefore, the Observable class will have a list of Observers (i.e. instances implementing the Observer interface methods you might have). Whenever it wants to broadcast something, it just calls the method on all the observers, one after the other.
The last thing to close the puzzle is how will the Observable class know who is interested?
So the Observable class must offer some mechanism to allow Observers to register their interest. A method such as addObserver(Observer o)
internally adds the Observer to the list of observers, so that when something important happens, it loops through the list and calls the respective notification method of the Observer interface of each instance in the list.
It might be that in the interview they did not ask you explicitly about the java.util.Observer
and java.util.Observable
but about the generic concept. The concept is a design pattern, which Java happens to provide support for directly out of the box to help you implement it quickly when you need it. So I would suggest that you understand the concept rather than the actual methods/classes (which you can look up when you need them).
UPDATE
In response to your comment, the actual java.util.Observable
class offers the following facilities:
Maintaining a list of java.util.Observer
instances. New instances interested in being notified can be added through addObserver(Observer o)
, and removed through deleteObserver(Observer o)
.
Maintaining an internal state, specifying whether the object has changed since the last notification to the observers. This is useful because it separates the part where you say that the Observable
has changed, from the part where you notify the changes. (E.g. Its useful if you have multiple changes happening and you only want to notify at the end of the process rather than at each small step). This is done through setChanged()
. So you just call it when you changed something to the Observable
and you want the rest of the Observers
to eventually know about it.
Notifying all observers that the specific Observable
has changed state. This is done through notifyObservers()
. This checks if the object has actually changed (i.e. a call to setChanged()
was made) before proceeding with the notification. There are 2 versions, one with no arguments and one with an Object
argument, in case you want to pass some extra information with the notification. Internally what happens is that it just iterates through the list of Observer
instances and calls the update(Observable o, Object arg)
method for each of them. This tells the Observer
which was the Observable object that changed (you could be observing more than one), and the extra Object arg
to potentially carry some extra information (passed through notifyObservers()
.
With ES6+ you can just do [${variable}
]
Try the following:
url($_GET['q'], array('absolute' => true));
In addition to Cristian C's answer (sorry, I do not have the ability to make comments), if you make one handler for both buttons, you may directly compare v to b1 and b2, or if you want to compare by the ID, you do not need to cast v to Button (View has getId() method, too), and that way there is no worry of cast exception.
private void ClearFolder(string FolderName)
{
DirectoryInfo dir = new DirectoryInfo(FolderName);
foreach(FileInfo fi in dir.GetFiles())
{
try
{
fi.Delete();
}
catch(Exception) { } // Ignore all exceptions
}
foreach(DirectoryInfo di in dir.GetDirectories())
{
ClearFolder(di.FullName);
try
{
di.Delete();
}
catch(Exception) { } // Ignore all exceptions
}
}
If you know there are no sub-folders, something like this may be the easiest:
Directory.GetFiles(folderName).ForEach(File.Delete)
I think you want something like this:
public class Person {
private int age;
//public method to get the age variable
public int getAge(){
return this.age
}
//public method to set the age variable
public void setAge(int age){
this.age = age;
}
}
You're simply calling such a method on an object instance. Such methods are useful especially if setting something is supposed to have side effects. E.g. if you want to react to certain events like:
public void setAge(int age){
this.age = age;
double averageCigarettesPerYear = this.smokedCigarettes * 1.0 / age;
if(averageCigarettesPerYear >= 7300.0) {
this.eventBus.fire(new PersonSmokesTooMuchEvent(this));
}
}
Of course this can be dangerous if somebody forgets to call setAge(int)
where he should and sets age
directly using this.age
.
one way...
$needle = "blah";
$content = file_get_contents('file.txt');
preg_match('~^(.*'.$needle.'.*)$~',$content,$line);
echo $line[1];
though it would probably be better to read it line by line with fopen() and fread() and use strpos()
All of these answers unfortunately miss the point.
There are 2 security context nuances here, and we need them to overlap. - "Run as administrator" - changing your execution level on your local machine - "Run as different user" - selects what user credentials you run the process under.
When UAC is enabled on a workstation, there are processes which refuse to run unless elevated - simply being a member of the local "Administrators" group isn't enough. If your requirement also dictates that you use alternate credentials to those you are signed in with, we need a method to invoke the process both as the alternate credentials AND elevated.
What I found can be used, though a bit of a hassle, is:
use the Sysinternals psexec utility as follows:
psexec \\localworkstation -h -i -u domain\otheruser exetorun.exe
The first elevation is needed to be able to push the psexec service. The -h runs the new "remote" (local) process elevated, and -i lets it interact with the desktop.
Perhaps there are easier ways than this?
Swift 3, xcode 8.1
You can use small extension to place UIActivityIndicatorView in the centre of UIView and inherited UIView classes:
extension UIActivityIndicatorView {
convenience init(activityIndicatorStyle: UIActivityIndicatorViewStyle, color: UIColor, placeInTheCenterOf parentView: UIView) {
self.init(activityIndicatorStyle: activityIndicatorStyle)
center = parentView.center
self.color = color
parentView.addSubview(self)
}
}
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge, color: .gray, placeInTheCenterOf: view)
activityIndicator.startAnimating()
In this example UIActivityIndicatorView placed in the centre of the ViewControllers view:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge, color: .gray, placeInTheCenterOf: view)
activityIndicator.startAnimating()
}
}
extension UIActivityIndicatorView {
convenience init(activityIndicatorStyle: UIActivityIndicatorViewStyle, color: UIColor, placeInTheCenterOf parentView: UIView) {
self.init(activityIndicatorStyle: activityIndicatorStyle)
center = parentView.center
self.color = color
parentView.addSubview(self)
}
}
Have you considered using the "xcopy" command?
The xcopy command will do all that for you.
Why not just using simple css :
<router-outlet></router-outlet>
<div class="loading"></div>
And in your styles :
div.loading{
height: 100px;
background-color: red;
display: none;
}
router-outlet + div.loading{
display: block;
}
Or even we can do this for the first answer:
<router-outlet></router-outlet>
<spinner-component></spinner-component>
And then simply just
spinner-component{
display:none;
}
router-outlet + spinner-component{
display: block;
}
The trick here is, the new routes and components will always appear after router-outlet , so with a simple css selector we can show and hide the loading.
String Declaration:
String str;
String Initialization
String[] str=new String[3];//if we give string[2] will get Exception insted
str[0]="Tej";
str[1]="Good";
str[2]="Girl";
String str="SSN";
We can get individual character in String:
char chr=str.charAt(0);`//output will be S`
If I want to to get individual character Ascii value like this:
System.out.println((int)chr); //output:83
Now i want to convert Ascii value into Charecter/Symbol.
int n=(int)chr;
System.out.println((char)n);//output:S
isn't the same as the Winform and Webform way?
listBox1.Items.Clear();
This solution is easy to use, it is used as a normal dictionary, but you can use the sum function.
class SumDict(dict):
def __add__(self, y):
return {x: self.get(x, 0) + y.get(x, 0) for x in set(self).union(y)}
A = SumDict({'a': 1, 'c': 2})
B = SumDict({'b': 3, 'c': 4}) # Also works: B = {'b': 3, 'c': 4}
print(A + B) # OUTPUT {'a': 1, 'b': 3, 'c': 6}
Depending on the data (e.g. tsv extension) it may use tab as separators, so you may try sep = '\t'
with read.csv
.
Adding a header with add_header
works fine with proxy pass, but if there is an existing header value in the response it will stack the values.
If you want to set or replace a header value (for example replace the Access-Control-Allow-Origin
header to match your client for allowing cross origin resource sharing) then you can do as follows:
# 1. hide the Access-Control-Allow-Origin from the server response
proxy_hide_header Access-Control-Allow-Origin;
# 2. add a new custom header that allows all * origins instead
add_header Access-Control-Allow-Origin *;
So proxy_hide_header
combined with add_header
gives you the power to set/replace response header values.
Similar answer can be found here on ServerFault
Note: proxy_set_header
is for setting request headers before the request is sent further, not for setting response headers (these configuration attributes for headers can be a bit confusing).
It is not clear from your question what the criteria for deciding what strings to remove is, but if you have or can make a list of the strings that you want to remove , you could do the following:
my_strings = ['a','b','c','d','e']
undesirable_strings = ['b','d']
for undesirable_string in undesirable_strings:
for i in range(my_strings.count(undesirable_string)):
my_strings.remove(undesirable_string)
which changes my_strings to ['a', 'c', 'e']
It's quite simple, first HTML must be added:
<div id="dialog"></div>
Then, it must be initialized:
<script type="text/javascript">
jQuery( document ).ready( function() {
jQuery( '#dialog' ).dialog( { 'autoOpen': false } );
});
</script>
After this you can show it by code:
jQuery( '#dialog' ).dialog( 'open' );
Gotta love list comprehensions.
[dict([a, int(x)] for a, x in b.items()) for b in list]
(remark: for Python 2 only code you may use "iteritems" instead of "items")
Try this one:
Actions builder = new Actions(fDriver);
builder.keyDown(Keys.CONTROL)
.click(element)
.dragAndDrop(element, elementDropped)
.keyUp(Keys.CONTROL);
Action selected = builder.build();
selected.perform();
this can also be done like this if you don't want to use prepared statements.
String sql = "INSERT INTO course(course_code,course_desc,course_chair)"+"VALUES('"+course_code+"','"+course_desc+"','"+course_chair+"');"
Why it didnt insert value is because you were not providing values, but you were providing names of variables that you have used.
```yaml
{
"this-json": "looks awesome..."
}
If you want to have keys a different colour to the parameters, set your language as yaml
@Ankanna's answer gave me the idea of going through github's supported language list and yaml
was my best find.
When git push [$there]
does not say what to push, we have used the
traditional "matching" semantics so far (all your branches were sent
to the remote as long as there already are branches of the same name
over there). In Git 2.0, the default is now the "simple" semantics,
which pushes:
only the current branch to the branch with the same name, and only when the current branch is set to integrate with that remote branch, if you are pushing to the same remote as you fetch from; or
only the current branch to the branch with the same name, if you are pushing to a remote that is not where you usually fetch from.
You can use the configuration variable "push.default" to change this. If you are an old-timer who wants to keep using the "matching" semantics, you can set the variable to "matching", for example. Read the documentation for other possibilities.
When git add -u
and git add -A
are run inside a subdirectory
without specifying which paths to add on the command line, they
operate on the entire tree for consistency with git commit -a
and
other commands (these commands used to operate only on the current
subdirectory). Say git add -u .
or git add -A .
if you want to
limit the operation to the current directory.
git add <path>
is the same as git add -A <path>
now, so that
git add dir/
will notice paths you removed from the directory and
record the removal. In older versions of Git, git add <path>
used
to ignore removals. You can say git add --ignore-removal <path>
to
add only added or modified paths in <path>
, if you really want to.
Static variable in a header file:
say 'common.h'
has
static int zzz;
This variable 'zzz'
has internal linkage (This same variable can not be accessed in other translation units). Each translation unit which includes 'common.h'
has it's own unique object of name 'zzz'
.
Static variable in a class:
Static variable in a class is not a part of the subobject of the class. There is only one copy of a static data member shared by all the objects of the class.
$9.4.2/6 - "Static data members of a class in namespace scope have external linkage (3.5).A local class shall not have static data members."
So let's say 'myclass.h'
has
struct myclass{
static int zzz; // this is only a declaration
};
and myclass.cpp
has
#include "myclass.h"
int myclass::zzz = 0 // this is a definition,
// should be done once and only once
and "hisclass.cpp"
has
#include "myclass.h"
void f(){myclass::zzz = 2;} // myclass::zzz is always the same in any
// translation unit
and "ourclass.cpp"
has
#include "myclass.h"
void g(){myclass::zzz = 2;} // myclass::zzz is always the same in any
// translation unit
So, class static members are not limited to only 2 translation units. They need to be defined only once in any one of the translation units.
Note: usage of 'static' to declare file scope variable is deprecated and unnamed namespace is a superior alternate
Calling .parents(".box .something1")
will return all parent elements that match the selector .box .something
. In other words, it will return parent elements that are .something1
and are inside of .box
.
You need to get the children of the closest parent, like this:
$(this).closest('.box').children('.something1')
This code calls .closest
to get the innermost parent matching a selector, then calls .children
on that parent element to find the uncle you're looking for.
Append "empty" row to data frame and fill selected cells:
Generate empty data frame (no rows just columns a
and b
):
import pandas as pd
col_names = ["a","b"]
df = pd.DataFrame(columns = col_names)
Append empty row at the end of the data frame:
df = df.append(pd.Series(), ignore_index = True)
Now fill the empty cell at the end (len(df)-1
) of the data frame in column a
:
df.loc[[len(df)-1],'a'] = 123
Result:
a b
0 123 NaN
And of course one can iterate over the rows and fill cells:
col_names = ["a","b"]
df = pd.DataFrame(columns = col_names)
for x in range(0,5):
df = df.append(pd.Series(), ignore_index = True)
df.loc[[len(df)-1],'a'] = 123
Result:
a b
0 123 NaN
1 123 NaN
2 123 NaN
3 123 NaN
4 123 NaN
this configuration in app.js worked fine for me :
//production mode
if (process.env.NODE_ENV === "production") {
app.use(express.static(path.join(__dirname, "client/build")));
app.get("*", (req, res) => {
res.sendFile(path.join((__dirname + "/client/build/index.html")));
});
}
//build mode
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname + "/client/public/index.html"));
});
You have to use absolute path in this case. But if you set the CopyToOutputDirectory = CopyAlways
, it will work as you are doing it.
just run this command from command prompt and it will launch chrome instance with CORS disabled:
C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --disable-gpu --user-data-dir=~/chromeTemp
sh prog1;sh prog2
I think this works..
Step-1: Change the file name src/App.js to src/app.js
Step-2: Click on "Yes" for "Update imports for app.js".
Step-3: Restart the server again.
Just as an FYI, here is my working code:
src_dir = "C:\\temp\\CSV\\"
target_dir = "C:\\temp\\output2\\"
keyword = "KEYWORD"
for f in os.listdir(src_dir):
file_name = os.path.join(src_dir, f)
out_file = os.path.join(target_dir, f)
with open(file_name, "r+") as fi, open(out_file, "w") as fo:
for line in fi:
if keyword not in line:
fo.write(line)
Thanks again to everyone for all the great feedback!
This always gets the right filename of the current script, even when it is called from within another script. It is especially useful when using subprocess
.
import sys,os
filename = sys.argv[0]
from there, you can get the script's full path with:
>>> os.path.abspath(filename)
'/foo/bar/script.py'
It also makes easier to navigate folders by just appending /..
as many times as you want to go 'up' in the directories' hierarchy.
To get the cwd:
>>> os.path.abspath(filename+"/..")
'/foo/bar'
For the parent path:
>>> os.path.abspath(filename+"/../..")
'/foo'
By combining "/.."
with other filenames, you can access any file in the system.
A better way for setting multiple options:
setIcon/setLogo
method will only work if you have set DisplayOptions Try this -
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE);
actionBar.setIcon(R.drawable.ic_launcher);
You can also set options for displaying LOGO(just add constant ActionBar.DISPLAY_USE_LOGO
). More information - displayOptions
Yep:
WITH tab (
bla bla
)
INSERT INTO dbo.prf_BatchItemAdditionalAPartyNos ( BatchID, AccountNo,
APartyNo,
SourceRowID)
SELECT * FROM tab
Note that this is for SQL Server, which supports multiple CTEs:
WITH x AS (), y AS () INSERT INTO z (a, b, c) SELECT a, b, c FROM y
Teradata allows only one CTE and the syntax is as your example.
$arr = [
[
'ID' => 1
]
];
echo array_search(1, array_column($arr, 'ID')); // prints 0 (!== false)
Above code echoes the index of the matching element, or false
if none.
To get the corresponding element, do something like:
$i = array_search(1, array_column($arr, 'ID'));
$element = ($i !== false ? $arr[$i] : null);
array_column works both on an array of arrays, and on an array of objects.
The lazy/hurry alternative (Dotnet Core 2.2):
[HttpGet("method1-{item}")]
public string Method1(var item) {
return "hello" + item;}
[HttpGet("method2-{item}")]
public string Method2(var item) {
return "world" + item;}
Calling them :
localhost:5000/api/controllername/method1-42
"hello42"
localhost:5000/api/controllername/method2-99
"world99"
Your submit button doesn't have a name. Add name="submit" to your submit button.
If you view source on the form in the browser, you'll see how it submits to self - the form's action attribute will contain the name of the current script - therefore when the form submits, it submits to itself. Edit for vanity sake!
This is another method I use because changing DropDownSyle
to DropDownList
makes it look 3D and sometimes its just plain ugly.
You can prevent user input by handling the KeyPress
event of the ComboBox like this.
private void ComboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
Make sure the physical available memory is more then VM defined min/max memory.
simply snapshot means it is the version which is not stable one.
when version includes snapshot like 1.0.0 -SNAPSHOT means it is not stable version and look for remote repository to resolve dependencies
or even more simple
Sub clearDebugConsole()
For i = 0 To 100
Debug.Print ""
Next i
End Sub
If you want to use a string key generated in your Node.js program, say, var v = 'HOME'
, you can use
process.env[v]
.
Otherwise, process.env.VARNAME
has to be hardcoded in your program.
Actually you have to Do Like below Example, which will help to Solve the Issue...
drop table ABC_table
create table ABC_table
(
names varchar(20),
age int
)
ALTER TABLE ABC_table
ADD CONSTRAINT MyConstraintName
DEFAULT 'This is not NULL' FOR names
insert into ABC(age) values(10)
select * from ABC
I've had this happen before as well, where there was TeamViewer client takes the control of the TAB key. You won't know this until you close the TV window that you have open in the background.
img{
max-width:100%;
object-fit: scale-down;
}
works for me. It scales down larger images to fit in the box, but leaves smaller images their original size.
This problem usually occurs when some process such as loading huge data to memory stream and your system memory is not capable of storing so much of data. Try clearing temp folder by giving the command
start -> run -> %temp%
what is the best way to do this in C++?
Because you asked it this way:
std::string msg(65546, 0); // all characters will be set to 0
Or:
std::vector<char> msg(65546); // all characters will be initialized to 0
If you are working with C functions which accept char* or const char*, then you can do:
some_c_function(&msg[0]);
You can also use the c_str() method on std::string if it accepts const char* or data().
The benefit of this approach is that you can do everything you want to do with a dynamically allocating char buffer but more safely, flexibly, and sometimes even more efficiently (avoiding the need to recompute string length linearly, e.g.). Best of all, you don't have to free the memory allocated manually, as the destructor will do this for you.
View.GONE = The view will not show and the rest of the views will not take its existence into consideration
View.INVISIBLE = The view will not show, but it will take its assigned space in the layout
Assume that we need to view some data in command prompt which are coming from a database table. First we create a list. Team_Details is my property class.
List<Team_Details> teamDetails = new List<Team_Details>();
Then you can connect to the database and do the data retrieving part and save it to the list as follows.
string connetionString = "Data Source=.;Initial Catalog=your DB name;Integrated Security=True;MultipleActiveResultSets=True";
using (SqlConnection conn = new SqlConnection(connetionString)){
string getTeamDetailsQuery = "select * from Team";
conn.Open();
using (SqlCommand cmd = new SqlCommand(getTeamDetailsQuery, conn))
{
SqlDataReader rdr = cmd.ExecuteReader();
{
teamDetails.Add(new Team_Details
{
Team_Name = rdr.GetString(rdr.GetOrdinal("Team_Name")),
Team_Lead = rdr.GetString(rdr.GetOrdinal("Team_Lead")),
});
}
Then you can print this list in command prompt as follows.
foreach (Team_Details i in teamDetails)
{
Console.WriteLine(i.Team_Name);
Console.WriteLine(i.Team_Lead);
}
In my case, I needed to watch a service, which contains an address object also watched by several other controllers. I was stuck in a loop until I added the 'true' parameter, which seems to be the key to success when watching objects.
$scope.$watch(function() {
return LocationService.getAddress();
}, function(address) {
//handle address object
}, true);
When everything else fails try editing the file
/.git/info/exclude
and adding the directories you want to the end of the file, like this:
# git ls-files --others --exclude-from=.git/info/exclude
# Lines that start with '#' are comments.
# For a project mostly in C, the following would be a good set of
# exclude patterns (uncomment them if you want to use them):
# *.[oa]
# *~
assets/
compiled/
I added the folders "assets" and "compiled" to the list of files and directories to ignore.
I am a beginner to screen but I find it immensely useful while restoring lost connections. Your question has already been answered but this information might serve as an add on - I use putty with putty connection manager and name my screens - "tab1", "tab2", etc. - as for me the overall picture of the 8-10 tabs is more important than each individual tab name. I use the 8th tab for connecting to db, the 7th for viewing logs, etc. So when I want to reattach my screens I have written a simple wrapper which says:
#!/bin/bash
screen -d -r tab$1
where first argument is the tab number.
PostreSQL apparently converts column names to lower case in a sql query - I've seen issues where mixed case column names will give that error. You can fix it by putting the column name in quotation marks:
SELECT * FROM table_name where "Foo" IS NULL
Cshtml files are the ones used by Razor and as stated as answer for this question, their main advantage is that they can be rendered inside unit tests. The various answers to this other topic will bring a lot of other interesting points.
Here is a JS function that converts "Country Code" (ISO3) to Telephone "Calling Code":
function country_iso3_to_country_calling_code(country_iso3) {
if(country_iso3 == 'AFG') return '93';
if(country_iso3 == 'ALB') return '355';
if(country_iso3 == 'DZA') return '213';
if(country_iso3 == 'ASM') return '1684';
if(country_iso3 == 'AND') return '376';
if(country_iso3 == 'AGO') return '244';
if(country_iso3 == 'AIA') return '1264';
if(country_iso3 == 'ATA') return '672';
if(country_iso3 == 'ATG') return '1268';
if(country_iso3 == 'ARG') return '54';
if(country_iso3 == 'ARM') return '374';
if(country_iso3 == 'ABW') return '297';
if(country_iso3 == 'AUS') return '61';
if(country_iso3 == 'AUT') return '43';
if(country_iso3 == 'AZE') return '994';
if(country_iso3 == 'BHS') return '1242';
if(country_iso3 == 'BHR') return '973';
if(country_iso3 == 'BGD') return '880';
if(country_iso3 == 'BRB') return '1246';
if(country_iso3 == 'BLR') return '375';
if(country_iso3 == 'BEL') return '32';
if(country_iso3 == 'BLZ') return '501';
if(country_iso3 == 'BEN') return '229';
if(country_iso3 == 'BMU') return '1441';
if(country_iso3 == 'BTN') return '975';
if(country_iso3 == 'BOL') return '591';
if(country_iso3 == 'BIH') return '387';
if(country_iso3 == 'BWA') return '267';
if(country_iso3 == 'BVT') return '_55';
if(country_iso3 == 'BRA') return '55';
if(country_iso3 == 'IOT') return '1284';
if(country_iso3 == 'BRN') return '673';
if(country_iso3 == 'BGR') return '359';
if(country_iso3 == 'BFA') return '226';
if(country_iso3 == 'BDI') return '257';
if(country_iso3 == 'KHM') return '855';
if(country_iso3 == 'CMR') return '237';
if(country_iso3 == 'CAN') return '1';
if(country_iso3 == 'CPV') return '238';
if(country_iso3 == 'CYM') return '1345';
if(country_iso3 == 'CAF') return '236';
if(country_iso3 == 'TCD') return '235';
if(country_iso3 == 'CHL') return '56';
if(country_iso3 == 'CHN') return '86';
if(country_iso3 == 'CXR') return '618';
if(country_iso3 == 'CCK') return '61';
if(country_iso3 == 'COL') return '57';
if(country_iso3 == 'COM') return '269';
if(country_iso3 == 'COG') return '242';
if(country_iso3 == 'COD') return '243';
if(country_iso3 == 'COK') return '682';
if(country_iso3 == 'CRI') return '506';
if(country_iso3 == 'HRV') return '385';
if(country_iso3 == 'CUB') return '53';
if(country_iso3 == 'CYP') return '357';
if(country_iso3 == 'CZE') return '420';
if(country_iso3 == 'DNK') return '45';
if(country_iso3 == 'DJI') return '253';
if(country_iso3 == 'DMA') return '1767';
if(country_iso3 == 'DOM') return '1';
if(country_iso3 == 'ECU') return '593';
if(country_iso3 == 'EGY') return '20';
if(country_iso3 == 'SLV') return '503';
if(country_iso3 == 'GNQ') return '240';
if(country_iso3 == 'ERI') return '291';
if(country_iso3 == 'EST') return '372';
if(country_iso3 == 'ETH') return '251';
if(country_iso3 == 'FLK') return '500';
if(country_iso3 == 'FRO') return '298';
if(country_iso3 == 'FJI') return '679';
if(country_iso3 == 'FIN') return '358';
if(country_iso3 == 'FRA') return '33';
if(country_iso3 == 'GUF') return '594';
if(country_iso3 == 'PYF') return '689';
if(country_iso3 == 'GAB') return '241';
if(country_iso3 == 'GMB') return '220';
if(country_iso3 == 'GEO') return '995';
if(country_iso3 == 'DEU') return '49';
if(country_iso3 == 'GHA') return '233';
if(country_iso3 == 'GIB') return '350';
if(country_iso3 == 'GRC') return '30';
if(country_iso3 == 'GRL') return '299';
if(country_iso3 == 'GRD') return '1473';
if(country_iso3 == 'GLP') return '590';
if(country_iso3 == 'GUM') return '1671';
if(country_iso3 == 'GTM') return '502';
if(country_iso3 == 'GIN') return '224';
if(country_iso3 == 'GNB') return '245';
if(country_iso3 == 'GUY') return '592';
if(country_iso3 == 'HTI') return '509';
if(country_iso3 == 'HMD') return '61';
if(country_iso3 == 'VAT') return '3';
if(country_iso3 == 'HND') return '504';
if(country_iso3 == 'HKG') return '852';
if(country_iso3 == 'HUN') return '36';
if(country_iso3 == 'ISL') return '354';
if(country_iso3 == 'IND') return '91';
if(country_iso3 == 'IDN') return '62';
if(country_iso3 == 'IRN') return '98';
if(country_iso3 == 'IRQ') return '964';
if(country_iso3 == 'IRL') return '353';
if(country_iso3 == 'ISR') return '972';
if(country_iso3 == 'ITA') return '39';
if(country_iso3 == 'CIV') return '225';
if(country_iso3 == 'JAM') return '1876';
if(country_iso3 == 'JPN') return '81';
if(country_iso3 == 'JOR') return '962';
if(country_iso3 == 'KAZ') return '7';
if(country_iso3 == 'KEN') return '254';
if(country_iso3 == 'KIR') return '686';
if(country_iso3 == 'PRK') return '850';
if(country_iso3 == 'KOR') return '82';
if(country_iso3 == 'KWT') return '965';
if(country_iso3 == 'KGZ') return '7';
if(country_iso3 == 'LAO') return '856';
if(country_iso3 == 'LVA') return '371';
if(country_iso3 == 'LBN') return '961';
if(country_iso3 == 'LSO') return '266';
if(country_iso3 == 'LBR') return '231';
if(country_iso3 == 'LBY') return '218';
if(country_iso3 == 'LIE') return '423';
if(country_iso3 == 'LTU') return '370';
if(country_iso3 == 'LUX') return '352';
if(country_iso3 == 'MAC') return '853';
if(country_iso3 == 'MKD') return '389';
if(country_iso3 == 'MDG') return '261';
if(country_iso3 == 'MWI') return '265';
if(country_iso3 == 'MYS') return '60';
if(country_iso3 == 'MDV') return '960';
if(country_iso3 == 'MLI') return '223';
if(country_iso3 == 'MLT') return '356';
if(country_iso3 == 'MHL') return '692';
if(country_iso3 == 'MTQ') return '596';
if(country_iso3 == 'MRT') return '222';
if(country_iso3 == 'MUS') return '230';
if(country_iso3 == 'MYT') return '262';
if(country_iso3 == 'MEX') return '52';
if(country_iso3 == 'FSM') return '691';
if(country_iso3 == 'MDA') return '373';
if(country_iso3 == 'MCO') return '377';
if(country_iso3 == 'MNG') return '976';
if(country_iso3 == 'MSR') return '1664';
if(country_iso3 == 'MAR') return '212';
if(country_iso3 == 'MOZ') return '258';
if(country_iso3 == 'MMR') return '95';
if(country_iso3 == 'NAM') return '264';
if(country_iso3 == 'NRU') return '674';
if(country_iso3 == 'NPL') return '977';
if(country_iso3 == 'NLD') return '31';
if(country_iso3 == 'ANT') return '599';
if(country_iso3 == 'NCL') return '687';
if(country_iso3 == 'NZL') return '64';
if(country_iso3 == 'NIC') return '505';
if(country_iso3 == 'NER') return '227';
if(country_iso3 == 'NGA') return '234';
if(country_iso3 == 'NIU') return '683';
if(country_iso3 == 'NFK') return '672';
if(country_iso3 == 'MNP') return '1670';
if(country_iso3 == 'NOR') return '47';
if(country_iso3 == 'OMN') return '968';
if(country_iso3 == 'PAK') return '92';
if(country_iso3 == 'PLW') return '680';
if(country_iso3 == 'PSE') return '970';
if(country_iso3 == 'PAN') return '507';
if(country_iso3 == 'PNG') return '675';
if(country_iso3 == 'PRY') return '595';
if(country_iso3 == 'PER') return '51';
if(country_iso3 == 'PHL') return '63';
if(country_iso3 == 'PCN') return '870';
if(country_iso3 == 'POL') return '48';
if(country_iso3 == 'PRT') return '351';
if(country_iso3 == 'PRI') return '1';
if(country_iso3 == 'QAT') return '974';
if(country_iso3 == 'REU') return '262';
if(country_iso3 == 'ROM') return '40';
if(country_iso3 == 'RUS') return '7';
if(country_iso3 == 'RWA') return '250';
if(country_iso3 == 'SHN') return '290';
if(country_iso3 == 'KNA') return '1869';
if(country_iso3 == 'LCA') return '1758';
if(country_iso3 == 'SPM') return '508';
if(country_iso3 == 'VCT') return '1758';
if(country_iso3 == 'WSM') return '685';
if(country_iso3 == 'SMR') return '378';
if(country_iso3 == 'STP') return '239';
if(country_iso3 == 'SAU') return '966';
if(country_iso3 == 'SEN') return '221';
if(country_iso3 == 'SRB') return '381';
if(country_iso3 == 'SYC') return '248';
if(country_iso3 == 'SLE') return '232';
if(country_iso3 == 'SGP') return '65';
if(country_iso3 == 'SVK') return '421';
if(country_iso3 == 'SVN') return '386';
if(country_iso3 == 'SLB') return '677';
if(country_iso3 == 'SOM') return '252';
if(country_iso3 == 'ZAF') return '27';
if(country_iso3 == 'SGS') return '44';
if(country_iso3 == 'ESP') return '34';
if(country_iso3 == 'LKA') return '94';
if(country_iso3 == 'SDN') return '249';
if(country_iso3 == 'SUR') return '597';
if(country_iso3 == 'SJM') return '47';
if(country_iso3 == 'SWZ') return '268';
if(country_iso3 == 'SWE') return '46';
if(country_iso3 == 'CHE') return '41';
if(country_iso3 == 'SYR') return '963';
if(country_iso3 == 'TWN') return '886';
if(country_iso3 == 'TJK') return '992';
if(country_iso3 == 'TZA') return '255';
if(country_iso3 == 'THA') return '66';
if(country_iso3 == 'TLS') return '670';
if(country_iso3 == 'TGO') return '228';
if(country_iso3 == 'TKL') return '690';
if(country_iso3 == 'TON') return '676';
if(country_iso3 == 'TTO') return '1868';
if(country_iso3 == 'TUN') return '216';
if(country_iso3 == 'TUR') return '90';
if(country_iso3 == 'TKM') return '993';
if(country_iso3 == 'TCA') return '1649';
if(country_iso3 == 'TUV') return '688';
if(country_iso3 == 'UGA') return '256';
if(country_iso3 == 'UKR') return '380';
if(country_iso3 == 'ARE') return '971';
if(country_iso3 == 'GBR') return '44';
if(country_iso3 == 'USA') return '1';
if(country_iso3 == 'UMI') return '1340';
if(country_iso3 == 'URY') return '598';
if(country_iso3 == 'UZB') return '998';
if(country_iso3 == 'VUT') return '678';
if(country_iso3 == 'VEN') return '58';
if(country_iso3 == 'VNM') return '84';
if(country_iso3 == 'VGB') return '1284';
if(country_iso3 == 'VIR') return '1340';
if(country_iso3 == 'WLF') return '681';
if(country_iso3 == 'YEM') return '260';
if(country_iso3 == 'ZMB') return '260';
if(country_iso3 == 'ZWE') return '263';
}
Note: "schtasks" (see the other, accepted response) has replaced "at". However, "at" may be of use if the situation calls for compatibility with older versions of Windows that don't have schtasks.
Command-line help for "at":
C:\>at /? The AT command schedules commands and programs to run on a computer at a specified time and date. The Schedule service must be running to use the AT command. AT [\\computername] [ [id] [/DELETE] | /DELETE [/YES]] AT [\\computername] time [/INTERACTIVE] [ /EVERY:date[,...] | /NEXT:date[,...]] "command" \\computername Specifies a remote computer. Commands are scheduled on the local computer if this parameter is omitted. id Is an identification number assigned to a scheduled command. /delete Cancels a scheduled command. If id is omitted, all the scheduled commands on the computer are canceled. /yes Used with cancel all jobs command when no further confirmation is desired. time Specifies the time when command is to run. /interactive Allows the job to interact with the desktop of the user who is logged on at the time the job runs. /every:date[,...] Runs the command on each specified day(s) of the week or month. If date is omitted, the current day of the month is assumed. /next:date[,...] Runs the specified command on the next occurrence of the day (for example, next Thursday). If date is omitted, the current day of the month is assumed. "command" Is the Windows NT command, or batch program to be run.
The ALL_DIRECTORIES
data dictionary view will have information about all the directories that you have access to. That includes the operating system path
SELECT owner, directory_name, directory_path
FROM all_directories
I know this is an old question but I stumbled upon this recently and it ended up misguiding me since the Subprocess API as changed since python 3.5.
The new way to execute external scripts is with the run
function, which runs the command described by args. Waits for command to complete, then returns a CompletedProcess instance.
import subprocess
subprocess.run(['./test.sh'])
There might be several reasons for this.
1.database set 1st single user mode
ALTER DATABASE BOSEVIKRAM SET SINGLE_USER WITH ROLLBACK IMMEDIATE
2.RENAME THE DATABASE
ALTER DATABASE BOSEVIKRAM MODIFY NAME = [BOSEVIKRAM_Deleted]
3.DATABAE SET MULIUSER MODE
ALTER DATABASE BOSEVIKRAM_Deleted SET MULTI_USER WITH ROLLBACK IMMEDIATE
Wouldn't Collections.disjoint(A, B)
work? From the documentation:
Returns
true
if the two specified collections have no elements in common.
Thus, the method returns false
if the collections contains any common elements.
If you're on Linux, or have cygwin available on Windows, you can run the input XML through a simple sed script that will replace <Active>True</Active>
with <Active>true</Active>
, like so:
cat <your XML file> | sed 'sX<Active>True</Active>X<Active>true</Active>X' | xmllint --schema -
If you're not, you can still use a non-validating xslt pocessor (xalan, saxon etc.) to run a simple xslt transformation on the input, and only then pipe it to xmllint.
What the xsl should contain something like below, for the example you listed above (the xslt processor should be 2.0 capable):
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<xsl:for-each select="XML">
<xsl:for-each select="Active">
<xsl:value-of select=" replace(current(), 'True','true')"/>
</xsl:for-each>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Let the resolver automatically do that.
Inside A controller:
public class AController : ApiController
{
private readonly BController _bController;
public AController(
BController bController)
{
_bController = bController;
}
public httpMethod{
var result = _bController.OtherMethodBController(parameters);
....
}
}
You can also try jQuery based method:
$(document).ready(function() {
$('form:first *:input[type!=hidden]:first').focus();
});
Just load it into a new object on process .. process.gulp = {}
and have the task look there.
Create a new custom object and add it to the object array that Import-Csv
creates.
$fileContent = Import-csv $file -header "Date", "Description"
$newRow = New-Object PsObject -Property @{ Date = 'Text4' ; Description = 'Text5' }
$fileContent += $newRow
Another great tool is KeyStore Explorer: http://keystore-explorer.sourceforge.net/
It refers to the instance of the current class, as meder said.
See the PHP Docs. It's explained under the first example.
The []
syntax for getting item by key or index is just syntax sugar.
When you evaluate a[i]
Python calls a.__getitem__(i)
(or type(a).__getitem__(a, i)
, but this distinction is about inheritance models and is not important here). Even if the class of a
may not explicitly define this method, it is usually inherited from an ancestor class.
All the (Python 2.7) special method names and their semantics are listed here: https://docs.python.org/2.7/reference/datamodel.html#special-method-names
In newer versions of MySQL connectors the default tables are also listed if catalog is not passed
DatabaseMetaData dbMeta = con.getMetaData();
//con.getCatalog() returns database name
ResultSet rs = dbMeta.getTables(con.getCatalog(), "", null, new String[]{"TABLE"});
ArrayList<String> tables = new ArrayList<String>();
while(rs.next()){
String tableName = rs.getString("TABLE_NAME");
tables.add(tableName);
}
return tables;
The R packages dplyr and sf import the operator %>% from the R package magrittr.
Help is available by using the following command:
?'%>%'
Of course the package must be loaded before by using e.g.
library(sf)
The documentation of the magrittr forward-pipe operator gives a good example: When functions require only one argument, x %>% f is equivalent to f(x)
//Multiple selection:
private void clbsec(CheckedListBox clb, string text)
{
for (int i = 0; i < clb.Items.Count; i++)
{
if(text == clb.Items[i].ToString())
{
clb.SetItemChecked(i, true);
}
}
}
using ==>
clbsec(checkedListBox1,"michael");
or
clbsec(checkedListBox1,textBox1.Text);
or
clbsec(checkedListBox1,dataGridView1.CurrentCell.Value.toString());
Here's possibly the simplest way:
IO.copy_stream(URI.open("https://i.pinimg.com/originals/24/17/d6/2417d6b3f3dc236b0b5b80fb00b3a791.png"), 'destination.png')
Rather than making a bunch of global variables, you might consider creating a class that has a bunch of public static constants. It's still global, but this way it's wrapped in a class so you know where the constant is coming from and that it's supposed to be a constant.
Constants.h
#ifndef CONSTANTS_H
#define CONSTANTS_H
class GlobalConstants {
public:
static const int myConstant;
static const int myOtherConstant;
};
#endif
Constants.cpp
#include "Constants.h"
const int GlobalConstants::myConstant = 1;
const int GlobalConstants::myOtherConstant = 3;
Then you can use this like so:
#include "Constants.h"
void foo() {
int foo = GlobalConstants::myConstant;
}
first import os module in your app than with use from getpid function get pid's app and save in a file.for example :
import os
pid = os.getpid()
op = open("/var/us.pid","w")
op.write("%s" % pid)
op.close()
and create a bash file in /etc/init.d path: /etc/init.d/servername
PATHAPP="/etc/bin/userscript.py &"
PIDAPP="/var/us.pid"
case $1 in
start)
echo "starting"
$(python $PATHAPP)
;;
stop)
echo "stoping"
PID=$(cat $PIDAPP)
kill $PID
;;
esac
now , u can start and stop ur app with down command:
service servername stop service servername start
or
/etc/init.d/servername stop /etc/init.d/servername start
HTML5 introduces FormData
class that can be used to file upload with ajax.
FormData support starts from following desktop browsers versions. IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+
You can use my libary called RDALogger. Here is github link.
With this library, you can log your message with method name/class name/line number and anchor link. With this link, when you click log, screen goes to this line of code.
To use library, you must do implementations below.
in root level gradle
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
in app level gradle
dependencies {
implementation 'com.github.ardakaplan:RDALogger:1.0.0'
}
For initializing library, you should start like this (in Application.class or before first use)
RDALogger.start("TAG NAME").enableLogging(true);
And than you can log whatever you want;
RDALogger.info("info");
RDALogger.debug("debug");
RDALogger.verbose("verbose");
RDALogger.warn("warn");
RDALogger.error("error");
RDALogger.error(new Throwable());
RDALogger.error("error", new Throwable());
And finally output shows you all you want (class name, method name, anchor link, message)
08-09 11:13:06.023 20025-20025/com.ardakaplan.application I/Application: IN CLASS : (ENApplication.java:29) /// IN METHOD : onCreate
info
If for example, it is an Ubuntu, after installing the packages:
$sudo apt install golang -y
Just add the following lines to ~/.bashrc (Of your user)
export GOROOT=/usr/lib/go
export GOPATH=$HOME/go
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin
There is big difference between dot (".")
and text()
:-
The dot (".")
in XPath
is called the "context item expression" because it refers to the context item. This could be match with a node (such as an element
, attribute
, or text node
) or an atomic value (such as a string
, number
, or boolean
). While text()
refers to match only element text
which is in string
form.
The dot (".")
notation is the current node in the DOM. This is going to be an object of type Node while Using the XPath
function text() to get the text for an element only gets the text up to the first inner element. If the text you are looking for is after the inner element you must use the current node to search for the string and not the XPath
text() function.
For an example :-
<a href="something.html">
<img src="filename.gif">
link
</a>
Here if you want to find anchor a
element by using text link, you need to use dot (".")
. Because if you use //a[contains(.,'link')]
it finds the anchor a
element but if you use //a[contains(text(),'link')]
the text()
function does not seem to find it.
Hope it will help you..:)
SHA1
is a cryptographic hash function, so the intention of the design was to avoid what you are trying to do.
However, breaking a SHA1
hash is technically possible. You can do so by just trying to guess what was hashed. This brute-force approach is of course not efficient, but that's pretty much the only way.
So to answer your question: yes, it is possible, but you need significant computing power. Some researchers estimate that it costs $70k - $120k.
As far as we can tell today, there is also no other way but to guess the hashed input. This is because operations such as mod
eliminate information from your input. Suppose you calculate mod 5
and you get 0
. What was the input? Was it 0
, 5
or 500
? You see, you can't really 'go back' in this case.
I solved this using attribute minChars:0 and after, trigger two clicks. (autocomplete shows after 1 click on input) my code
<input type='text' onfocus='setAutocomplete(this)'>
function setAutocomplete(el){
$(el).unbind().autocomplete("./index.php", {autoFill:false, minChars:0, matchContains:true, max:20});
$(el).trigger("click");$(el).trigger("click");
}
If it is a GET service, then you need to use it with a GET method, not a POST method. Your problem is a type mismatch. A different example of type mismatch (to put severity into perspective) is trying to assign a string to an integer variable.
You can also check if any process is using this file and show a list of programs you must close to continue like an installer does.
public static string GetFileProcessName(string filePath)
{
Process[] procs = Process.GetProcesses();
string fileName = Path.GetFileName(filePath);
foreach (Process proc in procs)
{
if (proc.MainWindowHandle != new IntPtr(0) && !proc.HasExited)
{
ProcessModule[] arr = new ProcessModule[proc.Modules.Count];
foreach (ProcessModule pm in proc.Modules)
{
if (pm.ModuleName == fileName)
return proc.ProcessName;
}
}
}
return null;
}
You must handle ArrayIndexOutOfBounds by yourself when adding to a certain position.
For convenience, you may use this extension function in Kotlin
/**
* Adds an [element] to index [index] or to the end of the List in case [index] is out of bounds
*/
fun <T> MutableList<T>.insert(index: Int, element: T) {
if (index <= size) {
add(index, element)
} else {
add(element)
}
}
In your request options, try including the following:
var req = https.request({
host: '192.168.1.1',
port: 443,
path: '/',
method: 'GET',
rejectUnauthorized: false,
requestCert: true,
agent: false
},
if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:
If x and/or y is 2-dimensional, then the corresponding columns will be plotted.
In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:
np.squeez doc: Remove single-dimensional entries from the shape of an array.
import numpy as np
import matplotlib.pyplot as plt
data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()
But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:
Edit /etc/paths
. Then close the terminal and reopen it.
$ sudo vi /etc/paths
Note: each entry is seperated by line breaks.
/usr/local/bin
/usr/bin
/bin
/usr/sbin
/sbin
Even if it is really discouraged to use merge cells in Excel (use Center Across Selection
for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).
Hence, you can get the value of merged cells in range B4:B11
in several ways:
Range("B4").Value
Range("B4:B11").Cells(1).Value
Range("B4:B11").Cells(1,1).Value
You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty
.
Also note that Range("B4:B11").Value
won't work (raises an execution error number 13 if you try to Debug.Print
it) because it returns an array.
require.paths
is deprecated.
Go to your project folder and type
npm install socket.io
that should install it in the local ./node_modules folder where node will look for it.
I keep my things like this:
cd ~/Sites/
mkdir sweetnodeproject
cd sweetnodeproject
npm install socket.io
Create an app.js file
// app.js
var socket = require('socket.io')
now run my app
node app.js
Make sure you're using npm >= 1.0
and node >= 4.0
.
The dispatch_async(dispatch_get_main_queue())
method above is not guaranteed to work. I'm seeing non-deterministic behavior with it, in which sometimes the system has completed the layoutSubviews and the cell rendering before the completion block, and sometimes after.
Here's a solution that works 100% for me, on iOS 10. It requires the ability to instantiate the UITableView or UICollectionView as a custom subclass. Here's the UICollectionView solution, but it's exactly the same for UITableView:
CustomCollectionView.h:
#import <UIKit/UIKit.h>
@interface CustomCollectionView: UICollectionView
- (void)reloadDataWithCompletion:(void (^)(void))completionBlock;
@end
CustomCollectionView.m:
#import "CustomCollectionView.h"
@interface CustomCollectionView ()
@property (nonatomic, copy) void (^reloadDataCompletionBlock)(void);
@end
@implementation CustomCollectionView
- (void)reloadDataWithCompletion:(void (^)(void))completionBlock
{
self.reloadDataCompletionBlock = completionBlock;
[self reloadData];
}
- (void)layoutSubviews
{
[super layoutSubviews];
if (self.reloadDataCompletionBlock) {
self.reloadDataCompletionBlock();
self.reloadDataCompletionBlock = nil;
}
}
@end
Example usage:
[self.collectionView reloadDataWithCompletion:^{
// reloadData is guaranteed to have completed
}];
See here for a Swift version of this answer
Don't forget the awesome
git fetch -p
which fetches and prunes all origins.
One of the answers in the question referred to by @Z.Bagley gave me the answer. I had to import Renderer2 from @angular/core into my component. Then:
const element = this.renderer.selectRootElement('#input1');
// setTimeout(() => element.focus, 0);
setTimeout(() => element.focus(), 0);
Thank you @MrBlaise for the solution!
This is the Formula of loop of Enumeration:
for (index, value) in shoppingList.enumerate() {
print("Item \(index + 1): \(value)")
}
for more detail you can check Here.
You can get the content of a MultipartFile
by using the getBytes
method and you can write to the file using Files.newOutputStream()
:
public void write(MultipartFile file, Path dir) {
Path filepath = Paths.get(dir.toString(), file.getOriginalFilename());
try (OutputStream os = Files.newOutputStream(filepath)) {
os.write(file.getBytes());
}
}
You can also use the transferTo method:
public void multipartFileToFile(
MultipartFile multipart,
Path dir
) throws IOException {
Path filepath = Paths.get(dir.toString(), multipart.getOriginalFilename());
multipart.transferTo(filepath);
}
One way would be to create an ObservableCollection (System.Collections.ObjectModel) and have your dictionary data in there. Then you should be able to bind the ObservableCollection to your ListBox.
In your XAML you should have something like this:
<ListBox ItemsSource="{Binding Path=Name_of_your_ObservableCollection" />
For adding argument to delay function.
First setup a dictionary then add it as the userInfo. Unwrap the info with the timer as the argument.
let arg : Int = 42
let infoDict : [String : AnyObject] = ["argumentInt", arg]
NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(3), target: self, selector: "functionHereWithArgument:", userInfo: infoDict, repeats: false)
Then in the called function
func functionHereWithArgument (timer : NSTimer)
{
if let userInfo = timer.userInfo as? Dictionary<String, AnyObject>
{
let argumentInt : Int = (userInfo[argumentInt] as! Int)
}
}
Thanks to galloglass' answer. The code works great with Python 2.7. There is only one thing I want to metion. When read the manifest.mbdb file, you should use binary mode. Otherwise, not all content are read.
I also made some minor changes to make the code work with Python 3.4. Here is the code.
#!/usr/bin/env python
import sys
import hashlib
mbdx = {}
def getint(data, offset, intsize):
"""Retrieve an integer (big-endian) and new offset from the current offset"""
value = 0
while intsize > 0:
value = (value << 8) + data[offset]
offset = offset + 1
intsize = intsize - 1
return value, offset
def getstring(data, offset):
"""Retrieve a string and new offset from the current offset into the data"""
if chr(data[offset]) == chr(0xFF) and chr(data[offset + 1]) == chr(0xFF):
return '', offset + 2 # Blank string
length, offset = getint(data, offset, 2) # 2-byte length
value = data[offset:offset + length]
return value.decode(encoding='latin-1'), (offset + length)
def process_mbdb_file(filename):
mbdb = {} # Map offset of info in this file => file info
data = open(filename, 'rb').read() # 'b' is needed to read all content at once
if data[0:4].decode() != "mbdb": raise Exception("This does not look like an MBDB file")
offset = 4
offset = offset + 2 # value x05 x00, not sure what this is
while offset < len(data):
fileinfo = {}
fileinfo['start_offset'] = offset
fileinfo['domain'], offset = getstring(data, offset)
fileinfo['filename'], offset = getstring(data, offset)
fileinfo['linktarget'], offset = getstring(data, offset)
fileinfo['datahash'], offset = getstring(data, offset)
fileinfo['unknown1'], offset = getstring(data, offset)
fileinfo['mode'], offset = getint(data, offset, 2)
fileinfo['unknown2'], offset = getint(data, offset, 4)
fileinfo['unknown3'], offset = getint(data, offset, 4)
fileinfo['userid'], offset = getint(data, offset, 4)
fileinfo['groupid'], offset = getint(data, offset, 4)
fileinfo['mtime'], offset = getint(data, offset, 4)
fileinfo['atime'], offset = getint(data, offset, 4)
fileinfo['ctime'], offset = getint(data, offset, 4)
fileinfo['filelen'], offset = getint(data, offset, 8)
fileinfo['flag'], offset = getint(data, offset, 1)
fileinfo['numprops'], offset = getint(data, offset, 1)
fileinfo['properties'] = {}
for ii in range(fileinfo['numprops']):
propname, offset = getstring(data, offset)
propval, offset = getstring(data, offset)
fileinfo['properties'][propname] = propval
mbdb[fileinfo['start_offset']] = fileinfo
fullpath = fileinfo['domain'] + '-' + fileinfo['filename']
id = hashlib.sha1(fullpath.encode())
mbdx[fileinfo['start_offset']] = id.hexdigest()
return mbdb
def modestr(val):
def mode(val):
if (val & 0x4):
r = 'r'
else:
r = '-'
if (val & 0x2):
w = 'w'
else:
w = '-'
if (val & 0x1):
x = 'x'
else:
x = '-'
return r + w + x
return mode(val >> 6) + mode((val >> 3)) + mode(val)
def fileinfo_str(f, verbose=False):
if not verbose: return "(%s)%s::%s" % (f['fileID'], f['domain'], f['filename'])
if (f['mode'] & 0xE000) == 0xA000:
type = 'l' # symlink
elif (f['mode'] & 0xE000) == 0x8000:
type = '-' # file
elif (f['mode'] & 0xE000) == 0x4000:
type = 'd' # dir
else:
print >> sys.stderr, "Unknown file type %04x for %s" % (f['mode'], fileinfo_str(f, False))
type = '?' # unknown
info = ("%s%s %08x %08x %7d %10d %10d %10d (%s)%s::%s" %
(type, modestr(f['mode'] & 0x0FFF), f['userid'], f['groupid'], f['filelen'],
f['mtime'], f['atime'], f['ctime'], f['fileID'], f['domain'], f['filename']))
if type == 'l': info = info + ' -> ' + f['linktarget'] # symlink destination
for name, value in f['properties'].items(): # extra properties
info = info + ' ' + name + '=' + repr(value)
return info
verbose = True
if __name__ == '__main__':
mbdb = process_mbdb_file(
r"Manifest.mbdb")
for offset, fileinfo in mbdb.items():
if offset in mbdx:
fileinfo['fileID'] = mbdx[offset]
else:
fileinfo['fileID'] = "<nofileID>"
print >> sys.stderr, "No fileID found for %s" % fileinfo_str(fileinfo)
print(fileinfo_str(fileinfo, verbose))
Use parseJSON
. Look at the doc
var obj = $.parseJSON(data);
Something like this:
$.ajax({
type: "POST",
url: '/admin/systemgoalssystemgoalupdate?format=html',
data: formdata,
success: function (data) {
console.log($.parseJSON(data)); //will log Object
}
});
Add this line of code in your res/value/styles.xml
<item name="android:fontFamily">@font/circular_medium</item>
the entire style will look like that
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:fontFamily">@font/circular_medium</item>
</style>
change "circular_medium" to your own font name..
this is how I do it.
char[] myEmptyCharArray = "".toCharArray();
There is a much simpler way. Put your picture in a comment box within the description cell. That way you only have one column and when you sort the picture will always stay with the description. Okay... Right click the cell containing the description... Insert comment...right click the outer border... Format comment...colours and lines tab... Colour drop down...Fill effects...Picture tab...select picture...browse for your picture (it might be best to keep all pictures in one folder for ease of placement)...ok... you will probably need to go to the size tab and frig around with the height and width. Done... You now only need to mouse over the red in the top right corner of the cell and the picture will appear...like magic.
This method means that the row height can be kept to a minimum and the pictures can be as big as you like.
We can use attribute selector in DOM by using document.querySelector()
and document.querySelectorAll()
methods.
for yours:
document.querySelector("[myAttribute='aValue']");
and by using querySelectorAll()
:
document.querySelectorAll("[myAttribute='aValue']");
In querySelector()
and querySelectorAll()
methods we can select objects as we select in "CSS".
More about "CSS" attribute selectors in https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
I found mpdf better than tcpdf in terms of html rendering. It can parse css styles much better and create pdf that look very similar to the original html.
mpdf even supports css things like border-radius and gradient etc.
I am surprised to see why mpdf is so less talked about when it comes to html to pdf.
Check out the examples here http://www.mpdf1.com/mpdf/index.php?page=Examples
I found it useful for designing invoices, receipts and simple prints etc. However the website itself says that pdfs generated from mpdf tend to be larger in size.
In Bash, I would use the following one-liner:
[[ "${str}" == \"*\" || "${str}" == \'*\' ]] && str="${str:1:-1}"
This will remove surrounding quotes (both single and double) while keeping quoting characters inside the string intact. Also, it won't do anything if there's only a single leading quote or only a single trailing quote, which is usually what you want in my experience.
Wrapped in a function:
#!/usr/bin/env bash
# Strip surrounding quotes from string [$1: variable name]
function strip_quotes() {
local -n var="$1"
[[ "${var}" == \"*\" || "${var}" == \'*\' ]] && var="${var:1:-1}"
}
str="$*"
echo "Before: ${str}"
strip_quotes str
echo "After: ${str}"
Default value doesn't mean default value of data type .Here default value mean value defined at the time of defining function. we have to declare default value of variable while defining variable in function.
Run ---> Debug Configuration ---> YourConfiguration ---> Arguments tab
If spring-security
jars are added in classpath and also if it is spring-boot
application all http endpoints will be secured by default security configuration class SecurityAutoConfiguration
This causes a browser pop-up to ask for credentials.
The password changes for each application restarts and can be found in console.
Using default security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35
To add your own layer of application security in front of the defaults,
@EnableWebSecurity
public class SecurityConfig {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
or if you just want to change password you could override default with,
application.xml
security.user.password=new_password
or
application.properties
spring.security.user.name=<>
spring.security.user.password=<>
For me, it worked once I changed
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
to:
in POM
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.1.0.jre8</version>
</dependency>
and then:
import com.microsoft.sqlserver.jdbc.SQLServerDriver;
...
DriverManager.registerDriver(SQLServerDriver());
Connection connection = DriverManager.getConnection(connectionUrl);