You can also use ls
with grep
or egrep
and put it in your profile as an alias:
ls -l | egrep -v '^d'
ls -l | grep -v '^d'
The simplified Java 8 way:
map.put(key, map.getOrDefault(key, 0) + 1);
This uses the method of HashMap that retrieves the value for a key, but if the key can't be retrieved it returns the specified default value (in this case a '0').
This is supported within core Java: HashMap<K,V> getOrDefault(Object key, V defaultValue)
You can use
DispatchQueue.main.asyncAfter(deadline: .now() + .microseconds(100)) {
// Code
}
Just because I haven't seen it here, if you are on MacOS or Linux, I suggest you add this to your PATH (in your bashrc etc):
node_modules/.bin
With this relative path entry, if you are sitting in the root folder of any node project, you can run any command line tool (eslint, gulp, etc. etc.) without worrying about "global installs" or npm run
etc.
Once I did this, I've never installed a module globally.
As per macOS 10.14.5, below are the details:
Go to
system preferences > sharing > remote login.
if it is coming from server as object you can do
this.service.subscribe(data:any) keep any type on data it will solve the issue
Small performance test comparision for three solutions:
$(".link").prop('href',"https://example.com")
$(".link").attr('href',"https://example.com")
document.querySelector(".link").href="https://example.com";
Here you can perform test by yourself https://jsperf.com/a-href-js-change
We can read href values in following ways
let href = $(selector).prop('href');
let href = $(selector).attr('href');
let href = document.querySelector(".link").href;
Here you can perform test by yourself https://jsperf.com/a-href-js-read
I would use a SpannableString
to change the color.
int colorBlue = getResources().getColor(R.color.blue);
String text = getString(R.string.text);
SpannableString spannable = new SpannableString(text);
// here we set the color
spannable.setSpan(new ForegroundColorSpan(colorBlue), 0, text.length(), 0);
OR you may try this
webView.clearCache(true)
appFormWebView.clearFormData()
appFormWebView.clearHistory()
appFormWebView.clearSslPreferences()
CookieManager.getInstance().removeAllCookies(null)
CookieManager.getInstance().flush()
WebStorage.getInstance().deleteAllData()
Best practice is to mark function async void
only if it is fire and forget method, if you want to await on, you should mark it as async Task
.
In case if you still want to await, then wrap it like so await Task.Run(() => blah())
But to make sure that your new row is accessible in the new table, you need to close the table:
DataTable destination = new DataTable(source.TableName);
destination = source.Clone();
DataRow sourceRow = source.Rows[0];
destination.ImportRow(sourceRow);
Same question as @Dan - why not StringReader ?
If it has to be InputStreamReader, then:
String charset = ...; // your charset
byte[] bytes = string.getBytes(charset);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
InputStreamReader isr = new InputStreamReader(bais);
The correct options are (in increasing order of recommendation):
# Single POSIX test command with -o operator (not recommended anymore).
# Quotes strongly recommended to guard against empty or undefined variables.
while [ "$stats" -gt 300 -o "$stats" -eq 0 ]
# Two POSIX test commands joined in a list with ||.
# Quotes strongly recommended to guard against empty or undefined variables.
while [ "$stats" -gt 300 ] || [ "$stats" -eq 0 ]
# Two bash conditional expressions joined in a list with ||.
while [[ $stats -gt 300 ]] || [[ $stats -eq 0 ]]
# A single bash conditional expression with the || operator.
while [[ $stats -gt 300 || $stats -eq 0 ]]
# Two bash arithmetic expressions joined in a list with ||.
# $ optional, as a string can only be interpreted as a variable
while (( stats > 300 )) || (( stats == 0 ))
# And finally, a single bash arithmetic expression with the || operator.
# $ optional, as a string can only be interpreted as a variable
while (( stats > 300 || stats == 0 ))
Some notes:
Quoting the parameter expansions inside [[ ... ]]
and ((...))
is optional; if the variable is not set, -gt
and -eq
will assume a value of 0.
Using $
is optional inside (( ... ))
, but using it can help avoid unintentional errors. If stats
isn't set, then (( stats > 300 ))
will assume stats == 0
, but (( $stats > 300 ))
will produce a syntax error.
add this also to ur XMl along with listselector..hope it will work
<ListView
android:cacheColorHint="@android:color/transparent"
android:listSelector="@android:color/transparent"/>
verify if You have correct values in child POMs
GroupId
ArtefactId
Version
ngStyle
accepts a map:
$scope.myStyle = {
"width" : "900px",
"background" : "red"
};
You need to update the package list in your Ubuntu:
$ sudo apt-get update
$ sudo apt-get install <package_name>
This is working perfect for me.
$content = simplexml_load_string(
$raw_xml
, null
, LIBXML_NOCDATA
);
When making a call such as a = foo();
, the compiler might push the address of the result structure on the stack and passes it as a "hidden" pointer to the foo()
function. Effectively, it could become something like:
void foo(MyObj *r) {
struct MyObj a;
// ...
*r = a;
}
foo(&a);
However, the exact implementation of this is dependent on the compiler and/or platform. As Carl Norum notes, if the structure is small enough, it might even be passed back completely in a register.
I use when I do a big commit, above all when I remove more files from the repository.. after, the commits are faster
I had similar issues with Angular6 . After going through many posts. I had to import FormsModule as below in app.module.ts .
import {FormsModule} from '@angular/forms';
Then my ngModel tag worked . Please try this.
<select [(ngModel)]='nrSelect' class='form-control'>
<option [ngValue]='47'>47</option>
<option [ngValue]='46'>46</option>
<option [ngValue]='45'>45</option>
</select>
This may or not be related....I started off with the same error mentioned above, started googling, making changes, getting new errors, endless loop.
The change that got me by that error was messing with the Feature Delegation in IIS Manager under the Management section of the server. I'm sorry I can't remember which one I changed, but googling might help.
That got me past the 1st error into a whole new stream of others, some totally nonsensical. (I would get one error when running under a virtual directory, converting it to an application yielded another error, etec etc). What finally solved this series of errors was: IIS manager, Application Pools, DefaultAppPool, Enable 32-Bit applications=True
I had started this app on a 32 bit windows xp box, and I am now running it on a 64Bit Windows 7 box.
So hopefully this helps someone else.
One way for me to understand wildcards is to think that the wildcard isn't specifying the type of the possible objects that given generic reference can "have", but the type of other generic references that it is is compatible with (this may sound confusing...) As such, the first answer is very misleading in it's wording.
In other words, List<? extends Serializable>
means you can assign that reference to other Lists where the type is some unknown type which is or a subclass of Serializable. DO NOT think of it in terms of A SINGLE LIST being able to hold subclasses of Serializable (because that is incorrect semantics and leads to a misunderstanding of Generics).
Following on from chimeric's answer above:
To get ALL the column indices in the df, so i used:
which(!names(df)%in%c())
or store in a list:
indexLst<-which(!names(df)%in%c())
When it comes to using a very long number that may exceed 32 bits to represent, you may use long to make sure that you'll not have strange behavior.
From Java 5 you can use in-boxing and out-boxing features to make the use of int and Integer completely the same. It means that you can do :
int myInt = new Integer(11);
Integer myInt2 = myInt;
The in and out boxing allow you to switch between int and Integer without any additional conversion (same for Long
,Double
,Short
too)
You may use int
all the time, but Integer
contains some helper methods that can help you to do some complex operations with integers (such as Integer.parseInt(String)
)
Access the Session via the thread's HttpContext:-
HttpContext.Current.Session["loginId"]
From the official GitFaq:
Git has a rename command
git mv
, but that is just a convenience. The effect is indistinguishable from removing the file and adding another with different name and the same content
Java 8 now provides the most concise method to get current Unix Timestamp:
Instant.now().getEpochSecond();
Some Google services do not like to be used to much. Quite recently my account was locked because of script, which was sending two e-mails per second to the same user. Google considered it as a spam. So using sleep here is also justified to prevent such situations.
Remove your Gemfile.lock.
Move to bash if you are using zsh.
sudo bash
gem update --system
Now run command bundle to create a new Gemfile.lock file.
Move back to your zsh sudo exec zsh
now run your rake commands.
It's very simple using System.Security.Cryptography.MD5:
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead(filename))
{
return md5.ComputeHash(stream);
}
}
(I believe that actually the MD5 implementation used doesn't need to be disposed, but I'd probably still do so anyway.)
How you compare the results afterwards is up to you; you can convert the byte array to base64 for example, or compare the bytes directly. (Just be aware that arrays don't override Equals
. Using base64 is simpler to get right, but slightly less efficient if you're really only interested in comparing the hashes.)
If you need to represent the hash as a string, you could convert it to hex using BitConverter
:
static string CalculateMD5(string filename)
{
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead(filename))
{
var hash = md5.ComputeHash(stream);
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
}
}
}
Right click on Project>>Properties>>Android and select API Level greater than 15
OR
Add google-play-services_lib to your project by right clicking on project and selecting Project>>Properties>>Android>>Add
Yes it is safe.
There's no harm in deleting a null pointer; it often reduces the number of tests at the tail of a function if the unallocated pointers are initialized to zero and then simply deleted.
Since the previous sentence has caused confusion, an example — which isn't exception safe — of what is being described:
void somefunc(void)
{
SomeType *pst = 0;
AnotherType *pat = 0;
…
pst = new SomeType;
…
if (…)
{
pat = new AnotherType[10];
…
}
if (…)
{
…code using pat sometimes…
}
delete[] pat;
delete pst;
}
There are all sorts of nits that can be picked with the sample code, but the concept is (I hope) clear. The pointer variables are initialized to zero so that the delete
operations at the end of the function do not need to test whether they're non-null in the source code; the library code performs that check anyway.
Use the substring method of the String class :
String removeCurrency=amount.getText().toString().substring(3);
If you use NavigationController in Swift 2.x
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let targetViewController = storyboard.instantiateViewControllerWithIdentifier("targetViewControllerID") as? TargetViewController
self.navigationController?.pushViewController(targetViewController!, animated: true)
the repr
function will return a string which is the exact definition of your dict (except for the order of the element, dicts are unordered in python). unfortunately, i can't tell a way to automatically get a string which represent the variable name.
>>> dict = {'one': 1, 'two': 2}
>>> repr(dict)
"{'two': 2, 'one': 1}"
writing to a file is pretty standard stuff, like any other file write:
f = open( 'file.py', 'w' )
f.write( 'dict = ' + repr(dict) + '\n' )
f.close()
For creating session only cookie with java script, you can use the following. This works for me.
document.cookie = "cookiename=value; expires=0; path=/";
then get cookie value as following
//get cookie
var cookiename = getCookie("cookiename");
if (cookiename == "value") {
//write your script
}
//function getCookie
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
}
return "";
}
Okay to support IE we can leave "expires" completely and can use this
document.cookie = "mtracker=somevalue; path=/";
var ul = document.getElementById("yourElementId");
while (ul.firstChild)
ul.removeChild(ul.firstChild);
The browser will execute the scripts in the order it finds them. If you call an external script, it will block the page until the script has been loaded and executed.
To test this fact:
// file: test.php
sleep(10);
die("alert('Done!');");
// HTML file:
<script type="text/javascript" src="test.php"></script>
Dynamically added scripts are executed as soon as they are appended to the document.
To test this fact:
<!DOCTYPE HTML>
<html>
<head>
<title>Test</title>
</head>
<body>
<script type="text/javascript">
var s = document.createElement('script');
s.type = "text/javascript";
s.src = "link.js"; // file contains alert("hello!");
document.body.appendChild(s);
alert("appended");
</script>
<script type="text/javascript">
alert("final");
</script>
</body>
</html>
Order of alerts is "appended" -> "hello!" -> "final"
If in a script you attempt to access an element that hasn't been reached yet (example: <script>do something with #blah</script><div id="blah"></div>
) then you will get an error.
Overall, yes you can include external scripts and then access their functions and variables, but only if you exit the current <script>
tag and start a new one.
You could use a List<T>
and when T
is a value type it will be allocated in contiguous memory which would not be the case if T
is a reference type.
Example:
List<int> integers = new List<int>();
integers.Add(1);
integers.Add(4);
integers.Add(7);
int someElement = integers[1];
You can create an html page with a form, having method="post" and action="yourdesiredurl" and open it with your browser.
As an alternative, there are some browser plugins for developers that allow you to do that, like Web Developer Toolbar for Firefox
std::vector<CustomClass *> whatever(20000);
or:
std::vector<CustomClass *> whatever;
whatever.reserve(20000);
The former sets the actual size of the array -- i.e., makes it a vector of 20000 pointers. The latter leaves the vector empty, but reserves space for 20000 pointers, so you can insert (up to) that many without it having to reallocate.
At least in my experience, it's fairly unusual for either of these to make a huge difference in performance--but either can affect correctness under some circumstances. In particular, as long as no reallocation takes place, iterators into the vector are guaranteed to remain valid, and once you've set the size/reserved space, you're guaranteed there won't be any reallocations as long as you don't increase the size beyond that.
You cannot add a ListView in a scroll View, as list view also scolls and there would be a synchonization problem between listview scroll and scroll view scoll. You can make a CustomList View and add this method into it.
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
/*
* Prevent parent controls from stealing our events once we've gotten a touch down
*/
if (ev.getActionMasked() == MotionEvent.ACTION_DOWN) {
ViewParent p = getParent();
if (p != null) {
p.requestDisallowInterceptTouchEvent(true);
}
}
return false;
}
def int2base(a, base, numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
baseit = lambda a=a, b=base: (not a) and numerals[0] or baseit(a-a%b,b*base)+numerals[a%b%(base-1) or (a%b) and (base-1)]
return baseit()
In any base every number is equal to a1+a2*base**2+a3*base**3...
The "mission" is to find all a 's.
For everyN=1,2,3...
the code is isolating the aN*base**N
by "mouduling" by b for b=base**(N+1)
which slice all a 's bigger than N, and slicing all the a 's that their serial is smaller than N by decreasing a everytime the func is called by the current aN*base**N
.
Base%(base-1)==1 therefor base**p%(base-1)==1 and therefor q*base^p%(base-1)==q with only one exception when q=base-1 which returns 0. To fix that in case it returns 0 the func is checking is it 0 from the beggining.
in this sample theres only one multiplications (instead of division) and some moudulueses which relatively takes small amounts of time.
//LinearLayOut Setup
LinearLayout linearLayout= new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
//ImageView Setup
ImageView imageView = new ImageView(this);
//setting image resource
imageView.setImageResource(R.drawable.play);
//setting image position
imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
//adding view to layout
linearLayout.addView(imageView);
//make visible to program
setContentView(linearLayout);
UPDATE user_account
SET (student_education_facility_id) = (
SELECT teacher.education_facility_id
FROM user_account teacher
WHERE teacher.user_account_id = teacher_id
AND teacher.user_type = 'ROLE_TEACHER'
)
WHERE user_type = 'ROLE_STUDENT'
Above are the sample update query...
You can write sub query with update SQL statement, you don't need to give alias name for that table. give alias name to sub query table. I tried and it's working fine for me....
You could call it just style, but I prefer aliasing to improve readability.
UPDATE A
SET ControllingSalesRep = RA.SalesRepCode
from DHE.dbo.tblAccounts A
INNER JOIN DHE_Import.dbo.tblSalesRepsAccountsLink RA
ON A.AccountCode = RA.AccountCode
For MySQL
UPDATE DHE.dbo.tblAccounts A
INNER JOIN DHE_Import.dbo.tblSalesRepsAccountsLink RA
ON A.AccountCode = RA.AccountCode
SET A.ControllingSalesRep = RA.SalesRepCode
canvas.toDataURL
is not working if the original image URL (either relative or absolute) does not belong to the same domain as the web page. Tested from a bookmarklet and a simple javascript in the web page containing the images.
Have a look to David Walsh working example. Put the html and images on your own web server, switch original image to relative or absolute URL, change to an external image URL. Only the first two cases are working.
Try it.
You can just pass the path to the style sheet .
{!! HTML::style('css/style.css') !!}
You can just pass the path to the javascript.
{!! HTML::script('js/script.js') !!}
Add the following lines in the require section of composer.json file and run composer update "illuminate/html": "5.*".
Register the service provider in config/app.php by adding the following value into the providers array:
'Illuminate\Html\HtmlServiceProvider'
Register facades by adding these two lines in the aliases array:
'Form'=> 'Illuminate\Html\FormFacade',
'HTML'=> 'Illuminate\Html\HtmlFacade'
The problem is that C++ is a statically-typed language, meaning that if something is declared as a string
, it's a string, and if something is declared as a double
, it's a double. Unlike other languages like JavaScript or PHP, there is no way to automatically convert from a string to a numeric value because the conversion might not be well-defined. For example, if you try converting the string "Hi there!"
to a double
, there's no meaningful conversion. Sure, you could just set the double
to 0.0 or NaN, but this would almost certainly be masking the fact that there's a problem in the code.
To fix this, don't buffer the file contents into a string. Instead, just read directly into the double
:
double lol;
openfile >> lol;
This reads the value directly as a real number, and if an error occurs will cause the stream's .fail()
method to return true. For example:
double lol;
openfile >> lol;
if (openfile.fail()) {
cout << "Couldn't read a double from the file." << endl;
}
For a project of mine, I needed to create intervals for time-series modeling, and to make the procedure more efficient I created tsmoothie: A python library for time-series smoothing and outlier detection in a vectorized way.
It provides different smoothing algorithms together with the possibility to computes intervals.
Here I use a ConvolutionSmoother
but you can also test it others.
import numpy as np
import matplotlib.pyplot as plt
from tsmoothie.smoother import *
x = np.linspace(0,2*np.pi,100)
y = np.sin(x) + np.random.random(100) * 0.2
# operate smoothing
smoother = ConvolutionSmoother(window_len=5, window_type='ones')
smoother.smooth(y)
# generate intervals
low, up = smoother.get_intervals('sigma_interval', n_sigma=2)
# plot the smoothed timeseries with intervals
plt.figure(figsize=(11,6))
plt.plot(smoother.smooth_data[0], linewidth=3, color='blue')
plt.plot(smoother.data[0], '.k')
plt.fill_between(range(len(smoother.data[0])), low[0], up[0], alpha=0.3)
I point out also that tsmoothie can carry out the smoothing of multiple timeseries in a vectorized way
When you use git push origin :staleStuff
, it automatically removes origin/staleStuff
, so when you ran git remote prune origin
, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune
to get rid of branches you have removed.
So what exactly git remote prune
does? Main idea: local branches (not tracking branches) are not touched by git remote prune
command and should be removed manually.
Now, a real-world example for better understanding:
You have a remote repository with 2 branches: master
and feature
. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):
refs/heads/master
(short name master
)refs/heads/feature
(short name feature
)refs/remotes/origin/master
(short name origin/master
)refs/remotes/origin/feature
(short name origin/feature
)Now, a typical scenario:
feature
, merges it into master
and removes feature
branch from remote repository.git fetch
(or git pull
), no references are removed from your local repository, so you still have all those 4 references.git remote prune origin
.feature
branch no longer exists, so refs/remotes/origin/feature
is a stale branch which should be removed. refs/heads/feature
, because git remote prune
does not remove any refs/heads/*
references.It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge
configuration parameter. This parameter is not really required for anything to work (probably except git pull
), so it might be missing.
(updated with example & useful info from comments)
(And if you have no admin access to the server)
ALTER ROLE <your_login_role> SET search_path TO a,b,c;
Two important things to know about:
a, b, c
matters, as it is also the order in which the schemas will be looked up for tables. So if you have the same table name in more than one schema among the defaults, there will be no ambiguity, the server will always use the table from the first schema you specified for your search_path
.The reason for the error is that the host server for https://cw.na1.hgncloud.com has provided some HTTP headers to protect the document. One of which is that the frame ancestors must be from the same domain as the original content. It seems you are attempting to put the iframe at a domain location that is not the same as the content of the iframe - thus violating the Content Security Policy that the host has set.
Check out this link on Content Security Policy for more details.
Using table aliases in the join condition:
update addresses a
set cid = b.id
from customers b
where a.id = b.id
You should always use the direct .attribute
form (but see the quirksmode link below) if you want programmatic access in JavaScript. It should handle the different types of attributes (think "onload") correctly.
Use getAttribute
/setAttribute
when you wish to deal with the DOM as it is (e.g. literal text only). Different browsers confuse the two. See Quirks modes: attribute (in)compatibility.
This is a known bug on Linux Debian. I solved using the create_tables.sql in the official package and changing pma_ with pma__ inside /etc/phpmyadmin/config.inc.php
I would use scikit-learn's own training_test_split, and generate it from the index
from sklearn.model_selection import train_test_split
y = df.pop('output')
X = df
X_train,X_test,y_train,y_test = train_test_split(X.index,y,test_size=0.2)
X.iloc[X_train] # return dataframe train
To be clear, you want to made your decision based on how much of the parameters are logical TRUE (in case of string arguments - not empty)?
argsne = (1 if a else 0) + (1 if b else 0) + (1 if c else 0)
Then you made a decision:
if ( 0 < argsne < 3 ):
doSth()
Now the logic is more clear.
To get the equivalent of a static constructor, you need to write a separate ordinary class to hold the static data and then make a static instance of that ordinary class.
class StaticStuff
{
std::vector<char> letters_;
public:
StaticStuff()
{
for (char c = 'a'; c <= 'z'; c++)
letters_.push_back(c);
}
// provide some way to get at letters_
};
class Elsewhere
{
static StaticStuff staticStuff; // constructor runs once, single instance
};
You can change from settings menu (at least from version 1.30.2 and above)...
On Mac, just hit Code > Preferences > Settings.
Then just search for "clear" and check Clear Previous Output.
SELECT word FROM table WHERE word NOT LIKE '%a%'
AND word NOT LIKE '%b%'
AND word NOT LIKE '%c%';
If you do not want to depend on throwing exception (which you probably should not) you can try this:
public static <T> T cast(Object o, Class<T> clazz) {
return clazz.isInstance(o) ? clazz.cast(o) : null;
}
Just to add up my bit:
Remember, you're gonna need to have at least 2 areas in your MVC application to get the routeValues: { area="" }
working; otherwise the area value will be used as a query-string parameter and you link will look like this: /?area=
If you don't have at least 2 areas, you can fix this behavior by:
1. editing the default route in RouteConfig.cs
like this:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { area = "", controller = "Home", action = "Index", id = UrlParameter.Optional }
);
OR
2. Adding a dummy area to your MVC project.
$(document).ready(function(){ contsize();});
$(window).bind("resize",function(){contsize();});
function contsize()
{
var h = window.innerHeight;
var calculatecontsize = h - 70;/*if header and footer heights= 35 then total 70px*/
$('#content').css({"height":calculatecontsize + "px"} );
}
show variables where Variable_name='hostname';
That could help you !!
you can drop the Constraint which is restricting you. If the column has access to other table. suppose a view is accessing the column which you are altering then it wont let you alter the column unless you drop the view. and after making changes you can recreate the view.
Advice on emulating a real system or your own thing? I can say that emulators work by emulating the ENTIRE hardware. Maybe not down to the circuit (as moving bits around like the HW would do. Moving the byte is the end result so copying the byte is fine). Emulator are very hard to create since there are many hacks (as in unusual effects), timing issues, etc that you need to simulate. If one (input) piece is wrong the entire system can do down or at best have a bug/glitch.
You can do something like:
Directory directory = new DirectoryInfo(path);
List<FileInfo> fileInfos = directory.EnumerateFiles("*.*", SearchOption.AllDirectories).ToList();
foreach (FileInfo f in fileInfos)
File.Delete(f.FullName);
You don't need a batch file, just do this from powershell :
powershell -C "gci | % {rni $_.Name ($_.Name -replace 'Vacation2010', 'December')}"
for(int i = 0; i < n; i++) {
existing_string += 'c';
}
but you should use StringBuilder instead, and save memory
int n = 3;
String existing_string = "string";
StringBuilder builder = new StringBuilder(existing_string);
for (int i = 0; i < n; i++) {
builder.append(" append ");
}
System.out.println(builder.toString());
Please see this link http://bugs.php.net/bug.php?id=45150 seems like they moved to native MYSQL support in PHP5.3 and it has some trouble working with IPV6. Try using "127.0.0.1" instead of "localhost"
$('td:first-child')
will return a collection of the elements that you want.
var text = $('td:first-child').map(function() {
return $(this).html();
}).get();
Have no fear, because a brave group of Ops Programmers have solved the situation with a brand spanking new nginx_tcp_proxy_module
Written in August 2012, so if you are from the future you should do your homework.
Assumes you are using CentOS:
init.d/nginx
script)yum install pcre pcre-devel openssl openssl-devel
and any other necessary libs for building NGINXAgain, assumes CentOS:
cd /usr/local/
wget 'http://nginx.org/download/nginx-1.2.1.tar.gz'
tar -xzvf nginx-1.2.1.tar.gz
cd nginx-1.2.1/
patch -p1 < /path/to/nginx_tcp_proxy_module/tcp.patch
./configure --add-module=/path/to/nginx_tcp_proxy_module --with-http_ssl_module
(you can add more modules if you need them)make
make install
Optional:
sudo /sbin/chkconfig nginx on
Remember to copy over your old configuration files first if you want to re-use them.
Important: you will need to create a tcp {}
directive at the highest level in your conf. Make sure it is not inside your http {}
directive.
The example config below shows a single upstream websocket server, and two proxies for both SSL and Non-SSL.
tcp {
upstream websockets {
## webbit websocket server in background
server 127.0.0.1:5501;
## server 127.0.0.1:5502; ## add another server if you like!
check interval=3000 rise=2 fall=5 timeout=1000;
}
server {
server_name _;
listen 7070;
timeout 43200000;
websocket_connect_timeout 43200000;
proxy_connect_timeout 43200000;
so_keepalive on;
tcp_nodelay on;
websocket_pass websockets;
websocket_buffer 1k;
}
server {
server_name _;
listen 7080;
ssl on;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.key;
timeout 43200000;
websocket_connect_timeout 43200000;
proxy_connect_timeout 43200000;
so_keepalive on;
tcp_nodelay on;
websocket_pass websockets;
websocket_buffer 1k;
}
}
In your .htaccess file , if you are using apache you can try with
Rule for Error Page - 404ErrorDocument 404 http://www.domain.com/notFound.html
While applying the new profile to the user,you should also check for resource limits are "turned on" for the database as a whole i.e.RESOURCE_LIMIT = TRUE
Let check the parameter value.
If in Case it is :
SQL> show parameter resource_limit
NAME TYPE VALUE
------------------------------------ ----------- ---------
resource_limit boolean FALSE
Its mean resource limit is off,we ist have to enable it.
Use the ALTER SYSTEM statement to turn on resource limits.
SQL> ALTER SYSTEM SET RESOURCE_LIMIT = TRUE;
System altered.
We can all see that the code you provided won't work at run time. That's because we know that the expression new A()
can never be an object of type B
.
But that's not how the compiler sees it. By the time the compiler is checking whether the cast is allowed, it just sees this:
variable_of_type_B = (B)expression_of_type_A;
And as others have demonstrated, that sort of cast is perfectly legal. The expression on the right could very well evaluate to an object of type B
. The compiler sees that A
and B
have a subtype relation, so with the "expression" view of the code, the cast might work.
The compiler does not consider the special case when it knows exactly what object type expression_of_type_A
will really have. It just sees the static type as A
and considers the dynamic type could be A
or any descendant of A
, including B
.
A bit of a hack, but it works fine for me:
Integer id = 2;
String query = "SELECT * FROM table WHERE id = ?";
PreparedStatement statement = m_connection.prepareStatement( query );
statement.setObject( 1, value );
String statementText = statement.toString();
query = statementText.substring( statementText.indexOf( ": " ) + 2 );
After compiling my code
in Android Studio, I found it here:
~\MyApp_Name\app\build\outputs\apk\app-debug.apk
I tried a lot of plugins, most of them don't support all browsers, I prefer iScroll and nanoScroller works for all these browsers :
But iScroll do not work with touch!
demo iScroll : http://lab.cubiq.org/iscroll/examples/simple/
demo nanoScroller : http://jamesflorentino.github.io/nanoScrollerJS/
This should work - imageButton.setBackgroundColor(android.R.color.transparent);
Another option is:
SELECT *
FROM TABLE
WHERE EXTRACT( YEAR FROM date_field) = EXTRACT(YEAR FROM sysdate)
Dir
takes wild cards so you could make a big difference adding the filter for test
up front and avoiding testing each file
Sub LoopThroughFiles()
Dim StrFile As String
StrFile = Dir("c:\testfolder\*test*")
Do While Len(StrFile) > 0
Debug.Print StrFile
StrFile = Dir
Loop
End Sub
This went a little weird for me, from one day to the next one the script that have been working since days just stop working. There wasn´t a newer version of mysql or any kind of upgrade but I was getting the same error, so I give a last try to the CSV file and notice that the end of lines were using \n instead of the expected ( per my script ) \r\n so I save it with the right EOL and run the script again without any trouble.
I think is kind of odd for mysql to tell me The used command is not allowed with this MySQL version since the reason was completely different.
My working command looks like this:
LOAD DATA LOCAL INFILE 'file-name' IGNORE INTO TABLE table-name CHARACTER SET latin1 FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\r\n' IGNORE 1 LINES.
This has been moved to a new location now -- and please use the below site for updates.
http://download.eclipse.org/technology/m2e/releases
I realize that this is an old thread, but for Future-Me, and posterity, I figured I should add my two-cents around the "running npm as sudo" discussion. Disclaimer: I do not use Windows. These steps have only been proven on non-windows machines, both virtual and physical.
You can avoid the need to use sudo by changing the permission to npm's default directory.
sudo
npm config get prefix
/usr/local
/usr
or /Users/YOURUSERNAME/node_modules
or /Something/Else/FishyLooking
npm config set prefix /usr/local
sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share}
Now you should be able to run npm <whatever>
without sudo
. Note: You may need to restart your terminal in order for these changes to take effect.
This is how I would do it (the code below has been tested, full source provided below), begin by creating a class with common properties
class Word
{
public string Base { get; set; }
public string Category { get; set; }
public string Id { get; set; }
}
load using XDocument with INPUT_DATA for demonstration purposes and find element name with lexicon . . .
XDocument doc = XDocument.Parse(INPUT_DATA);
XElement lex = doc.Element("lexicon");
make sure there is a value and use linq to extract the word elements from it . . .
Word[] catWords = null;
if (lex != null)
{
IEnumerable<XElement> words = lex.Elements("word");
catWords = (from itm in words
where itm.Element("category") != null
&& itm.Element("category").Value == "verb"
&& itm.Element("id") != null
&& itm.Element("base") != null
select new Word()
{
Base = itm.Element("base").Value,
Category = itm.Element("category").Value,
Id = itm.Element("id").Value,
}).ToArray<Word>();
}
The where
statement checks if the category element exists and that the category value is not null and then check it again that it is a verb. Then check that the other nodes also exists . . .
The linq query will return an IEnumerable< Typename > object, so we can call ToArray< Typename >() to cast the entire collection into the type we want.
Then print it to get . . .
[Found]
Id: E0006429
Base: abandon
Category: verb
[Found]
Id: E0006524
Base: abolish
Category: verb
Full Source:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace test
{
class Program
{
class Word
{
public string Base { get; set; }
public string Category { get; set; }
public string Id { get; set; }
}
static void Main(string[] args)
{
XDocument doc = XDocument.Parse(INPUT_DATA);
XElement lex = doc.Element("lexicon");
Word[] catWords = null;
if (lex != null)
{
IEnumerable<XElement> words = lex.Elements("word");
catWords = (from itm in words
where itm.Element("category") != null
&& itm.Element("category").Value == "verb"
&& itm.Element("id") != null
&& itm.Element("base") != null
select new Word()
{
Base = itm.Element("base").Value,
Category = itm.Element("category").Value,
Id = itm.Element("id").Value,
}).ToArray<Word>();
}
//print it
if (catWords != null)
{
Console.WriteLine("Words with <category> and value verb:\n");
foreach (Word itm in catWords)
Console.WriteLine("[Found]\n Id: {0}\n Base: {1}\n Category: {2}\n",
itm.Id, itm.Base, itm.Category);
}
}
const string INPUT_DATA =
@"<?xml version=""1.0""?>
<lexicon>
<word>
<base>a</base>
<category>determiner</category>
<id>E0006419</id>
</word>
<word>
<base>abandon</base>
<category>verb</category>
<id>E0006429</id>
<ditransitive/>
<transitive/>
</word>
<word>
<base>abbey</base>
<category>noun</category>
<id>E0203496</id>
</word>
<word>
<base>ability</base>
<category>noun</category>
<id>E0006490</id>
</word>
<word>
<base>able</base>
<category>adjective</category>
<id>E0006510</id>
<predicative/>
<qualitative/>
</word>
<word>
<base>abnormal</base>
<category>adjective</category>
<id>E0006517</id>
<predicative/>
<qualitative/>
</word>
<word>
<base>abolish</base>
<category>verb</category>
<id>E0006524</id>
<transitive/>
</word>
</lexicon>";
}
}
You can enter the long form command:
source ~/.bashrc
or you can use the shorter version of the command:
. ~/.bashrc
Character issues like this are difficult to diagnose because information is easily lost through misinterpretation of characters via application bugs, misconfiguration, cut'n'paste, etc.
As I (and apparently others) see it, you've pasted three characters:
codepoint glyph escaped windows-1252 info
=======================================================================
U+00ef ï \u00ef ef, LATIN_1_SUPPLEMENT, LOWERCASE_LETTER
U+00bf ¿ \u00bf bf, LATIN_1_SUPPLEMENT, OTHER_PUNCTUATION
U+00bd ½ \u00bd bd, LATIN_1_SUPPLEMENT, OTHER_NUMBER
To identify the character, download and run the program from this page. Paste your character into the text field and select the glyph mode; paste the report into your question. It'll help people identify the problematic character.
All the other codes I've tested didn't work good due to the fact that the user could still place the caret/cursor wherever in the middle of the string (ex.: 12|3.00 - where | is the cursor). My solution always puts the cursor in the end of the string whenever the touch occurs on the EditText.
The ultimate solution is:
// For a EditText like:
<EditText
android:id="@+id/EditTextAmount"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:hint="@string/amount"
android:layout_weight="1"
android:text="@string/zero_value"
android:inputType="text|numberDecimal"
android:maxLength="13"/>
@string/amount="0.00" @string/zero_value="0.00"
// Create a Static boolean flag
private static boolean returnNext;
// Set caret/cursor to the end on focus change
EditTextAmount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View editText, boolean hasFocus) {
if(hasFocus){
((EditText) editText).setSelection(((EditText) editText).getText().length());
}
}
});
// Create a touch listener and put caret to the end (no matter where the user touched in the middle of the string)
EditTextAmount.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View editText, MotionEvent event) {
((EditText) editText).onTouchEvent(event);
((EditText) editText).setSelection(((EditText) editText).getText().length());
return true;
}
});
// Implement a Currency Mask with addTextChangedListener
EditTextAmount.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String input = s.toString();
String output = new String();
String buffer = new String();
String decimals = new String();
String numbers = Integer.toString(Integer.parseInt(input.replaceAll("[^0-9]", "")));
if(returnNext){
returnNext = false;
return;
}
returnNext = true;
if (numbers.equals("0")){
output += "0.00";
}
else if (numbers.length() <= 2){
output += "0." + String.format("%02d", Integer.parseInt(numbers));
}
else if(numbers.length() >= 3){
decimals = numbers.substring(numbers.length() - 2);
int commaCounter = 0;
for(int i=numbers.length()-3; i>=0; i--){
if(commaCounter == 3){
buffer += ",";
commaCounter = 0;
}
buffer += numbers.charAt(i);
commaCounter++;
}
output = new StringBuilder(buffer).reverse().toString() + "." + decimals;
}
EditTextAmount.setText(output);
EditTextAmount.setSelection(EditTextAmount.getText().length());
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
/*String input = s.toString();
if(input.equals("0.0")){
EditTextAmount.setText("0.00");
EditTextAmount.setSelection(EditTextAmount.getText().length());
return;
}*/
}
@Override
public void afterTextChanged(Editable s) {
}
});
Hope it helps!
Why not try find /usr/include/X11 -name Xlib.h
If there is a hit, you have Xlib.h
If not install it using sudo apt-get install libx11-dev
and you are good to go :)
For optimal Insertion performance disable the index if that's an option for you. Other than that, better hardware (disk, memory) is also helpful
I'm using typescript with vue, but this is how I went about it
<template><div><img :src="MyImage" /></div></template>
<script lang="ts">
import { Vue } from 'vue-property-decorator';
export default class MyPage extends Vue {
MyImage = "../assets/images/myImage.png";
}
</script>
What I did it to ignore the settings.php file successfully:
I think if there's the committed file on Git then ignore doesn't work as expected. Just delete the file and commit. Afterwards it'll ignore.
Assuming type TreeMap<String,Integer> :
for(Map.Entry<String,Integer> entry : treeMap.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + " => " + value);
}
(key and Value types can be any class of course)
Assuming that your branch was created off of master
, then while in the branch (that is, you have the branch checked out):
git cherry -v master
or
git log master..
If you are not in the branch, then you can add the branch name to the "git log" command, like this:
git log master..branchname
If your branch was made off of origin/master
, then say origin/master
instead of master
.
One-liner in Racket:
racket -e '(define (g) (define i (read)) (if (eof-object? i) empty (cons i (g)))) (foldr + 0 (g))' < numlist.txt
ThisWorkbook.Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "XYZ"
(when you add a worksheet, anyway it'll be the active sheet)
As of Git v2.23.0 (August 2019), git switch
is preferred over git checkout
when you’re simply switching branches/tags. I’m guessing they did this since git checkout
had two functions: for switching branches and for restoring files. So in v2.23.0, they added two new commands, git switch
, and git restore
, to separate those concerns. I would predict at some point in the future, git checkout
will be deprecated.
To switch to a normal branch, use git switch <branch-name>
. To switch to a commit-like object, including single commits and tags, use git switch --detach <commitish>
, where <commitish>
is the tag name or commit number.
The --detach
option forces you to recognize that you’re in a mode of “inspection and discardable experiments”. To create a new branch from the commitish you’re switching to, use git switch -c <new-branch> <start-point>
.
The resource drawable names are not stored as strings, so you'll have to resolve the string into the integer constant generated during the build. You can use the Resources
class to resolve the string into that integer.
Resources res = getResources();
int resourceId = res.getIdentifier(
generatedString, "drawable", getPackageName() );
imageView.setImageResource( resourceId );
This resolves your generated string into the integer that the ImageView
can use to load the right image.
Alternately, you can use the id to load the Drawable
manually and then set the image using that drawable instead of the resource ID.
Drawable drawable = res.getDrawable( resourceId );
imageView.setImageDrawable( drawable );
For me the padding solution wasn't good, as I was using border on the button, and would've been hard to put modify the markup to create an overlay for the touch area.
So what I did, is I just used the :before pseudo tag, and created an overlay, which was perfect in my case, as the click event propagated the same way.
button.my-button:before {
content: '';
position: absolute;
width: 26px;
height: 26px;
top: -6px;
left: -5px;
}
sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename
sudo update-rc.d filename defaults
Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln
).
At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename
) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*
. Updated above code to reflect this.
Also as pointed out in the comments (by Charles Brandt), /filename
must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.
Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts
As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.
According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering
", in which case you have to pass sequence and runlevel configuration through command line arguments.
The equivalent argument set for the above example is
sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .
If you are trying to group values together this may be a great opportunity to create a simple struct or class and use that as the value in a dictionary.
public struct MyValue
{
public object Value1;
public double Value2;
}
then you could have your dictionary
var dict = new Dictionary<int, MyValue>();
you could even go a step further and implement your own dictionary class that will handle any special operations that you would need. for example if you wanted to have an Add method that accepted an int, object, and double
public class MyDictionary : Dictionary<int, MyValue>
{
public void Add(int key, object value1, double value2)
{
MyValue val;
val.Value1 = value1;
val.Value2 = value2;
this.Add(key, val);
}
}
then you could simply instantiate and add to the dictionary like so and you wouldn't have to worry about creating 'MyValue' structs:
var dict = new MyDictionary();
dict.Add(1, new Object(), 2.22);
I do it this way:
<!-- global template loaded in all pages // -->
<div id="NewsModal" class="modal fade" tabindex="-1" role="dialog" data-ajaxload="true" aria-labelledby="newsLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 class="newsLabel"></h3>
</div>
<div class="modal-body">
<div class="loading">
<span class="caption">Loading...</span>
<img src="/images/loading.gif" alt="loading">
</div>
</div>
<div class="modal-footer caption">
<button class="btn btn-right default modal-close" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Here is my a href:
<a href="#NewsModal" onclick="remote=\'modal_newsfeed.php?USER='.trim($USER).'&FUNCTION='.trim(urlencode($FUNCTIONCODE)).'&PATH_INSTANCE='.$PATH_INSTANCE.'&ALL=ALL\'
remote_target=\'#NewsModal .modal-body\'" role="button" data-toggle="modal">See All Notifications <i class="m-icon-swapright m-icon-dark"></i></a>
This is because you are adding your <tbody>
tag before <td>
in table you cannot print any data without <td>
.
So for that you have to make a <div>
say #header
with position: fixed;
header
{
position: fixed;
}
make another <div>
which will act as <tbody>
tbody
{
overflow:scroll;
}
Now your header is fixed and the body will scroll. And the header will remain there.
If you include the input tag in the label tag, you don't need to use the 'for' attribute.
That said, I don't like to include the input tag in my labels because I think they're separate, not containing, entities.
I did a time test here, using each method 100000 times in a loop. The results surprised me. (The results still surprise me after editing them in response to valid criticism in the comments.)
Here's the script:
import timeit
bad_chars = '(){}<>'
setup = """import re
import string
s = 'Barack (of Washington)'
bad_chars = '(){}<>'
rgx = re.compile('[%s]' % bad_chars)"""
timer = timeit.Timer('o = "".join(c for c in s if c not in bad_chars)', setup=setup)
print "List comprehension: ", timer.timeit(100000)
timer = timeit.Timer("o= rgx.sub('', s)", setup=setup)
print "Regular expression: ", timer.timeit(100000)
timer = timeit.Timer('for c in bad_chars: s = s.replace(c, "")', setup=setup)
print "Replace in loop: ", timer.timeit(100000)
timer = timeit.Timer('s.translate(string.maketrans("", "", ), bad_chars)', setup=setup)
print "string.translate: ", timer.timeit(100000)
Here are the results:
List comprehension: 0.631745100021
Regular expression: 0.155561923981
Replace in loop: 0.235936164856
string.translate: 0.0965719223022
Results on other runs follow a similar pattern. If speed is not the primary concern, however, I still think string.translate
is not the most readable; the other three are more obvious, though slower to varying degrees.
len(yourdict.keys())
or just
len(yourdict)
If you like to count unique words in the file, you could just use set
and do like
len(set(open(yourdictfile).read().split()))
I have personally found some errors in when using unix_timestamp based date converstions from dd-MMM-yyyy format to yyyy-mm-dd, using spark 1.6, but this may extend into recent versions. Below I explain a way to solve the problem using java.time that should work in all versions of spark:
I've seen errors when doing:
from_unixtime(unix_timestamp(StockMarketClosingDate, 'dd-MMM-yyyy'), 'yyyy-MM-dd') as FormattedDate
Below is code to illustrate the error, and my solution to fix it. First I read in stock market data, in a common standard file format:
import sys.process._
import org.apache.spark.sql.SQLContext
import org.apache.spark.sql.functions.udf
import org.apache.spark.sql.types.{StructType, StructField, StringType, IntegerType, DateType}
import sqlContext.implicits._
val EODSchema = StructType(Array(
StructField("Symbol" , StringType, true), //$1
StructField("Date" , StringType, true), //$2
StructField("Open" , StringType, true), //$3
StructField("High" , StringType, true), //$4
StructField("Low" , StringType, true), //$5
StructField("Close" , StringType, true), //$6
StructField("Volume" , StringType, true) //$7
))
val textFileName = "/user/feeds/eoddata/INDEX/INDEX_19*.csv"
// below is code to read using later versions of spark
//val eoddata = spark.read.format("csv").option("sep", ",").schema(EODSchema).option("header", "true").load(textFileName)
// here is code to read using 1.6, via, "com.databricks:spark-csv_2.10:1.2.0"
val eoddata = sqlContext.read
.format("com.databricks.spark.csv")
.option("header", "true") // Use first line of all files as header
.option("delimiter", ",") //.option("dateFormat", "dd-MMM-yyyy") failed to work
.schema(EODSchema)
.load(textFileName)
eoddata.registerTempTable("eoddata")
And here is the date conversions having issues:
%sql
-- notice there are errors around the turn of the year
Select
e.Date as StringDate
, cast(from_unixtime(unix_timestamp(e.Date, "dd-MMM-yyyy"), 'YYYY-MM-dd') as Date) as ProperDate
, e.Close
from eoddata e
where e.Symbol = 'SPX.IDX'
order by cast(from_unixtime(unix_timestamp(e.Date, "dd-MMM-yyyy"), 'YYYY-MM-dd') as Date)
limit 1000
A chart made in zeppelin shows spikes, which are errors.
and here is the check that shows the date conversion errors:
// shows the unix_timestamp conversion approach can create errors
val result = sqlContext.sql("""
Select errors.* from
(
Select
t.*
, substring(t.OriginalStringDate, 8, 11) as String_Year_yyyy
, substring(t.ConvertedCloseDate, 0, 4) as Converted_Date_Year_yyyy
from
( Select
Symbol
, cast(from_unixtime(unix_timestamp(e.Date, "dd-MMM-yyyy"), 'YYYY-MM-dd') as Date) as ConvertedCloseDate
, e.Date as OriginalStringDate
, Close
from eoddata e
where e.Symbol = 'SPX.IDX'
) t
) errors
where String_Year_yyyy <> Converted_Date_Year_yyyy
""")
//df.withColumn("tx_date", to_date(unix_timestamp($"date", "M/dd/yyyy").cast("timestamp")))
result.registerTempTable("SPX")
result.cache()
result.show(100)
result: org.apache.spark.sql.DataFrame = [Symbol: string, ConvertedCloseDate: date, OriginalStringDate: string, Close: string, String_Year_yyyy: string, Converted_Date_Year_yyyy: string]
res53: result.type = [Symbol: string, ConvertedCloseDate: date, OriginalStringDate: string, Close: string, String_Year_yyyy: string, Converted_Date_Year_yyyy: string]
+-------+------------------+------------------+-------+----------------+------------------------+
| Symbol|ConvertedCloseDate|OriginalStringDate| Close|String_Year_yyyy|Converted_Date_Year_yyyy|
+-------+------------------+------------------+-------+----------------+------------------------+
|SPX.IDX| 1997-12-30| 30-Dec-1996| 753.85| 1996| 1997|
|SPX.IDX| 1997-12-31| 31-Dec-1996| 740.74| 1996| 1997|
|SPX.IDX| 1998-12-29| 29-Dec-1997| 953.36| 1997| 1998|
|SPX.IDX| 1998-12-30| 30-Dec-1997| 970.84| 1997| 1998|
|SPX.IDX| 1998-12-31| 31-Dec-1997| 970.43| 1997| 1998|
|SPX.IDX| 1998-01-01| 01-Jan-1999|1229.23| 1999| 1998|
+-------+------------------+------------------+-------+----------------+------------------------+
FINISHED
After this result, I switched to java.time conversions with a UDF like this, which worked for me:
// now we will create a UDF that uses the very nice java.time library to properly convert the silly stockmarket dates
// start by importing the specific java.time libraries that superceded the joda.time ones
import java.time.LocalDate
import java.time.format.DateTimeFormatter
// now define a specific data conversion function we want
def fromEODDate (YourStringDate: String): String = {
val formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy")
var retDate = LocalDate.parse(YourStringDate, formatter)
// this should return a proper yyyy-MM-dd date from the silly dd-MMM-yyyy formats
// now we format this true local date with a formatter to the desired yyyy-MM-dd format
val retStringDate = retDate.format(DateTimeFormatter.ISO_LOCAL_DATE)
return(retStringDate)
}
Now I register it as a function for use in sql:
sqlContext.udf.register("fromEODDate", fromEODDate(_:String))
and check the results, and rerun test:
val results = sqlContext.sql("""
Select
e.Symbol as Symbol
, e.Date as OrigStringDate
, Cast(fromEODDate(e.Date) as Date) as ConvertedDate
, e.Open
, e.High
, e.Low
, e.Close
from eoddata e
order by Cast(fromEODDate(e.Date) as Date)
""")
results.printSchema()
results.cache()
results.registerTempTable("results")
results.show(10)
results: org.apache.spark.sql.DataFrame = [Symbol: string, OrigStringDate: string, ConvertedDate: date, Open: string, High: string, Low: string, Close: string]
root
|-- Symbol: string (nullable = true)
|-- OrigStringDate: string (nullable = true)
|-- ConvertedDate: date (nullable = true)
|-- Open: string (nullable = true)
|-- High: string (nullable = true)
|-- Low: string (nullable = true)
|-- Close: string (nullable = true)
res79: results.type = [Symbol: string, OrigStringDate: string, ConvertedDate: date, Open: string, High: string, Low: string, Close: string]
+--------+--------------+-------------+-------+-------+-------+-------+
| Symbol|OrigStringDate|ConvertedDate| Open| High| Low| Close|
+--------+--------------+-------------+-------+-------+-------+-------+
|ADVA.IDX| 01-Jan-1996| 1996-01-01| 364| 364| 364| 364|
|ADVN.IDX| 01-Jan-1996| 1996-01-01| 1527| 1527| 1527| 1527|
|ADVQ.IDX| 01-Jan-1996| 1996-01-01| 1283| 1283| 1283| 1283|
|BANK.IDX| 01-Jan-1996| 1996-01-01|1009.41|1009.41|1009.41|1009.41|
| BKX.IDX| 01-Jan-1996| 1996-01-01| 39.39| 39.39| 39.39| 39.39|
|COMP.IDX| 01-Jan-1996| 1996-01-01|1052.13|1052.13|1052.13|1052.13|
| CPR.IDX| 01-Jan-1996| 1996-01-01| 1.261| 1.261| 1.261| 1.261|
|DECA.IDX| 01-Jan-1996| 1996-01-01| 205| 205| 205| 205|
|DECN.IDX| 01-Jan-1996| 1996-01-01| 825| 825| 825| 825|
|DECQ.IDX| 01-Jan-1996| 1996-01-01| 754| 754| 754| 754|
+--------+--------------+-------------+-------+-------+-------+-------+
only showing top 10 rows
which looks ok, and I rerun my chart, to see if there are errors/spikes:
As you can see, no more spikes or errors. I now use a UDF as I've shown to apply my date format transformations to a standard yyyy-MM-dd format, and have not had spurious errors since. :-)
I've been verifying calls in the same manner - I believe it is the right way to do it.
mockSomething.Verify(ms => ms.Method(
It.IsAny<int>(),
It.Is<MyObject>(mo => mo.Id == 5 && mo.description == "test")
), Times.Once());
If your lambda expression becomes unwieldy, you could create a function that takes MyObject
as input and outputs true
/false
...
mockSomething.Verify(ms => ms.Method(
It.IsAny<int>(),
It.Is<MyObject>(mo => MyObjectFunc(mo))
), Times.Once());
private bool MyObjectFunc(MyObject myObject)
{
return myObject.Id == 5 && myObject.description == "test";
}
Also, be aware of a bug with Mock where the error message states that the method was called multiple times when it wasn't called at all. They might have fixed it by now - but if you see that message you might consider verifying that the method was actually called.
EDIT: Here is an example of calling verify multiple times for those scenarios where you want to verify that you call a function for each object in a list (for example).
foreach (var item in myList)
mockRepository.Verify(mr => mr.Update(
It.Is<MyObject>(i => i.Id == item.Id && i.LastUpdated == item.LastUpdated),
Times.Once());
Same approach for setup...
foreach (var item in myList) {
var stuff = ... // some result specific to the item
this.mockRepository
.Setup(mr => mr.GetStuff(item.itemId))
.Returns(stuff);
}
So each time GetStuff is called for that itemId, it will return stuff specific to that item. Alternatively, you could use a function that takes itemId as input and returns stuff.
this.mockRepository
.Setup(mr => mr.GetStuff(It.IsAny<int>()))
.Returns((int id) => SomeFunctionThatReturnsStuff(id));
One other method I saw on a blog some time back (Phil Haack perhaps?) had setup returning from some kind of dequeue object - each time the function was called it would pull an item from a queue.
The Web Tools Platform provides the Java EE development tools, and is included in the IDE for Java EE Developers. Among other things, it provides the Servers view and makes it easy to launch a Tomcat server from there. You can either download the IDE for Java EE Developers, or go to the Help menu and Install New Software, looking for the Java EE features.
use this code it is working
// index.jsp or login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="login" method="post">
Username : <input type="text" name="username"><br>
Password : <input type="password" name="pass"><br>
<input type="submit"><br>
</form>
</body>
</html>
// authentication servlet class
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class auth extends HttpServlet {
private static final long serialVersionUID = 1L;
public auth() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String username = request.getParameter("username");
String pass = request.getParameter("pass");
String sql = "select * from reg where username='" + username + "'";
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/Exam",
"root", "");
Statement s = conn.createStatement();
java.sql.ResultSet rs = s.executeQuery(sql);
String un = null;
String pw = null;
String name = null;
/* Need to put some condition in case the above query does not return any row, else code will throw Null Pointer exception */
PrintWriter prwr1 = response.getWriter();
if(!rs.isBeforeFirst()){
prwr1.write("<h1> No Such User in Database<h1>");
} else {
/* Conditions to be executed after at least one row is returned by query execution */
while (rs.next()) {
un = rs.getString("username");
pw = rs.getString("password");
name = rs.getString("name");
}
PrintWriter pww = response.getWriter();
if (un.equalsIgnoreCase(username) && pw.equals(pass)) {
// use this or create request dispatcher
response.setContentType("text/html");
pww.write("<h1>Welcome, " + name + "</h1>");
} else {
pww.write("wrong username or password\n");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
int
and double
have different semantics. Consider division. 1/2
is 0
, 1.0/2.0
is 0.5
. In any given situation, one of those answers will be right and the other wrong.
That said, there are programming languages, such as JavaScript, in which 64-bit float is the only numeric data type. You have to explicitly truncate some division results to get the same semantics as Java int
. Languages such as Java that support integer types make truncation automatic for integer variables.
In addition to having different semantics from double
, int
arithmetic is generally faster, and the smaller size (32 bits vs. 64 bits) leads to more efficient use of caches and data transfer bandwidth.
Here is a video about Debugging with eclipse.
For more details read this page.
Instead of Debugging as Java program, use Debug as Android Application
May help new comers.
Another way to change the color is remove the default class and replace , in the panel using the classes of bootstrap.
example:
<div class="panel panel-danger">
<div class="panel-heading">
</div>
</div>
Some options:
tr
tr -d '\15\32' < windows.txt > unix.txt
OR
tr -d '\r' < windows.txt > unix.txt
perl
perl -p -e 's/\r$//' < windows.txt > unix.txt
sed
sed 's/^M$//' windows.txt > unix.txt
OR
sed 's/\r$//' windows.txt > unix.txt
To obtain ^M
, you have to type CTRL-V
and then CTRL-M
.
Another possible solution:
<div>
<h2 align="center">
San Andreas: Multiplayer
</h2>
<div align="center">
<font size="+1"><em class="heading_description">15 pence per
slot</em></font> <img src=
"http://fhers.com/images/game_servers/sa-mp.jpg" class=
"alignleft noTopMargin" style="width: 188px;" /> <a href="gfh"
class="order-small"><span>order</span></a>
</div>
</div>
Also helpful as well.
Here is a Python 3, POSIX solution (not Windows!) that uses mmap
to map the object into memory.
import hashlib
import mmap
def sha256sum(filename):
h = hashlib.sha256()
with open(filename, 'rb') as f:
with mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ) as mm:
h.update(mm)
return h.hexdigest()
To build a regular expression from a variable in JavaScript, you'll need to use the RegExp
constructor with a string parameter.
function reg(input) {
var flags;
//could be any combination of 'g', 'i', and 'm'
flags = 'g';
return new RegExp('ReGeX' + input + 'ReGeX', flags);
}
of course, this is a very naive example. It assumes that input
is has been properly escaped for a regular expression. If you're dealing with user-input, or simply want to make it more convenient to match special characters, you'll need to escape special characters:
function regexEscape(str) {
return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
}
function reg(input) {
var flags;
//could be any combination of 'g', 'i', and 'm'
flags = 'g';
input = regexEscape(input);
return new RegExp('ReGeX' + input + 'ReGeX', flags);
}
Download anaconda https://anaconda.org/
once done installing anaconda...
Go into Settings -> Project Settings -> Project Interpreter.
Then navigate to the "Paths" tab and search for /anaconda/bin/python
click apply
You can append a class to the className
member, with a leading space.
document.getElementById('hello').className += ' new-class';
The solution provided by Justin should work. To be sure making use of SelectedIndex
property will also help.
ddlColor.DataSource = from p in db.ProductTypes
where p.ProductID == pID
orderby p.Color
select new { p.Color };
ddlColor.DataTextField = "Color";
ddlColor.DataBind();
ddlColor.Items.Insert(0, new ListItem("Select Color", "");
ddlColor.SelectedIndex = 0;
You can do the following:
String [] strings = new String [] {"1", "2" };
List<String> stringList = new ArrayList<String>(Arrays.asList(strings)); //new ArrayList is only needed if you absolutely need an ArrayList
This how I manage with very big file (tested with up to 100G). And it's faster than fgets()
$block =1024*1024;//1MB or counld be any higher than HDD block_size*2
if ($fh = fopen("file.txt", "r")) {
$left='';
while (!feof($fh)) {// read the file
$temp = fread($fh, $block);
$fgetslines = explode("\n",$temp);
$fgetslines[0]=$left.$fgetslines[0];
if(!feof($fh) )$left = array_pop($lines);
foreach ($fgetslines as $k => $line) {
//do smth with $line
}
}
}
fclose($fh);
I used to try this method
_.filter(data, function(d) { return d.name != 'a' });
There might be better methods too like the above solutions provided by users
I'd print out the result of an2.getNodeName()
as well for debugging purposes. My guess is that your tree crawling code isn't crawling to the nodes that you think it is. That suspicion is enhanced by the lack of checking for node names in your code.
Other than that, the javadoc for Node defines "getNodeValue()" to return null for Nodes of type Element. Therefore, you really should be using getTextContent(). I'm not sure why that wouldn't give you the text that you want.
Perhaps iterate the children of your tag node and see what types are there?
Tried this code and it works for me:
String xml = "<add job=\"351\">\n" +
" <tag>foobar</tag>\n" +
" <tag>foobar2</tag>\n" +
"</add>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
Document doc = db.parse(bis);
Node n = doc.getFirstChild();
NodeList nl = n.getChildNodes();
Node an,an2;
for (int i=0; i < nl.getLength(); i++) {
an = nl.item(i);
if(an.getNodeType()==Node.ELEMENT_NODE) {
NodeList nl2 = an.getChildNodes();
for(int i2=0; i2<nl2.getLength(); i2++) {
an2 = nl2.item(i2);
// DEBUG PRINTS
System.out.println(an2.getNodeName() + ": type (" + an2.getNodeType() + "):");
if(an2.hasChildNodes()) System.out.println(an2.getFirstChild().getTextContent());
if(an2.hasChildNodes()) System.out.println(an2.getFirstChild().getNodeValue());
System.out.println(an2.getTextContent());
System.out.println(an2.getNodeValue());
}
}
}
Output was:
#text: type (3): foobar foobar
#text: type (3): foobar2 foobar2
Just in case you guys have the url like localhost/index.xsp?a=1#something and you need to get the param not the hash.
var vars = [], hash, anchor;
var q = document.URL.split('?')[1];
if(q != undefined){
q = q.split('&');
for(var i = 0; i < q.length; i++){
hash = q[i].split('=');
anchor = hash[1].split('#');
vars.push(anchor[0]);
vars[hash[0]] = anchor[0];
}
}
Use OUTER APPLY instead of LEFT JOIN:
SELECT u.id, mbg.marker_value
FROM dps_user u
OUTER APPLY
(SELECT TOP 1 m.marker_value, um.profile_id
FROM dps_usr_markers um (NOLOCK)
INNER JOIN dps_markers m (NOLOCK)
ON m.marker_id= um.marker_id AND
m.marker_key = 'moneyBackGuaranteeLength'
WHERE um.profile_id=u.id
ORDER BY m.creation_date
) AS MBG
WHERE u.id = 'u162231993';
Unlike JOIN, APPLY allows you to reference the u.id inside the inner query.
I got this message when updating new files from remote and index got out of whack. Tried to fix the index, but resolving via Xcode 4.5, GitHub.app (103), and GitX.app (0.7.1) failed. So, I did this:
git commit -a -m "your commit message here"
which worked in bypassing the git index.
Two blog posts that helped me understand about Git and Xcode are:
now i got it finally! make sure that there are no spaces before and after the path and put the semi-colon on both sides without spaces
For the benefit of searchers looking to solve a similar problem, you can get a similar error if your input is an empty string.
e.g.
var d = "";
var json = JSON.parse(d);
or if you are using AngularJS
var d = "";
var json = angular.fromJson(d);
In chrome it resulted in 'Uncaught SyntaxError: Unexpected end of input', but Firebug showed it as 'JSON.parse: unexpected end of data at line 1 column 1 of the JSON data'.
Sure most people won't be caught out by this, but I hadn't protected the method and it resulted in this error.
const { width, height } = Dimensions.get('window')
<View style={{marginBottom: 20}}>
<Image
style={{ height: 200, width: width, position: 'absolute', resizeMode: 'cover' }}
source={{ uri: 'https://picsum.photos/'+width+'/200/?random' }}
/>
<View style={styles.productBar}>
<View style={styles.productElement}>
<Image
style={{ height: 160, width: width - 250, position: 'relative', resizeMode: 'cover' }}
source={{ uri: 'https://picsum.photos/'+ 250 +'/160/?random' }}
/>
</View>
<View style={styles.productElement}>
<Text style={{ fontSize: 16, paddingLeft: 20 }}>Baslik</Text>
<Text style={{ fontSize: 12, paddingLeft: 20, color: "blue"}}>Alt Baslik</Text>
</View>
</View>
</View>
productBar: {
margin: 20,
marginBottom: 0,
justifyContent: "flex-start" ,
flexDirection: "row"
},
productElement: {
marginBottom: 0,
},
If you want to know if a property exists in an instance of a class that you have defined, simply combine property_exists()
with isset()
.
public function hasProperty($property)
{
return property_exists($this, $property) && isset($this->$property);
}
EasySSLProtocolSocketFactory was giving me problems so I ended up implementing my own ProtocolSocketFactory.
First you need to register it:
Protocol.registerProtocol("https", new Protocol("https", new TrustAllSSLSocketFactory(), 443));
HttpClient client = new HttpClient();
...
Then implement ProtocolSocketFactory:
class TrustAllSSLSocketFactory implements ProtocolSocketFactory {
public static final TrustManager[] TRUST_ALL_CERTS = new TrustManager[]{
new X509TrustManager() {
public void checkClientTrusted(final X509Certificate[] certs, final String authType) {
}
public void checkServerTrusted(final X509Certificate[] certs, final String authType) {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
};
private TrustManager[] getTrustManager() {
return TRUST_ALL_CERTS;
}
public Socket createSocket(final String host, final int port, final InetAddress clientHost,
final int clientPort) throws IOException {
return getSocketFactory().createSocket(host, port, clientHost, clientPort);
}
@Override
public Socket createSocket(final String host, final int port, final InetAddress localAddress,
final int localPort, final HttpConnectionParams params) throws IOException {
return createSocket(host, port);
}
public Socket createSocket(final String host, final int port) throws IOException {
return getSocketFactory().createSocket(host, port);
}
private SocketFactory getSocketFactory() throws UnknownHostException {
TrustManager[] trustAllCerts = getTrustManager();
try {
SSLContext context = SSLContext.getInstance("SSL");
context.init(null, trustAllCerts, new SecureRandom());
final SSLSocketFactory socketFactory = context.getSocketFactory();
HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
return socketFactory;
} catch (NoSuchAlgorithmException | KeyManagementException exception) {
throw new UnknownHostException(exception.getMessage());
}
}
}
Note: This is with HttpClient 3.1 and Java 8
I ran into a similar issue where I wanted to call a function defined in my controller from my view. Although it perplexed me for a while trying to figure out how to get to the controller from the view it turned out to be fairly straightforward.
I hand off an array to my views with data records that the view formats and presents to the user with jQuery DataTables (big duh). One column in the presented UI table is a set of action buttons that need to be created per row based on the content of the data in each of the rows. I guess I could have added the button definitions to the data rows as a column sent to the views but not all views needed the buttons so why? Instead, I wanted the view that needed them add them.
In the controller I pass a reference to the controller itself to the view as in
->with('callbackController', $this)
I called it callbackController as that is what I was doing. Now, inside my view I can either escape to PHP to use $callbackController to access the parent controller as in
<?php echo $callbackController->makeButtons($parameters); ?>
or just use the Blade mechanism
{!! $callbackController->makeButtons($parameters); ?>
It seems to be working fine across multiple controllers and views. I have not noticed a performance penalty using this mechanism and I have one huge table with over 50K rows.
I have not tried to pass on references to other objects (e.g., models, etc) yet but I do not see what that would not work as well
Might not be elegant but it seems to get the job done.
In Windows, if you have the shortcut in your taskbar, right-click the "Anaconda Prompt" icon, you'll see:
Right-click on "Anaconda Prompt" again.
Click "Properties"
Add the path you want your anaconda prompt to open up into in the "Start In:" section.
Note - you can also do this by searching for "Anaconda Prompt" in the Start Menu. The directions above are specifically for the shortcut.
More recently, I have found that other factors will also cause this error. I had an AES.h, AES.cpp containing a AES class and it gave this same unhelpful error. Only when I renamed to Encryption.h, Encryption.cpp and Encryption as the class name did it suddenly start working. There were no other code changes.
In my case I simply had to run the control panel as administrator
EDIT - Removed Skip(0) as it's not necessary
var queryResult = (from o in objects where ...
select new
{
A = o.a,
B = o.b
}
).Take(10);
I have utilize c# Uri class and it works, well with IP Address, localhost
public static bool CheckURLIsValid(string url)
{
Uri returnURL;
return (Uri.TryCreate(url, UriKind.Absolute, out returnURL)
&& (returnURL.Scheme == Uri.UriSchemeHttp || returnURL.Scheme == Uri.UriSchemeHttps));
}
I always use this implementors plugin to find all the implementation of an Interface
http://eclipse-tools.sourceforge.net/updates/
it's my favorite and the best
In comprehension, the nested lists iteration should follow the same order than the equivalent imbricated for loops.
To understand, we will take a simple example from NLP. You want to create a list of all words from a list of sentences where each sentence is a list of words.
>>> list_of_sentences = [['The','cat','chases', 'the', 'mouse','.'],['The','dog','barks','.']]
>>> all_words = [word for sentence in list_of_sentences for word in sentence]
>>> all_words
['The', 'cat', 'chases', 'the', 'mouse', '.', 'The', 'dog', 'barks', '.']
To remove the repeated words, you can use a set {} instead of a list []
>>> all_unique_words = list({word for sentence in list_of_sentences for word in sentence}]
>>> all_unique_words
['.', 'dog', 'the', 'chase', 'barks', 'mouse', 'The', 'cat']
or apply list(set(all_words))
>>> all_unique_words = list(set(all_words))
['.', 'dog', 'the', 'chases', 'barks', 'mouse', 'The', 'cat']
I had to import also the language:
import moment from 'moment'
import 'moment/locale/es' // without this line it didn't work
moment.locale('es')
Then use moment like you normally would
alert(moment(date).fromNow())
In addition to the above answers, I would say for columns having no single word name, you may use:-
df[df['Product ID'].str.contains("foo") == True]
Hope this helps.
I've written a library that is up-to-date, since all the other answers are outdated:
I faced the same issue, though I had local.properties file in my main module, and ANDROID_HOME environment variable set at system level.
What fixed this problem was when I copied the local.properties file which was in my main project module to the root of the whole project (i.e the directory parent to your main module)
Try copying the local.properties file inside modules and the root directory. Should work.
Several answers here use range
. xrange
is generally better as it returns a generator, rather than a fully-instantiated list. Where memory and or iterables of widely-varying lengths can be an issue, xrange
is superior.
If you are already using Newtonsoft.Json
and don't want to install Microsoft.AspNet.WebApi.Client
:
var myInstance = JsonConvert.DeserializeObject<MyClass>(
await response.Content.ReadAsStringAsync());
I had this issue with a facebook application that I was developing for a fan page tab. If anyone faces this issue with a facebook application then
1-goto https://developers.facebook.com
2-select the application that you are developing
3-make sure that all the link to your application has tailing slash /
my issue was in the https://developers.facebook.com->Apps->MYAPPNAME->settings->Page Tab->Secure Page Tab URL, Page Tab Edit URL, Page Tab URL hope this will help
The name of the array indicates the starting address. Starting address of both namet2
and nameIt2
are different. So the equal to (==
) operator checks whether the addresses are the same or not. For comparing two strings, a better way is to use strcmp()
, or we can compare character by character using a loop.
May be I come later to answer but right now I'm facing with this... if helps there are one more solution (the way i solved it).
var query2 = (
from users in Repo.T_Benutzer
join mappings in Repo.T_Benutzer_Benutzergruppen on mappings.BEBG_BE equals users.BE_ID into tmpMapp
join groups in Repo.T_Benutzergruppen on groups.ID equals mappings.BEBG_BG into tmpGroups
from mappings in tmpMapp.DefaultIfEmpty()
from groups in tmpGroups.DefaultIfEmpty()
select new
{
UserId = users.BE_ID
,UserName = users.BE_User
,UserGroupId = mappings.BEBG_BG
,GroupName = groups.Name
}
);
By the way, I tried using the Stefan Steiger code which also helps but it was slower as hell.
in order to capture key events of ALL text fields in a JFrame, one can employ a key event post processor. Here is a working example, after you add the obvious includes.
public class KeyListenerF1Demo extends JFrame implements KeyEventPostProcessor {
public static final long serialVersionUID = 1L;
public KeyListenerF1Demo() {
setTitle(getClass().getName());
// Define two labels and two text fields all in a row.
setLayout(new FlowLayout());
JLabel label1 = new JLabel("Text1");
label1.setName("Label1");
add(label1);
JTextField text1 = new JTextField(10);
text1.setName("Text1");
add(text1);
JLabel label2 = new JLabel("Text2");
label2.setName("Label2");
add(label2);
JTextField text2 = new JTextField(10);
text2.setName("Text2");
add(text2);
// Register a key event post processor.
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.addKeyEventPostProcessor(this);
}
public static void main(String[] args) {
JFrame f = new KeyListenerF1Demo();
f.setName("MyFrame");
f.pack();
f.setVisible(true);
}
@Override
public boolean postProcessKeyEvent(KeyEvent ke) {
// Check for function key F1 pressed.
if (ke.getID() == KeyEvent.KEY_PRESSED
&& ke.getKeyCode() == KeyEvent.VK_F1) {
// Get top level ancestor of focused element.
Component c = ke.getComponent();
while (null != c.getParent())
c = c.getParent();
// Output some help.
System.out.println("Help for " + c.getName() + "."
+ ke.getComponent().getName());
// Tell keyboard focus manager that event has been fully handled.
return true;
}
// Let keyboard focus manager handle the event further.
return false;
}
}
Use LocalDate
from java.time, the modern Java date and time API, for a date
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MMMM d, u", Locale.ENGLISH);
LocalDate date = LocalDate.parse("June 27, 2007", dateFormatter);
System.out.println(date);
Output:
2007-06-27
As others have said already, remember to specify an English-speaking locale when your string is in English. A LocalDate
is a date without time of day, so a lot better suitable for the date from your string than the old Date
class. Despite its name a Date
does not represent a date but a point in time that falls on at least two different dates in different time zones of the world.
Only if you need an old-fashioned Date
for an API that you cannot afford to upgrade to java.time just now, convert like this:
Instant startOfDay = date.atStartOfDay(ZoneId.systemDefault()).toInstant();
Date oldfashionedDate = Date.from(startOfDay);
System.out.println(oldfashionedDate);
Output in my time zone:
Wed Jun 27 00:00:00 CEST 2007
Oracle tutorial: Date Time explaining how to use java.time.
If number is int use
"" + parseInt(str)
If the number is float use
"" + parseFloat(str)
In Angular you can define event listeners
like in the example below:
<!-- Here you can call public methods from parental component -->
<input (change)="method_name()">
The URI is encoded as UTF-8, but Tomcat is decoding them as ISO-8859-1. You need to edit the connector settings in the server.xml and add the URIEncoding="UTF-8" attribute.
or edit this parameter on your application.properties
server.tomcat.uri-encoding=utf-8
This can also happen when you forget to make a first commit.
Use the latest scope provided by Laravel out of the box.
Model::latest()->first();
That way you're not retrieving all the records. A nicer shortcut to orderBy.
It is a syntax sugar for faster query writing. Its implementation in pseudocode:
def filter_by(self, **kwargs):
return self.filter(sql.and_(**kwargs))
For AND you can simply write:
session.query(db.users).filter_by(name='Joe', surname='Dodson')
btw
session.query(db.users).filter(or_(db.users.name=='Ryan', db.users.country=='England'))
can be written as
session.query(db.users).filter((db.users.name=='Ryan') | (db.users.country=='England'))
Also you can get object directly by PK via get
method:
Users.query.get(123)
# And even by a composite PK
Users.query.get(123, 321)
When using get
case its important that object can be returned without database request from identity map
which can be used as cache(associated with transaction)
I found a purely Javascript solution here that seems to work for major browsers for both PC and Mac. I tested it in BrowserStack for both platforms and it works like a dream. The Javascript solution posted in this thread by Jason D'Souza is really nice because it gives you a lot of information about the browser, but it has an issue identifying Edge which seems to look like Chrome to it. His code could probably be modified a bit with this solution to make it work for Edge too. Here is the snippet of code I found:
var browser = (function (agent) {
switch (true) {
case agent.indexOf("edge") > -1: return "edge";
case agent.indexOf("edg") > -1: return "chromium based edge (dev or canary)";
case agent.indexOf("opr") > -1 && !!window.opr: return "opera";
case agent.indexOf("chrome") > -1 && !!window.chrome: return "chrome";
case agent.indexOf("trident") > -1: return "ie";
case agent.indexOf("firefox") > -1: return "firefox";
case agent.indexOf("safari") > -1: return "safari";
default: return "other";
}
})(window.navigator.userAgent.toLowerCase());
console.log(window.navigator.userAgent.toLowerCase() + "\n" + browser);
You could use pandas plot as @Bharath suggest:
import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)
Output:
Updated:
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Updated Pandas 0.21.0+ reindex_axis
is deprecated, use reindex
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Output:
For all those working with implicit rules (and GNU MAKE). Here is a simple makefile which supports different directories:
#Start of the makefile
VPATH = ./src:./header:./objects
OUTPUT_OPTION = -o objects/$@
CXXFLAGS += -Wall -g -I./header
Target = $(notdir $(CURDIR)).exe
Objects := $(notdir $(patsubst %.cpp,%.o,$(wildcard src/*.cpp)))
all: $(Target)
$(Target): $(Objects)
$(CXX) $(CXXFLAGS) -o $(Target) $(addprefix objects/,$(Objects))
#Beware of -f. It skips any confirmation/errors (e.g. file does not exist)
.PHONY: clean
clean:
rm -f $(addprefix objects/,$(Objects)) $(Target)
Lets have a closer look (I will refer to the current Directory with curdir):
This line is used to get a list of the used .o files which are in curdir/src.
Objects := $(notdir $(patsubst %.cpp,%.o,$(wildcard src/*.cpp)))
#expands to "foo.o myfoo.o otherfoo.o"
Via variable the output is set to a different directory (curdir/objects).
OUTPUT_OPTION = -o objects/$@
#OUTPUT_OPTION will insert the -o flag into the implicit rules
To make sure the compiler finds the objects in the new objects folder, the path is added to the filename.
$(Target): $(Objects)
$(CXX) $(CXXFLAGS) -o $(Target) $(addprefix objects/,$(Objects))
# ^^^^^^^^^^^^^^^^^^^^
This is meant as an example and there is definitly room for improvement.
For additional Information consult: Make documetation. See chapter 10.2
I strongly recommend BOUML which:
Ok, after struggling for a long time with the stupid pickerview in iOS 4, I've decided to change my control into simple table: here is the code:
ComboBoxView.m = which is actually looks more like pickerview.
//
// ComboBoxView.m
// iTrophy
//
// Created by Gal Blank on 8/18/10.
//
#import "ComboBoxView.h"
#import "AwardsStruct.h"
@implementation ComboBoxView
@synthesize displayedObjects;
#pragma mark -
#pragma mark Initialization
/*
- (id)initWithStyle:(UITableViewStyle)style {
// Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
if ((self = [super initWithStyle:style])) {
}
return self;
}
*/
#pragma mark -
#pragma mark View lifecycle
/*
- (void)viewDidLoad {
[super viewDidLoad];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
*/
/*
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
return [[self displayedObjects] count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *MyIdentifier = [NSString stringWithFormat:@"MyIdentifier %i", indexPath.row];
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
//cell.contentView.frame = CGRectMake(0, 0, 230.0,16);
UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(0, 5, 230.0,19)] autorelease];
VivatAwardsStruct *vType = [displayedObjects objectAtIndex:indexPath.row];
NSString *section = [vType awardType];
label.tag = 1;
label.font = [UIFont systemFontOfSize:17.0];
label.text = section;
label.textAlignment = UITextAlignmentCenter;
label.baselineAdjustment = UIBaselineAdjustmentAlignCenters;
label.adjustsFontSizeToFitWidth=YES;
label.textColor = [UIColor blackColor];
//label.autoresizingMask = UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label];
//UIImage *image = nil;
label.backgroundColor = [UIColor whiteColor];
//image = [awards awardImage];
//image = [image imageScaledToSize:CGSizeMake(32.0, 32.0)];
//[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
//UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
//cell.accessoryView = imageView;
//[imageView release];
}
return cell;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
*/
}
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Relinquish ownership any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
@end
Here is the .h file for that:
//
// ComboBoxView.h
// iTrophy
//
// Created by Gal Blank on 8/18/10.
//
#import <UIKit/UIKit.h>
@interface ComboBoxView : UITableViewController {
NSMutableArray *displayedObjects;
}
@property (nonatomic, retain) NSMutableArray *displayedObjects;
@end
now, in the ViewController where I had Apple UIPickerView I replaced with my own ComboBox view and made it size what ever I wish.
ComboBoxView *mypickerholder = [[ComboBoxView alloc] init];
[mypickerholder.view setFrame:CGRectMake(50, 220, 230, 80)];
[mypickerholder setDisplayedObjects:awardTypesArray];
that's it, now the only thing is left is to create a member variable in the combobox view that will hold current row selection, and we are good to go.
Enjoy everyone.
In your Execute SQL Task, make sure SQLSourceType is set to Direct Input, then your SQL Statement is the name of the stored proc, with questionmarks for each paramter of the proc, like so:
Click the parameter mapping in the left column and add each paramter from your stored proc and map it to your SSIS variable:
Now when this task runs it will pass the SSIS variables to the stored proc.
It seems that google-services:4.1.0
has an issue. Either downgrade it to
classpath 'com.google.gms:google-services:4.0.0'
or upgrade it to
classpath 'com.google.gms:google-services:4.2.0'
dependencies {
classpath 'com.android.tools.build:gradle:3.3.0-alpha08'
classpath 'com.google.gms:google-services:4.2.0'
/*classpath 'com.google.gms:google-services:4.1.0' <-- this was the problem */
}
Hope it helps
Put a single listener on the table. When it gets a click from an input with a button that has a name of "edit" and value "edit", change its value to "modify". Get rid of the input's id (they aren't used for anything here), or make them all unique.
<script type="text/javascript">
function handleClick(evt) {
var node = evt.target || evt.srcElement;
if (node.name == 'edit') {
node.value = "Modify";
}
}
</script>
<table id="table1" border="1" onclick="handleClick(event);">
<thead>
<tr>
<th>Select
</thead>
<tbody>
<tr>
<td>
<form name="f1" action="#" >
<input id="edit1" type="submit" name="edit" value="Edit">
</form>
<tr>
<td>
<form name="f2" action="#" >
<input id="edit2" type="submit" name="edit" value="Edit">
</form>
<tr>
<td>
<form name="f3" action="#" >
<input id="edit3" type="submit" name="edit" value="Edit">
</form>
</tbody>
</table>
I had a case where Process.HasExited
didn't change after closing the window belonging to the process. So Process.WaitForExit()
also didn't work. I had to monitor Process.Responding
that went to false after closing the window like that:
while (!_process.HasExited && _process.Responding) {
Thread.Sleep(100);
}
...
Perhaps this helps someone.
Here is my answer:
Brief: I was using typeorm
as a ORM library. So, to set the query logging level I have used the following option instead of directly setting the logging option as false
.
Solution: File name - ormconfig.ts
{
'type': process.env.DB_DRIVER,
'host': process.env.DB_HOST,
'port': process.env.DB_PORT,
'username': process.env.DB_USER,
'password': process.env.DB_PASS,
'database': process.env.DB_NAME,
'migrations': [process.env.MIGRATIONS_ENTITIES],
'synchronize': false,
'logging': process.env.DB_QUERY_LEVEL,
'entities': [
process.env.ORM_ENTITIES
],
'cli': {
'migrationsDir': 'migrations'
}
}
And, in the envrionment variable set the DB_QUERY_LEVEL
as ["query", "error"].
Result: As a result it will log only when the query has error else it won't.
Ref link: typeorm db query logging doc
Hope this helps! Thanks.
If you want it without the year:
DateTime.Now.ToString("MM/DD");
DateTime.ToString() has a lot of cool format strings:
I got same error after publish my project to my physical server. My web application works perfectly on my computer when I compile on VS2013
. When I checked connection string on sql server manager, everything works perfect on server too. I also checked firewall (I switched it off). But still didn't work. I remotely try to connect database by SQL Manager with exactly same user/pass and instance name etc with protocol pipe/tcp and I saw that everything working normally. But when I try to open website I'm getting this error. Is there anyone know 4th option for fix this problem?.
NOTE: My App: ASP.NET 4.5 (by VS2013)
, Server: Windows 2008 R2 64bit
, SQL: MS-SQL WEB 2012 SP1
Also other web applications works great at web browsers with their database on same server.
After one day suffering I found the solution of my issue:
First I checked all the logs and other details but i could find nothing. Suddenly I recognize that; when I try to use connection string which is connecting directly to published DB and run application on my computer by VS2013, I saw that it's connecting another database file. I checked local directories and I found it. ASP.NET Identity not using my connection string as I wrote in web.config file. And because of this VS2013 is creating or connecting a new database with the name "DefaultConnection.mdf" in App_Data folder. Then I found the solution, it was in IdentityModel.cs.
I changed code as this:
public class ApplicationUser : IdentityUser
{
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
//public ApplicationDbContext() : base("DefaultConnection") ---> this was original
public ApplicationDbContext() : base("<myConnectionStringNameInWebConfigFile>") //--> changed
{
}
}
So, after all, I re-builded and published my project and everything works fine now :)
You can chain commands:mkdir ~/bar/baz | mv foo.c ~/bar/baz/
or shell script is here:
#!/bin/bash
mkdir $2 | mv $1 $2
1. Open any text editor
2. Copy-paste shell script.
3. Save it as mkdir_mv.sh
4. Enter your script's directory: cd your/script/directory
5. Change file mode : chmod +x mkdir_mv.sh
6. Set alias: alias mv="./mkdir_mv.sh"
Now, whenever you run command mv
moving directory will be created if does not exists.
I'm using Rails 4.2, and could not get the footable icons to show up. Little boxes were showing, instead of the (+) on collapsed rows and the little sorting arrows I expected. After studying the information here, I made one simple change to my code: remove the font directory in css. That is, change all the css entries like this:
src:url('fonts/footable.eot');
to look like this:
src:url('footable.eot');
It worked. I think Rails 4.2 already assumes the font directory, so specifying it again in the css code makes the font files not get found. Hope this helps.
Rob Heiser suggested checking out your java version by using 'java -version'.
That will identify the Java version that will be commonly found and used. Doing dev work, you can often have more than one version installed (I currently have 2 JREs - 6 and 7 - and may soon have 8).
http://www.coderanch.com/t/453224/java/java/java-version-work-setting-path
java -version will look for java.exe in the System32 directory in Windows. That's where a JRE will install it.
I'm assuming that IE either simply looks for java and that automatically starts checking in System32 or it'll use the path and hit whichever java.exe comes first in your path (if you tamper with the path to point to another JRE).
Also from what SLaks said, I would disagree with one thing. There is likely slightly better performance out of 64-it IE in 64-bit environments. So there is some reason for using it.
I had a similar problem, the annotation @Autowired
in the test code did not work under using the Maven command line while it worked fine in Eclipse. I just update my JUnit version from 4.4 to 4.9 and the problem was solved.
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
</dependency>
Try this:
SELECT Count(*)
FROM <DATABASE_NAME>.INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
Use %0A
(URL encoding) instead of \n
(C encoding).
Well, in java, you can also create a parameterized enum. Say you want to create a className enum, in which you need to store classCode as well as className, you can do that like this:
public enum ClassEnum {
ONE(1, "One"),
TWO(2, "Two"),
THREE(3, "Three"),
FOUR(4, "Four"),
FIVE(5, "Five")
;
private int code;
private String name;
private ClassEnum(int code, String name) {
this.code = code;
this.name = name;
}
public int getCode() {
return code;
}
public String getName() {
return name;
}
}
The quickest (and most flexible) way is to use np.where, which chooses between two arrays according to a mask(array of true and false values):
import numpy as np
a = np.random.randint(0, 5, size=(5, 4))
b = np.where(a<3,0,1)
print('a:',a)
print()
print('b:',b)
which will produce:
a: [[1 4 0 1]
[1 3 2 4]
[1 0 2 1]
[3 1 0 0]
[1 4 0 1]]
b: [[0 1 0 0]
[0 1 0 1]
[0 0 0 0]
[1 0 0 0]
[0 1 0 0]]
Better approach may be a polyfill like this
jQuery.fn.load = function(callback){ $(window).on("load", callback) };
With this you can leave the legacy code untouched. If you use webpack be sure to use script-loader.
Both
-Djavax.net.ssl.trustStore=path/to/trustStore.jks
and
System.setProperty("javax.net.ssl.trustStore", "cacerts.jks");
do the same thing and have no difference working wise. In your case you just have a typo. You have misspelled trustStore
in javax.net.ssl.trustStore.
In addition to max, you can also sort:
>>> lis
[(101, 153), (255, 827), (361, 961)]
>>> sorted(lis,key=lambda x: x[1], reverse=True)[0]
(361, 961)
There are several different varieties of CRC-16. See wiki page.
Every of those will return different results from the same input.
So you must carefully select correct one for your program.
Easiest solution:
app.disable('etag');
Alternate solution here if you want more control:
You can use cURL and CRON to run .php files at set times.
Here's an example of what cURL needs to run the .php file:
curl http://localhost/myscript.php
Then setup the CRON job to run the above cURL:
nano -w /var/spool/cron/root
or
crontab -e
Followed by:
01 * * * * /usr/bin/curl http://www.yoursite.com/script.php
For more info about, check out this post: https://www.scalescale.com/tips/nginx/execute-php-scripts-automatically-using-cron-curl/
For more info about cURL: What is cURL in PHP?
For more info about CRON: http://code.tutsplus.com/tutorials/scheduling-tasks-with-cron-jobs--net-8800
Also, if you would like to learn about setting up a CRON job on your hosted server, just inquire with your host provider, and they may have a GUI for setting it up in the c-panel (such as http://godaddy.com, or http://1and1.com/ )
NOTE: Technically I believe you can setup a CRON job to run the .php file directly, but I'm not certain.
Best of luck with the automatic PHP running :-)
A little bit deeper with 'SC' command, we are able to extract all 'Services Name' and got all 'QueryServiceConfig' :)
>SC QUERY > "%computername%-services.txt" [enter]
>FIND "SERVICE_NAME: " "%computername%-services.txt" /i > "%computername%-services-name.txt" [enter]
>NOTEPAD2 "%computername%-services-name.txt" [enter]
Then, continue with 'CMD'..
>FOR /F "DELIMS= SKIP=2" %S IN ('TYPE "%computername%-services-name.txt"') DO @SC QC "%S" >> "%computername%-services-list-config.txt" [enter]
>NOTEPAD2 "%computername%-services-list-config.txt" [enter]
Raw data is ready for feeding 'future batch file' so the result is look like this below!!!
+ -------------+-------------------------+---------------------------+---------------+--------------------------------------------------+------------------+-----+----------------+--------------+--------------------+
| SERVICE_NAME | TYPE | START_TYPE | ERROR_CONTROL | BINARY_PATH_NAME | LOAD_ORDER_GROUP | TAG | DISPLAY_NAME | DEPENDENCIES | SERVICE_START_NAME |
+ -------------+-------------------------+---------------------------+---------------+--------------------------------------------------+------------------+-----+----------------+--------------+--------------------+
+ WSearch | 10 WIN32_OWN_PROCESS | 2 AUTO_START (DELAYED) | 1 NORMAL | C:\Windows\system32\SearchIndexer.exe /Embedding | none | 0 | Windows Search | RPCSS | LocalSystem |
+ wuauserv | 20 WIN32_SHARE_PROCESS | 2 AUTO_START (DELAYED) | 1 NORMAL | C:\Windows\system32\svchost.exe -k netsvcs | none | 0 | Windows Update | rpcss | LocalSystem |
But, HTML will be pretty easier :D
Any bright ideas for improvement are welcome V^_^
If you put constrains on a generic class or method, every other generic class or method that is using it need to have "at least" those constrains.
Yes, use source or the short form which is just .
:
. other_script.sh
sleep()
causes the thread to definitely stop executing for a given amount of time; if no other thread or process needs to be run, the CPU will be idle (and probably enter a power saving mode).
yield()
basically means that the thread is not doing anything particularly important and if any other threads or processes need to be run, they should. Otherwise, the current thread will continue to run.
Try this
HTML
<select class="form-control"name="country">
<option class="servce_pro_disabled">Select Country</option>
<option class="servce_pro_disabled" value="Aruba" id="cl_country_option">Aruba</option>
</select>
CSS
.form-control option:first-child {
display: none;
}
If you are having this problem and are using Qt - you need to link qtmain.lib or qtmaind.lib
The ::
are used to dereference scopes.
const int x = 5;
namespace foo {
const int x = 0;
}
int bar() {
int x = 1;
return x;
}
struct Meh {
static const int x = 2;
}
int main() {
std::cout << x; // => 5
{
int x = 4;
std::cout << x; // => 4
std::cout << ::x; // => 5, this one looks for x outside the current scope
}
std::cout << Meh::x; // => 2, use the definition of x inside the scope of Meh
std::cout << foo::x; // => 0, use the definition of x inside foo
std::cout << bar(); // => 1, use the definition of x inside bar (returned by bar)
}
unrelated: cout and cin are not functions, but instances of stream objects.
EDIT fixed as Keine Lust suggested
The parameterless form of the change() method triggers a change
event. You can write something like:
$(document).ready(function() {
$("#yourInitialElementID").change(function() {
// Do something here...
$(".yourDropDownClass").change();
});
});
There is also some more detail on the use of <mvc:annotation-driven />
in the Spring docs. In a nutshell, <mvc:annotation-driven />
gives you greater control over the inner workings of Spring MVC. You don't need to use it unless you need one or more of the features outlined in the aforementioned section of the docs.
Also, there are other "annotation-driven" tags available to provide additional functionality in other Spring modules. For example, <transaction:annotation-driven />
enables the use of the @Transaction annotation, <task:annotation-driven />
is required for @Scheduled et al...
You can use three things to mimic disabled:
HTML: readonly
attribute (so that the value present in input can be used on form submission. Also the user can't change the input value)
CSS: 'pointer-events':'none'
(blocking the user from clicking the input)
HTML: tabindex="-1"
(blocking the user to navigate to the input from the keyboard)
I submit that it is better to leave your data stacked as it is:
df = pandas.DataFrame(data, columns=['R_Number', 'C_Number', 'Avg', 'Std'])
# Possibly also this if these can always be the indexes:
# df = df.set_index(['R_Number', 'C_Number'])
Then it's a bit more intuitive to say
df.set_index(['R_Number', 'C_Number']).Avg.unstack(level=1)
This way it is implicit that you're seeking to reshape the averages, or the standard deviations. Whereas, just using pivot
, it's purely based on column convention as to what semantic entity it is that you are reshaping.
I'm looking for the fastest way of inserting into Entity Framework
There are some third-party libraries supporting Bulk Insert available:
See: Entity Framework Bulk Insert library
Be careful, when choosing a bulk insert library. Only Entity Framework Extensions supports all kind of associations and inheritances and it's the only one still supported.
Disclaimer: I'm the owner of Entity Framework Extensions
This library allows you to perform all bulk operations you need for your scenarios:
Example
// Easy to use
context.BulkSaveChanges();
// Easy to customize
context.BulkSaveChanges(bulk => bulk.BatchSize = 100);
// Perform Bulk Operations
context.BulkDelete(customers);
context.BulkInsert(customers);
context.BulkUpdate(customers);
// Customize Primary Key
context.BulkMerge(customers, operation => {
operation.ColumnPrimaryKeyExpression =
customer => customer.Code;
});
search()
is a String method.
You are executing the attr
function on every <li>
element.
You need to invoke each
and use the this
reference within.
Example:
$('li').each(function() {
var isFound = $(this).attr('title').search(/string/i);
//do something based on isFound...
});