Example of how it's implemented on wellsfargo.com:
try {
if (window.document.documentElement.getAttribute("webdriver")) return !+[]
} catch (IDLMrxxel) {}
try {
if ("_Selenium_IDE_Recorder" in window) return !+""
} catch (KknKsUayS) {}
try {
if ("__webdriver_script_fn" in document) return !+""
You have correctly used "CURLOPT_COOKIEJAR" (writing) but you also need to set "CURLOPT_COOKIEFILE" (reading)
curl_setopt ($ch, CURLOPT_COOKIEJAR, COOKIE_FILE);
curl_setopt ($ch, CURLOPT_COOKIEFILE, COOKIE_FILE);
I'm sad to say: We are sh*t out of luck on this one.
I'd like to refer you to the author of WhichBrowser: Everybody lies.
Basically, no browser is being honest. No matter if you use Chrome or IE, they both will tell you that they are "Mozilla Netscape" with Gecko and Safari support. Try it yourself on any of the fiddles flying around in this thread:
or any other... Try it with Chrome (which might still succeed), then try it with a recent version of IE, and you will cry. Of course, there are heuristics, to get it all right, but it will be tedious to grasp all the edge cases, and they will very likely not work anymore in a year's time.
Take your code, for example:
<div id="example"></div>
<script type="text/javascript">
txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
document.getElementById("example").innerHTML=txt;
</script>
Chrome says:
Browser CodeName: Mozilla
Browser Name: Netscape
Browser Version: 5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36
Cookies Enabled: true
Platform: Win32
User-agent header: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36
IE says:
Browser CodeName: Mozilla
Browser Name: Netscape
Browser Version: 5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; rv:11.0) like Gecko
Cookies Enabled: true
Platform: Win32
User-agent header: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; rv:11.0) like Gecko
At least Chrome still has a string that contains "Chrome" with the exact version number. But, for IE you must extrapolate from the things it supports to actually figure it out (who else would boast that they support .NET
or Media Center
:P), and then match it against the rv:
at the very end to get the version number. Of course, even such sophisticated heuristics might very likely fail as soon as IE 12 (or whatever they want to call it) comes out.
SSL development libraries have to be installed
CentOS:
$ yum install openssl-devel libffi-devel
Ubuntu:
$ apt-get install libssl-dev libffi-dev
OS X (with Homebrew installed):
$ brew install openssl
I spent a lot of time looking for a solution to this problem too. Here's what i've found thus far:
If you want your users to be able to click on a button and copy some text, you may have to use Flash.
If you want your users to press Ctrl+C anywhere on the page, but always copy xyz to the clipboard, I wrote an all-JS solution in YUI3 (although it could easily be ported to other frameworks, or raw JS if you're feeling particularly self-loathing).
It involves creating a textbox off the screen which gets highlighted as soon as the user hits Ctrl/CMD. When they hit 'C' shortly after, they copy the hidden text. If they hit 'V', they get redirected to a container (of your choice) before the paste event fires.
This method can work well, because while you listen for the Ctrl/CMD keydown anywhere in the body, the 'A', 'C' or 'V' keydown listeners only attach to the hidden text box (and not the whole body). It also doesn't have to break the users expectations - you only get redirected to the hidden box if you had nothing selected to copy anyway!
Here's what i've got working on my site, but check http://at.cg/js/clipboard.js for updates if there are any:
YUI.add('clipboard', function(Y) {
// Change this to the id of the text area you would like to always paste in to:
pasteBox = Y.one('#pasteDIV');
// Make a hidden textbox somewhere off the page.
Y.one('body').append('<input id="copyBox" type="text" name="result" style="position:fixed; top:-20%;" onkeyup="pasteBox.focus()">');
copyBox = Y.one('#copyBox');
// Key bindings for Ctrl+A, Ctrl+C, Ctrl+V, etc:
// Catch Ctrl/Window/Apple keydown anywhere on the page.
Y.on('key', function(e) {
copyData();
// Uncomment below alert and remove keyCodes after 'down:' to figure out keyCodes for other buttons.
// alert(e.keyCode);
// }, 'body', 'down:', Y);
}, 'body', 'down:91,224,17', Y);
// Catch V - BUT ONLY WHEN PRESSED IN THE copyBox!!!
Y.on('key', function(e) {
// Oh no! The user wants to paste, but their about to paste into the hidden #copyBox!!
// Luckily, pastes happen on keyPress (which is why if you hold down the V you get lots of pastes), and we caught the V on keyDown (before keyPress).
// Thus, if we're quick, we can redirect the user to the right box and they can unload their paste into the appropriate container. phew.
pasteBox.select();
}, '#copyBox', 'down:86', Y);
// Catch A - BUT ONLY WHEN PRESSED IN THE copyBox!!!
Y.on('key', function(e) {
// User wants to select all - but he/she is in the hidden #copyBox! That wont do.. select the pasteBox instead (which is probably where they wanted to be).
pasteBox.select();
}, '#copyBox', 'down:65', Y);
// What to do when keybindings are fired:
// User has pressed Ctrl/Meta, and is probably about to press A,C or V. If they've got nothing selected, or have selected what you want them to copy, redirect to the hidden copyBox!
function copyData() {
var txt = '';
// props to Sabarinathan Arthanari for sharing with the world how to get the selected text on a page, cheers mate!
if (window.getSelection) { txt = window.getSelection(); }
else if (document.getSelection) { txt = document.getSelection(); }
else if (document.selection) { txt = document.selection.createRange().text; }
else alert('Something went wrong and I have no idea why - please contact me with your browser type (Firefox, Safari, etc) and what you tried to copy and I will fix this immediately!');
// If the user has nothing selected after pressing Ctrl/Meta, they might want to copy what you want them to copy.
if(txt=='') {
copyBox.select();
}
// They also might have manually selected what you wanted them to copy! How unnecessary! Maybe now is the time to tell them how silly they are..?!
else if (txt == copyBox.get('value')) {
alert('This site uses advanced copy/paste technology, possibly from the future.\n \nYou do not need to select things manually - just press Ctrl+C! \n \n(Ctrl+V will always paste to the main box too.)');
copyBox.select();
} else {
// They also might have selected something completely different! If so, let them. It's only fair.
}
}
});
Hope someone else finds this useful :]
Setting up a simple reverse proxy on the server, will allow the browser to use relative paths for the Ajax requests, while the server would be acting as a proxy to any remote location.
If using mod_proxy in Apache, the fundamental configuration directive to set up a reverse proxy is the ProxyPass
. It is typically used as follows:
ProxyPass /ajax/ http://other-domain.com/ajax/
In this case, the browser would be able to request /ajax/web_service.xml
as a relative URL, but the server would serve this by acting as a proxy to http://other-domain.com/ajax/web_service.xml
.
One interesting feature of the this method is that the reverse proxy can easily distribute requests towards multiple back-ends, thus acting as a load balancer.
It looks like you took the code from Greasemonkey\JavaScript Copy to Clipboard button or the original source of this snippet...
This code was for Greasemonkey, hence the unsafeWindow. And I guess the syntax error in Internet Explorer comes from the const
keyword which is specific to Firefox (replace it with var
).
Unfortunately, ­
's support is so inconsistent between browsers that it can't really be used.
QuirksMode is right -- there's no good way to use soft hyphens in HTML right now. See what you can do to go without them.
2013 edit: According to QuirksMode, ­
now works/is supported on all major browsers.
Suppose you want to see the difference between commits 012345 and abcdef. The following should do what you want:
$ git checkout 012345 $ git cherry-pick -n abcdef $ git diff --cached
if you are using extracted tomcat then,
startup.sh
and shutdown.sh
are two script located in TOMCAT/bin/ to start and shutdown tomcat, You could use that
if tomcat is installed then
/etc/init.d/tomcat5.5 start
/etc/init.d/tomcat5.5 stop
/etc/init.d/tomcat5.5 restart
In my opinion the best solutions is in this link: http://www.myonlinetraininghub.com/excel-factor-12-secret-evaluate-function
Here is a summary: 1) In cell A1 enter 1, 2) In cell A2 enter 2, 3) In cell A3 enter +, 4) Create a named range, with "=Evaluate(A1 & A3 & A2)" in the refers to field while creating the named range. Lets call this named range "testEval", 5) In cell A4 enter =testEval,
Cell A4 should have the value 3 in it.
Notes: a) Requires no programming/vba. b) I did this in Excel 2013 and it works.
CASE
is an expression - it returns a single scalar value (per row). It can't return a complex part of the parse tree of something else, like an ORDER BY
clause of a SELECT
statement.
It looks like you just need:
ORDER BY
CASE WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount END desc,
CASE WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount END desc,
Case WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount END DESC,
CASE WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount END DESC,
Case WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount END DESC,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC
Or possibly:
ORDER BY
CASE
WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount
WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount
WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount
WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount
WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount
END desc,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC
It's a little tricky to tell which of the above (or something else) is what you're looking for because you've a) not explained what actual sort order you're trying to achieve, and b) not supplied any sample data and expected results, from which we could attempt to deduce the actual sort order you're trying to achieve.
This may be the answer we're looking for:
ORDER BY
CASE
WHEN TblList.PinRequestCount <> 0 THEN 5
WHEN TblList.HighCallAlertCount <> 0 THEN 4
WHEN TblList.HighAlertCount <> 0 THEN 3
WHEN TblList.MediumCallAlertCount <> 0 THEN 2
WHEN TblList.MediumAlertCount <> 0 THEN 1
END desc,
CASE
WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount
WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount
WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount
WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount
WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount
END desc,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC
Although it works, the current solution is a little overkill as noted in some comments. So here is an alternative that works for me, using the latest Spring Boot (1.4.3).
The default security password is configured inside Spring Boot's AuthenticationManagerConfiguration class. This class has a conditional annotation to prevent from loading if a AuthenticationManager Bean is already defined.
The folllowing code works to prevent execution of the code inside AuthenticationManagerConfiguration because we define our current AuthenticationManager as a bean.
@Configuration
@EnableWebSecurity
public class MyCustomSecurityConfig extends WebSecurityConfigurerAdapter{
[...]
@Override
protected void configure(AuthenticationManagerBuilder authManager) throws Exception {
// This is the code you usually have to configure your authentication manager.
// This configuration will be used by authenticationManagerBean() below.
}
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
// ALTHOUGH THIS SEEMS LIKE USELESS CODE,
// IT'S REQUIRED TO PREVENT SPRING BOOT AUTO-CONFIGURATION
return super.authenticationManagerBean();
}
}
You can either use a double backslash each time
string foo = "D:\\Projects\\Some\\Kind\\Of\\Pathproblem\\wuhoo.xml";
or use the @ symbol
string foo = @"D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";
Yes in SQl <> is the same as != which is not equal.....excepts for NULLS of course, in that case you need to use IS NULL or IS NOT NULL
Console.WriteLine(curr.ToString("HH:mm"));
Sometimes https and http ports can be same because if two tags are given same ports
IISExpressSSLPort
and DevelopmentServerPort
Make sure these two ports have different ports
then in IISUrl
use your default port either HTTP or HTTPS
https://localhost:44365
IISExpressSSLPort
DevelopmentServerPort
Then you may delete hidden .vs folder in solution folder
Since Eclipse Neon which contains Eclipse Maven Integration (m2e) 1.7, the preferred way is one of the following ways:
.project
) as well as for non-Eclipse projects that only contain the file pom.xml
.It's as simple as adding a line to your ~/.vimrc
:
colorscheme color_scheme_name
Use the FolderExists
method of the Scripting
object.
Public Function dirExists(s_directory As String) As Boolean
Dim oFSO As Object
Set oFSO = CreateObject("Scripting.FileSystemObject")
dirExists = oFSO.FolderExists(s_directory)
End Function
You need to start by understanding that the target of a symlink is a pathname. And it can be absolute or relative to the directory which contains the symlink
Assuming you have foo.conf in sites-available
Try
cd sites-enabled
sudo ln -s ../sites-available/foo.conf .
ls -l
Now you will have a symlink in sites-enabled called foo.conf which has a target ../sites-available/foo.conf
Just to be clear, the normal configuration for Apache is that the config files for potential sites live in sites-available and the symlinks for the enabled sites live in sites-enabled, pointing at targets in sites-available. That doesn't quite seem to be the case the way you describe your setup, but that is not your primary problem.
If you want a symlink to ALWAYS point at the same file, regardless of the where the symlink is located, then the target should be the full path.
ln -s /etc/apache2/sites-available/foo.conf mysimlink-whatever.conf
Here is (line 1 of) the output of my ls -l /etc/apache2/sites-enabled:
lrwxrwxrwx 1 root root 26 Jun 24 21:06 000-default -> ../sites-available/default
See how the target of the symlink is relative to the directory that contains the symlink (it starts with ".." meaning go up one directory).
Hardlinks are totally different because the target of a hardlink is not a directory entry but a filing system Inode.
I had the same problems, but using easy_install "module"
solved the problem for me.
I am not sure why, but pip and easy_install use different install locations, and easy_install chose the right ones.
Edit: without re-checking but because of the comments; it seems that different (OSX and brew-installed) installations interfere with each other which is why they tools mentioned indeed point to different locations (since they belong to different installations). I understand that usually those tools from one install point to the same folder.
Select your results by clicking in the top left corner, right click and select "Copy with Headers". Paste in excel. Done!
In case you wish to keep the current version of angular, you can visit this version compatibility checker to check which version of angular-material is best for your current angular version. You can also check peer dependencies of angular-material using angular-material compatibility.
Full reference present at : listview with checkbox android studio Pass selected items to next activity
Main source code is as below.
Create a model class first
public class Model {
private boolean isSelected;
private String animal;
public String getAnimal() {
return animal;
}
public void setAnimal(String animal) {
this.animal = animal;
}
public boolean getSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
}
Then in adapter class, setTags to checkbox. Use those tags in onclicklistener of checkbox.
public class CustomAdapter extends BaseAdapter {
private Context context;
public static ArrayList<Model> modelArrayList;
public CustomAdapter(Context context, ArrayList<Model> modelArrayList) {
this.context = context;
this.modelArrayList = modelArrayList;
}
@Override
public int getViewTypeCount() {
return getCount();
}
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public int getCount() {
return modelArrayList.size();
}
@Override
public Object getItem(int position) {
return modelArrayList.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder(); LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.lv_item, null, true);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.cb);
holder.tvAnimal = (TextView) convertView.findViewById(R.id.animal);
convertView.setTag(holder);
}else {
// the getTag returns the viewHolder object set as a tag to the view
holder = (ViewHolder)convertView.getTag();
}
holder.checkBox.setText("Checkbox "+position);
holder.tvAnimal.setText(modelArrayList.get(position).getAnimal());
holder.checkBox.setChecked(modelArrayList.get(position).getSelected());
holder.checkBox.setTag(R.integer.btnplusview, convertView);
holder.checkBox.setTag( position);
holder.checkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
View tempview = (View) holder.checkBox.getTag(R.integer.btnplusview);
TextView tv = (TextView) tempview.findViewById(R.id.animal);
Integer pos = (Integer) holder.checkBox.getTag();
Toast.makeText(context, "Checkbox "+pos+" clicked!", Toast.LENGTH_SHORT).show();
if(modelArrayList.get(pos).getSelected()){
modelArrayList.get(pos).setSelected(false);
}else {
modelArrayList.get(pos).setSelected(true);
}
}
});
return convertView;
}
private class ViewHolder {
protected CheckBox checkBox;
private TextView tvAnimal;
}
}
I landed here because I was looking for something like that too. In my case, I was copying the data from a set of staging tables with many columns into one table while also assigning row ids to the target table. Here is a variant of the above approaches that I used. I added the serial column at the end of my target table. That way I don't have to have a placeholder for it in the Insert statement. Then a simple select * into the target table auto populated this column. Here are the two SQL statements that I used on PostgreSQL 9.6.4.
ALTER TABLE target ADD COLUMN some_column SERIAL;
INSERT INTO target SELECT * from source;
Here is one way to “untrack” any files that are would otherwise be ignored under the current set of exclude patterns:
(GIT_INDEX_FILE=some-non-existent-file \
git ls-files --exclude-standard --others --directory --ignored -z) |
xargs -0 git rm --cached -r --ignore-unmatch --
This leaves the files in your working directory but removes them from the index.
The trick used here is to provide a non-existent index file to git ls-files so that it thinks there are no tracked files. The shell code above asks for all the files that would be ignored if the index were empty and then removes them from the actual index with git rm.
After the files have been “untracked”, use git status to verify that nothing important was removed (if so adjust your exclude patterns and use git reset -- path to restore the removed index entry). Then make a new commit that leaves out the “crud”.
The “crud” will still be in any old commits. You can use git filter-branch to produce clean versions of the old commits if you really need a clean history (n.b. using git filter-branch will “rewrite history”, so it should not be undertaken lightly if you have any collaborators that have pulled any of your historical commits after the “crud” was first introduced).
You need to alias the subquery. Thus, your statement should be:
Select Z.id
From (
Select id, time
From dbo.tablea
Union All
Select id, time
From dbo.tableb
) As Z
Group By Z.id
Adding to previous answers: check the pexpect module for dealing with interactive commands (adduser, passwd etc.)
Make sure to check your build.gradle and that it doesn't use a newer SDK version than what is installed on your AVD. That's only if you use Android Studio though.
Sometimes truncating or dropping the table DATABASECHANGELOGLOCK doesn't work. I use PostgreSQL database and came across this issue a lot of times. What I do for solving is to rollback the prepared statements running in background for that database. Try to rollback all the prepared statements and try the liquibase changes again.
SQL:
SELECT gid FROM pg_prepared_xacts WHERE database='database_name';
If above statement returns any record, then rollback that prepared statement with following SQL statement.
ROLLBACK PREPARED 'gid_obtained_from_above_SQL';
in the recent version of facebook sdk , facebook has disabled the feature that let you access some one friends list due to security reasons ... check the documentation to learn more ...
As noted by Riedsio, the session variables do not change after connecting unless you specifically set them; setting the global variable only changes the session value of your next connection.
For example, if you have 100 connections and you lower the global wait_timeout
then it will not affect the existing connections, only new ones after the variable was changed.
Specifically for the wait_timeout
variable though, there is a twist.
If you are using the mysql
client in the interactive mode, or the connector with CLIENT_INTERACTIVE
set via mysql_real_connect()
then you will see the interactive_timeout
set for @@session.wait_timeout
Here you can see this demonstrated:
> ./bin/mysql -Bsse 'select @@session.wait_timeout, @@session.interactive_timeout, @@global.wait_timeout, @@global.interactive_timeout'
70 60 70 60
> ./bin/mysql -Bsse 'select @@wait_timeout'
70
> ./bin/mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 5.7.12-5 MySQL Community Server (GPL)
Copyright (c) 2009-2016 Percona LLC and/or its affiliates
Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> select @@wait_timeout;
+----------------+
| @@wait_timeout |
+----------------+
| 60 |
+----------------+
1 row in set (0.00 sec)
So, if you are testing this using the client it is the interactive_timeout
that you will see when connecting and not the value of wait_timeout
There's a solution:
import pyautogui
for i in range(1000):
pyautogui.typewrite("a")
You are testing if the values of the variables error
and Already
are present in RepoOutput[RepoName.index(repo)]
. If these variables don't exist then an undefined object is used.
Both of your if
and elif
tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].
I think you wanted to test if certain strings are in the value instead:
{% if "error" in RepoOutput[RepoName.index(repo)] %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
<td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>
Other corrections I made:
{% elif ... %}
instead of {$ elif ... %}
.</tr>
tag out of the if
conditional structure, it needs to be there always.id
attributeNote that most likely you want to use a class
attribute instead here, not an id
, the latter must have a value that must be unique across your HTML document.
Personally, I'd set the class value here and reduce the duplication a little:
{% if "Already" in RepoOutput[RepoName.index(repo)] %}
{% set row_class = "good" %}
{% else %}
{% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>
Sorry to open an old thread but I'm posting just in case it helps someone. This seems to be the easiest way to do this in Python 3.
from datetime import datetime
Date = str(datetime.now())[:10]
Hour = str(datetime.now())[11:13]
Minute = str(datetime.now())[14:16]
Second = str(datetime.now())[17:19]
Millisecond = str(datetime.now())[20:]
If you need the values as a number just cast them as an int e.g
Hour = int(str(datetime.now())[11:13])
To get the path of file in application package;
ContextWrapper c = new ContextWrapper(this);
Toast.makeText(this, c.getFilesDir().getPath(), Toast.LENGTH_LONG).show();
This sub will populate a Collection with all files matching the filename or pattern you pass in.
Sub GetFiles(StartFolder As String, Pattern As String, _
DoSubfolders As Boolean, ByRef colFiles As Collection)
Dim f As String, sf As String, subF As New Collection, s
If Right(StartFolder, 1) <> "\" Then StartFolder = StartFolder & "\"
f = Dir(StartFolder & Pattern)
Do While Len(f) > 0
colFiles.Add StartFolder & f
f = Dir()
Loop
If DoSubfolders then
sf = Dir(StartFolder, vbDirectory)
Do While Len(sf) > 0
If sf <> "." And sf <> ".." Then
If (GetAttr(StartFolder & sf) And vbDirectory) <> 0 Then
subF.Add StartFolder & sf
End If
End If
sf = Dir()
Loop
For Each s In subF
GetFiles CStr(s), Pattern, True, colFiles
Next s
End If
End Sub
Usage:
Dim colFiles As New Collection
GetFiles "C:\Users\Marek\Desktop\Makro\", FName & ".xls", True, colFiles
If colFiles.Count > 0 Then
'work with found files
End If
If you are using storyboards you could set the navigation bar tint colour.
After clicking on the magic wand icon to infer constraints:
1) In Projects window, go to Gradle Scripts > build.gradle (Module:app)
2) Scroll down to dependencies
3) Look for implementation 'com.android.support:appcompat-v7:28.0.0-beta03'
4) Change this line to implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'
5) A banner should pop up at the top of the window, click Sync Now in the right corner.
This works for Android Studio v3.1 click for image of edit to build.gradle file
HttpWebRequest webRequest = WebRequest.Create(uirTradeStream) as HttpWebRequest;
webRequest.Proxy = WebRequest.DefaultWebProxy;
webRequest.Credentials = new NetworkCredential("user", "password");
webRequest.Proxy.Credentials = new NetworkCredential("user", "password");
It is successful.
Most of the solutions here count the amount of commits you'd like to go back. I think this is an error prone methodology. Counting would require recounting.
You can simply pass the commit hash of the commit you want to be at HEAD or in other words, the commit you'd like to be the last commit via:
(Notice see commit hash)
To avoid this:
1) git checkout master
2) git branch <feature branch> master
3) git reset --hard <commit hash>
4) git push -f origin master
Just use this js file. (I mentioned 2 examples with different js files. hope the second one is what you need) You can simply change the scroll amount, speed etc by changing the parameters.
https://github.com/nathco/jQuery.scrollSpeed
Here's a Demo
None of the 7 prior answers mentioned that console.dir
supports extra arguments: depth
, showHidden
, and whether to use colors
.
Of particular interest is depth
, which (in theory) allows travering objects into more than the default 2 levels that console.log
supports.
I wrote "in theory" because in practice when I had a Mongoose object and ran console.log(mongoose)
and console.dir(mongoose, { depth: null })
, the output was the same. What actually recursed deeply into the mongoose
object was using util.inspect
:
import * as util from 'util';
console.log(util.inspect(myObject, {showHidden: false, depth: null}));
public static void main(String[] args) {
String start = "THIS_IS_A_TEST";
StringBuffer sb = new StringBuffer();
for (String s : start.split("_")) {
sb.append(Character.toUpperCase(s.charAt(0)));
if (s.length() > 1) {
sb.append(s.substring(1, s.length()).toLowerCase());
}
}
System.out.println(sb);
}
for me, prepared statements is a must-have feature. more exactly, parameter binding (which only works on prepared statements). it's the only really sane way to insert strings into SQL commands. i really don't trust the 'escaping' functions. the DB connection is a binary protocol, why use an ASCII-limited sub-protocol for parameters?
divs can't be vertically aligned that way, you can however use margins or position:relative to modify its location.
Here is some example using CASE WHEN
SELECT
CASE WHEN A > 1 THEN
'Greater than 1'
END
FROM TRIANGLES
.
SELECT
CASE WHEN A > 1 THEN
A
END
FROM TRIANGLES
.
SELECT
CASE WHEN A > 1 and B > 1 THEN
'Greater than 1'
END
FROM TRIANGLES
.
SELECT
CASE WHEN A > 1 THEN
'greater than 1'
ELSE
'less than 1'
END
FROM TRIANGLES
.
SELECT
CASE WHEN A > 1 THEN
'greater than 1'
ELSE CASE WHEN A >= 0 THEN
'greater than or equal 0'
ELSE
'less than 0'
END
END
FROM TRIANGLES;
Hope this helps
You could do the following:
def Lists():
my_list1 = [30,34,56]
my_list2 = [29,500,43]
for element in my_list1:
print(element >= 30)
for element in my_list2:
print(element >= 30)
Lists()
This will return the values that are greater than 30 as True, and the values that are smaller as false.
JLabel label = new JLabel("fax", SwingConstants.RIGHT);
I used this
:top
cls
type G:\empty.txt
type I:\empty.txt
timeout /T 500
goto top
As the answer is marked correct then it's a Windows Dos prompt script and this will work too:
find "string" status.txt >nul && call "my batch file.bat"
You need to seperate the functionality into a class or classes and launch that via one of two stubs. The console stub or service stub.
As its plain to see, when running windows, the myriad services that make up the infrastructure do not (and can't directly) present console windows to the user. The service needs to communicate with the user in a non graphical way: via the SCM; in the event log, to some log file etc. The service will also need to communicate with windows via the SCM, otherwise it will get shutdown.
It would obviously be acceptable to have some console app that can communicate with the service but the service needs to run independently without a requirement for GUI interaction.
The Console stub can very useful for debugging service behaviour but should not be used in a "productionized" environment which, after all, is the purpose of creating a service.
I haven't read it fully but this article seems to pint in the right direction.
So, this is an old post, however I think I can contribute something to it.
You can always do something like this:
package com.dyna.test;
import java.io.File;
import java.lang.reflect.Constructor;
public class DynamicClass{
@SuppressWarnings("unchecked")
public Object castDynamicClass(String className, String value){
Class<?> dynamicClass;
try
{
//We get the actual .class object associated with the specified name
dynamicClass = Class.forName(className);
/* We get the constructor that received only
a String as a parameter, since the value to be used is a String, but we could
easily change this to be "dynamic" as well, getting the Constructor signature from
the same datasource we get the values from */
Constructor<?> cons =
(Constructor<?>) dynamicClass.getConstructor(new Class<?>[]{String.class});
/*We generate our object, without knowing until runtime
what type it will be, and we place it in an Object as
any Java object extends the Object class) */
Object object = (Object) cons.newInstance(new Object[]{value});
return object;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
public static void main(String[] args)
{
DynamicClass dynaClass = new DynamicClass();
/*
We specify the type of class that should be used to represent
the value "3.0", in this case a Double. Both these parameters
you can get from a file, or a network stream for example. */
System.out.println(dynaClass.castDynamicClass("java.lang.Double", "3.0"));
/*
We specify a different value and type, and it will work as
expected, printing 3.0 in the above case and the test path in the one below, as the Double.toString() and
File.toString() would do. */
System.out.println(dynaClass.castDynamicClass("java.io.File", "C:\\testpath"));
}
Of course, this is not really dynamic casting, as in other languages (Python for example), because java is a statically typed lang. However, this can solve some fringe cases where you actually need to load some data in different ways, depending on some identifier. Also, the part where you get a constructor with a String parameter could be probably made more flexible, by having that parameter passed from the same data source. I.e. from a file, you get the constructor signature you want to use, and the list of values to be used, that way you pair up, say, the first parameter is a String, with the first object, casting it as a String, next object is an Integer, etc, but somehwere along the execution of your program, you get now a File object first, then a Double, etc.
In this way, you can account for those cases, and make a somewhat "dynamic" casting on-the-fly.
Hope this helps anyone as this keeps turning up in Google searches.
After pulling my hair out for like 6 hours of this completely useless error, my problem ended up being that my data transfer objects
were too complex. Start with uber simple properties like public long Id { get; set;}
that's it... nothing fancy.
In this specific case (there is always a single character at the start you want to remove) you'll want:
str.substring(1)
However, if you want to be able to detect if the comma is there and remove it if it is, then something like:
if (str[0] == ',') {
str = str.substring(1);
}
This is what I came up with. There is an added function to check to see if the int is past the date on which the exceptions were imposed(year$100, year %400). Before 1582 those exceptions weren't around.
import java.util.Scanner;
public class lecture{
public static void main(String[] args) {
boolean loop=true;
Scanner console = new Scanner( System.in );
while (loop){
System.out.print( "Enter the year: " );
int year= console.nextInt();
System.out.println( "The year is a leap year: "+ leapYear(year) );
System.out.print( "again?: " );
int again = console.nextInt();
if (again == 1){
loop=false;
}//if
}
}
public static boolean leapYear ( int year){
boolean leaped = false;
if (year%4==0){
leaped = true;
if(year>1582){
if (year%100==0&&year%400!=0){
leaped=false;
}
}
}//1st if
return leaped;
}
}
As of PHP 7, you can just use the define() function to define a constant array :
define('ANIMALS', [
'dog',
'cat',
'bird'
]);
echo ANIMALS[1]; // outputs "cat"
This is what worked for me:
function validateURL(value) {
return /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);
}
from there is is just a matter of calling the function to get a true or false back:
validateURL(urltovalidate);
You can select every column from that sub-query by aliasing it and adding the alias before the *
:
SELECT t.*, a+b AS total_sum
FROM
(
SELECT SUM(column1) AS a, SUM(column2) AS b
FROM table
) t
Getting the Phone Number, IMEI, and SIM Card ID
TelephonyManager tm = (TelephonyManager)
getSystemService(Context.TELEPHONY_SERVICE);
For SIM card, use the getSimSerialNumber()
//---get the SIM card ID---
String simID = tm.getSimSerialNumber();
if (simID != null)
Toast.makeText(this, "SIM card ID: " + simID,
Toast.LENGTH_LONG).show();
Phone number of your phone, use the getLine1Number() (some device's dont return the phone number)
//---get the phone number---
String telNumber = tm.getLine1Number();
if (telNumber != null)
Toast.makeText(this, "Phone number: " + telNumber,
Toast.LENGTH_LONG).show();
IMEI number of the phone, use the getDeviceId()
//---get the IMEI number---
String IMEI = tm.getDeviceId();
if (IMEI != null)
Toast.makeText(this, "IMEI number: " + IMEI,
Toast.LENGTH_LONG).show();
Permissions needed
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
For 2020 Mac OS X Catalina users:
Forget about other useless answers, here only two steps needed:
Create a file with the naming convention: priority-appname. Then copy-paste the path you want to add to PATH
.
E.g. 80-vscode
with content /Applications/Visual Studio Code.app/Contents/Resources/app/bin/
in my case.
Move that file to /etc/paths.d/
. Don't forget to open a new tab(new session) in the Terminal and type echo $PATH
to check that your path is added!
Notice: this method only appends your path to PATH
.
I was getting this error. Turns out it only happened when I completely cleaned the RN caches (quite elaborate process) and then created a release build.
If I cleaned the caches, created a debug build and then a release build, everything worked. Bit worrying but works.
Note: My clean command is...
rm -r android/build ; rm -r android/app/src/release/res ; rm -r android/app/build/intermediates ; watchman watch-del-all ; rm -rf $TMPDIR/react-* ; npm start -- --reset-cache
How you generate the unique_ids is a useful question - but you seem to be making a counter productive assumption about when you generate them!
My point is that you do not need to generate these unique id's at the time of creating your rows, because they are essentially independent of the data being inserted.
What I do is pre-generate unique id's for future use, that way I can take my own sweet time and absolutely guarantee they are unique, and there's no processing to be done at the time of the insert.
For example I have an orders table with order_id in it. This id is generated on the fly when the user enters the order, incrementally 1,2,3 etc forever. The user does not need to see this internal id.
Then I have another table - unique_ids with (order_id, unique_id). I have a routine that runs every night which pre-loads this table with enough unique_id rows to more than cover the orders that might be inserted in the next 24 hours. (If I ever get 10000 orders in one day I'll have a problem - but that would be a good problem to have!)
This approach guarantees uniqueness and takes any processing load away from the insert transaction and into the batch routine, where it does not affect the user.
Use the following in the function you will call and it will work just fine.
[a b c] = yourfunction(optional)
%your code
a = 5;
b = 7;
c = 10;
return
end
This is a way to call the function both from another function and from the command terminal
[aa bb cc] = yourfunction(optional);
The variables aa, bb and cc now hold the return variables.
i think it should be
select convert(varchar(10),StandardCost) +'S' from DimProduct where ProductKey = 212
or
select cast(StandardCost as varchar(10)) + 'S' from DimProduct where ProductKey = 212
I think many of the answers here may be missing a quality method included in StringBuilder
: .delete(int start, [int] end)
. I know this is a late reply; however, this should be made known (and explained a bit more thoroughly).
Let's say you have a StringBuilder table - which you wish to modify, dynamically, throughout your program (one I am working on right now does this), e.g.
StringBuilder table = new StringBuilder();
If you are looping through the method and alter the content, use the content, then wish to discard the content to "clean up" the StringBuilder
for the next iteration, you can delete it's contents, e.g.
table.delete(int start, int end).
start and end being the indices of the chars you wish to remove. Don't know the length in chars and want to delete the whole thing?
table.delete(0, table.length());
NOW, for the kicker. StringBuilders
, as mentioned previously, take a lot of overhead when altered frequently (and can cause safety issues with regard to threading); therefore, use StringBuffer
- same as StringBuilder
(with a few exceptions) - if your StringBuilder
is used for the purpose of interfacing with the user.
Another way is to setup an alias in Config Manager. Then simply type that alias name when you want to connect. This makes it much easier and is more prefereable when you have to manage several servers/instances and/or servers on multiple ports and/or multiple protocols. Give them friendly names and it becomes much easier to remember them.
Similar idea to yeh answer, just minimalist alternative.
Create a batch file with the following content:
helloworld.exe
pause
Then use the batch file.
You're not passing any credentials to sqlcmd.exe
So it's trying to authenticate you using the Windows Login credentials, but you mustn't have your SQL Server setup to accept those credentials...
When you were installing it, you would have had to supply a Server Admin password (for the sa
account)
Try...
sqlcmd.exe -U sa -P YOUR_PASSWORD -S ".\SQL2008"
for reference, theres more details here...
One other use (in languages that support properties) is that setters and getters can imply that an operation is non-trivial. Typically, you want to avoid doing anything that's computationally expensive in a property.
First of all, swapping without a temporary variable in a language as C# is a very bad idea.
But for the sake of answer, you can use this code:
startAngle = startAngle + stopAngle;
stopAngle = startAngle - stopAngle;
startAngle = startAngle - stopAngle;
Problems can however occur with rounding off if the two numbers differ largely. This is due to the nature of floating point numbers.
If you want to hide the temporary variable, you can use a utility method:
public static class Foo {
public static void Swap<T> (ref T lhs, ref T rhs) {
T temp = lhs;
lhs = rhs;
rhs = temp;
}
}
Using ElementTree
:
import xml.etree.ElementTree
# Open original file
et = xml.etree.ElementTree.parse('file.xml')
# Append new tag: <a x='1' y='abc'>body text</a>
new_tag = xml.etree.ElementTree.SubElement(et.getroot(), 'a')
new_tag.text = 'body text'
new_tag.attrib['x'] = '1' # must be str; cannot be an int
new_tag.attrib['y'] = 'abc'
# Write back to file
#et.write('file.xml')
et.write('file_new.xml')
note: output written to file_new.xml
for you to experiment, writing back to file.xml
will replace the old content.
IMPORTANT: the ElementTree library stores attributes in a dict, as such, the order in which these attributes are listed in the xml text will NOT be preserved. Instead, they will be output in alphabetical order. (also, comments are removed. I'm finding this rather annoying)
ie: the xml input text <b y='xxx' x='2'>some body</b>
will be output as <b x='2' y='xxx'>some body</b>
(after alphabetising the order parameters are defined)
This means when committing the original, and changed files to a revision control system (such as SVN, CSV, ClearCase, etc), a diff between the 2 files may not look pretty.
If the constraint is not a foreign key, eg. one added using 'UNIQUE CONSTRAINT (colA, colB)' then it is an index that can be dropped using ALTER TABLE ... DROP INDEX ...
For a package manager that can install and manage multiple versions of python, these are good choices:
The advantages to these package managers is that it may be easier to set them up and install multiple versions of python with them than it is to install python from source. They also provide commands for easily changing the available python version(s) using shims and setting the python version per-directory.
This disadvantage is that, by default, they are installed at the user-level (inside your home directory) and require a little bit of user-level configuration - you'll need to edit your ~/.profile
and ~/.bashrc
or similar files. This means that it is not easy to use them to install multiple python versions globally for all users. In order to do this, you can install from source alongside the OS's existing python version.
You'll need root privileges for this method.
See the official python documentation for building from source for additional considerations and options.
/usr/local
is the designated location for a system administrator to install shared (system-wide) software, so it's subdirectories are a good place to download the python source and install. See section 4.9 of the Linux Foundation's File Hierarchy Standard.
Install any build dependencies. On Debian-based systems, use:
apt update
apt install build-essential zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libsqlite3-dev libreadline-dev libffi-dev libbz2-dev
Choose which python version you want to install. See the Python Source Releases page for a listing.
Download and unzip file in /usr/local/src
, replacing X.X.X
below with the python version (i.e. 3.8.2
).
cd /usr/local/src
wget https://www.python.org/ftp/python/X.X.X/Python-X.X.X.tgz
tar vzxf Python-X.X.X.tgz
Before building and installing, set the CFLAGS
environment variable with C compiler flags necessary (see GNU's make
documentation). This is usually not necessary for general use, but if, for example, you were going to create a uWSGI plugin with this python version, you might want to set the flags, -fPIC
, with the following:
export CFLAGS='-fPIC'
Change the working directory to the unzipped python source directory, and configure the build. You'll probably want to use the --enable-optimizations
option on the ./configure
command for profile guided optimization. Use --prefix=/usr/local
to install to the proper subdirectories (/usr/local/bin
, /usr/local/lib
, etc.).
cd Python-X.X.X
./configure --enable-optimizations --prefix=/usr/local
Build the project with make
and install with make altinstall
to avoid overriding any files when installing multiple versions. See the warning on this page of the python build documentation.
make -j 4
make altinstall
Then you should be able to run your new python and pip versions with pythonX.X
and pipX.X
(i.e python3.8
and pip3.8
). Note that if the minor version of your new installation is the same as the OS's version (for example if you were installing python3.8.4 and the OS used python3.8.2), then you would need to specify the entire path (/usr/local/bin/pythonX.X
) or set an alias to use this version.
i couldn't change the permissions on the sharepoint i'm using but got a round it by uploading .url files with the drag and drop multiple files uploader.
Using the normal upload didn't work because they are intepreted by the file open dialog when you try to open them singly so it just tries to open the target not the .url file.
.url files can be made by saving a favourite with internet exploiter.
$("#btnAddProfile").click(function(){
$("#btnAddProfile").attr('value', 'Save');
});
The answers proposing :noh
or :nohlsearch
(e.g., Matt McMinn’s) are correct for temporarily disabling search highlighting – as asked in the original question.
I thought I'd contribute a mapping that I find useful in Normal mode:
nnoremap <C-L> :nohlsearch<CR><C-L>
By default, CtrlL in Vim clears and redraws the screen. A number of command line programs (mostly those using the GNU Readline library, such as Bash) use the same key combination to clear the screen. This feature is useful in the situation where a process running in the background prints to the terminal, over-writing parts of the foreground process.
This Normal mode mapping also clears the highlighting of most recent search term before redrawing the screen. I find the two features complement each other and it’s convenient to use one CtrlL for both actions together rather than create a separate mapping for disabling search highlighting.
NB: noremap
is used rather than map
as otherwise, the mapping would be recursive.
Tip: I usually remap Caps Lock to Ctrl to make it easier to type such key combinations; the details for doing this depend on your choice of OS / windowing system (and are off-topic for this answer). Both the following tips include information on mapping Caps Lock to Ctrl as well as Esc:
It's not a big deal on a small/personal scale, but it can become a bigger deal quickly on a larger scale. My employer is a large Microsoft shop, but won't/can't buy into Team System/TFS for a number of reasons. We currently use Subversion + Orcas + MBUnit + TestDriven.NET and it works well, but getting TD.NET was a huge hassle. The version sensitivity of MBUnit + TestDriven.NET is also a big hassle, and having one additional commercial thing (TD.NET) for legal to review and procurement to handle and manage, isn't trivial. My company, like a lot of companies, are fat and happy with a MSDN Subscription model, and it's just not used to handling one off procurements for hundreds of developers. In other words, the fully integrated MS offer, while definitely not always best-of-bread, is a significant value-add in my opinion.
I think we'll stay with our current step because it works and we've already gotten over the hump organizationally, but I sure do wish MS had a compelling offering in this space so we could consolidate and simplify our dev stack a bit.
CTRL+SHIFT+C in Eclipse + StatET and Rstudio.
h1 { font-size: 150%; }
h2 { font-size: 120%; }
Tune as needed.
A dict's keys are stored in a hashtable so that is their 'natural order', i.e. psuedo-random. Any other ordering is a concept of the consumer of the dict.
sorted() always returns a list, not a dict. If you pass it a dict.items() (which produces a list of tuples), it will return a list of tuples [(k1,v1), (k2,v2), ...] which can be used in a loop in a way very much like a dict, but it is not in anyway a dict!
foo = {
'a': 1,
'b': 2,
'c': 3,
}
print foo
>>> {'a': 1, 'c': 3, 'b': 2}
print foo.items()
>>> [('a', 1), ('c', 3), ('b', 2)]
print sorted(foo.items())
>>> [('a', 1), ('b', 2), ('c', 3)]
The following feels like a dict in a loop, but it's not, it's a list of tuples being unpacked into k,v:
for k,v in sorted(foo.items()):
print k, v
Roughly equivalent to:
for k in sorted(foo.keys()):
print k, foo[k]
I'm surprised Object.assign
hasn't been mentioned.
let cloned = Object.assign({}, source);
If available (e.g. Babel), you can use the object spread operator:
let cloned = { ... source };
This is probably faster?:
n = len(predictions)
rmse = np.linalg.norm(predictions - targets) / np.sqrt(n)
You can change the behavior of the built in types in Python. For your case it's really easy to create a dict subclass that will store duplicated values in lists under the same key automatically:
class Dictlist(dict):
def __setitem__(self, key, value):
try:
self[key]
except KeyError:
super(Dictlist, self).__setitem__(key, [])
self[key].append(value)
Output example:
>>> d = dictlist.Dictlist()
>>> d['test'] = 1
>>> d['test'] = 2
>>> d['test'] = 3
>>> d
{'test': [1, 2, 3]}
>>> d['other'] = 100
>>> d
{'test': [1, 2, 3], 'other': [100]}
How about:
update table
set columnname = columnname + 1
where id = <some id>
I have 2 CSV files that I use to read data. The java program is exported as a runnable jar file. When you export it, you will figure out it doesn't export your resources with it.
I added a folder under project called data in eclipse. In that folder i stored my csv files.
When I need to reference those files I do it like this...
private static final String ZIP_FILE_LOCATION_PRIMARY = "free-zipcode-database-Primary.csv";
private static final String ZIP_FILE_LOCATION = "free-zipcode-database.csv";
private static String getFileLocation(){
String loc = new File("").getAbsolutePath() + File.separatorChar +
"data" + File.separatorChar;
if (usePrimaryZipCodesOnly()){
loc = loc.concat(ZIP_FILE_LOCATION_PRIMARY);
} else {
loc = loc.concat(ZIP_FILE_LOCATION);
}
return loc;
}
Then when you put the jar in a location so it can be ran via commandline, make sure that you add the data folder with the resources into the same location as the jar file.
With the new angular class Renderer2
constructor(private renderer:Renderer2) {}
@ViewChild('one', { static: false }) d1: ElementRef;
ngAfterViewInit() {
const d2 = this.renderer.createElement('div');
const text = this.renderer.createText('two');
this.renderer.appendChild(d2, text);
this.renderer.appendChild(this.d1.nativeElement, d2);
}
You can use hasOwnProperty, but based on the reference you need quotes when using this method:
if (myObj.hasOwnProperty('myProp')) {
// do something
}
Another way is to use in operator, but you need quotes here as well:
if ('myProp' in myObj) {
// do something
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in
You should consider creating a timestamp from that date witk mktime()
eg:
$date = explode('/', $_POST['date']);
$time = mktime(0,0,0,$date[0],$date[1],$date[2]);
$mysqldate = date( 'Y-m-d H:i:s', $time );
My approach via group dialout to get every tty with user 'dialout'
ls -l /dev/tty* | grep 'dialout'
to only get its folder
ls -l /dev/tty* | grep 'dialout' | rev | cut -d " " -f1 | rev
easy listen to the tty output e.g. when arduino serial out:
head --lines 1 < /dev/ttyUSB0
listen to every tty out for one line only:
for i in $(ls -l /dev/tty* | grep 'dialout' | rev | cut -d " " -f1 | rev); do head --lines 1 < $i; done
I really like the approach via looking for drivers:
ll /sys/class/tty/*/device/driver
You can pick the tty-Name now:
ls /sys/class/tty/*/device/driver | grep 'driver' | cut -d "/" -f 5
I'm loading the PDF with jQuery ajax into browser cache. Then I create embedded element with data already in browser cache. I guess it will work with iframe too.
var url = "http://example.com/my.pdf";
// show spinner
$.mobile.showPageLoadingMsg('b', note, false);
$.ajax({
url: url,
cache: true,
mimeType: 'application/pdf',
success: function () {
// display cached data
$(scroller).append('<embed type="application/pdf" src="' + url + '" />');
// hide spinner
$.mobile.hidePageLoadingMsg();
}
});
You have to set your http headers correctly as well.
HttpContext.Response.Expires = 1;
HttpContext.Response.Cache.SetNoServerCaching();
HttpContext.Response.Cache.SetAllowResponseInBrowserHistory(false);
HttpContext.Response.CacheControl = "Private";
The way to install plugins seems to have changed, the previous answers here did not work for me.
The current (checked with 7.8.1) way to install plugins is to install it in a sub folder:
The plugin (in the DLL form) should be placed in the plugins subfolder of the Notepad++ Install Folder, under the subfolder with the same name of plugin binary name without file extension. For example, if the plugin you want to install named myAwesomePlugin.dll, you should install it with the following path: %PROGRAMFILES(x86)%\Notepad++\plugins\myAwesomePlugin\myAwesomePlugin.dll
from https://npp-user-manual.org/docs/plugins/
So PluginManager.dll
goes into PluginManager
sub folder.
The RemoveAll()
methods accept a Predicate<T>
delegate (until here nothing new). A predicate points to a method that simply returns true or false. Of course, the RemoveAll
will remove from the collection all the T
instances that return True with the predicate applied.
C# 3.0 lets the developer use several methods to pass a predicate to the RemoveAll
method (and not only this one…). You can use:
Lambda expressions
vehicles.RemoveAll(vehicle => vehicle.EnquiryID == 123);
Anonymous methods
vehicles.RemoveAll(delegate(Vehicle v) {
return v.EnquiryID == 123;
});
Normal methods
vehicles.RemoveAll(VehicleCustomPredicate);
private static bool
VehicleCustomPredicate (Vehicle v) {
return v.EnquiryID == 123;
}
Why not a/b/(c|d|e)
? I just tried with Saxon XML library (wrapped up nicely with some Clojure goodness), and it seems to work.
abc.xml
is the doc described by OP.
(require '[saxon :as xml])
(def abc-doc (xml/compile-xml (slurp "abc.xml")))
(xml/query "a/b/(c|d|e)" abc-doc)
=> (#<XdmNode <c>C1</c>>
#<XdmNode <d>D1</d>>
#<XdmNode <e>E1</e>>
#<XdmNode <c>C2</c>>
#<XdmNode <d>D2</d>>
#<XdmNode <e>E1</e>>)
Eigen C++ Version for 3D line segment and point
// Return minimum distance between line segment: head--->tail and point
double MinimumDistance(Eigen::Vector3d head, Eigen::Vector3d tail,Eigen::Vector3d point)
{
double l2 = std::pow((head - tail).norm(),2);
if(l2 ==0.0) return (head - point).norm();// head == tail case
// Consider the line extending the segment, parameterized as head + t (tail - point).
// We find projection of point onto the line.
// It falls where t = [(point-head) . (tail-head)] / |tail-head|^2
// We clamp t from [0,1] to handle points outside the segment head--->tail.
double t = max(0,min(1,(point-head).dot(tail-head)/l2));
Eigen::Vector3d projection = head + t*(tail-head);
return (point - projection).norm();
}
Sass supports @if
statements. (See the documentation.)
You could write your mixin like this:
@mixin box-shadow($top, $left, $blur, $color, $inset:"") {
@if $inset != "" {
-webkit-box-shadow:$top $left $blur $color $inset;
-moz-box-shadow:$top $left $blur $color $inset;
box-shadow:$top $left $blur $color $inset;
}
}
Consider an example having 10 apples. When it implements Iterable, it is like putting each apple in boxes from 1 to 10 and return an iterator which can be used to navigate.
By implementing iterator, we can get any apple, apple in next boxes etc.
So implementing iterable gives an iterator to navigate its elements although to navigate, iterator needs to be implemented.
Open Safari Desktop iOS
Develop -> Responsive Design Mode
Click "Other" under device
Paste this: Mozilla/5.0 (iPad; CPU OS 10_2_1 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.79 Mobile/14D27 Safari/602.1
Use Safari inspect tools.
One of The Shortest method i found for single value while i was searching for myself, is just passing single string and setting string as model in view like this.
In your Partial calling side
@Html.Partial("ParitalAction", "String data to pass to partial")
And then binding the model with Partial View like this
@model string
and the using its value in Partial View like this
@Model
You can also play with other datatypes like array, int or more complex data types like IDictionary or something else.
Hope it helps,
As others have already pointed out, Python includes a module to read and write CSV files. It works pretty well as long as the input characters stay within ASCII limits. In case you want to process other encodings, more work is needed.
The Python documentation for the csv module implements an extension of csv.reader, which uses the same interface but can handle other encodings and returns unicode strings. Just copy and paste the code from the documentation. After that, you can process a CSV file like this:
with open("some.csv", "rb") as csvFile:
for row in UnicodeReader(csvFile, encoding="iso-8859-15"):
print row
After trying the above, I realized I was getting an error on pod install
[!] CocoaPods did not set the base configuration of your project because your project already has a custom config set.
This was causing the error, because cocoapods was not adding the .xcconfig file to my project.
To solve this I went to the Info
tab of my project. Set my Based on Configuration File to None
for all schemes and targets. Then re-ran pod install
See this link for more information. Cocoapods Warning - CocoaPods did not set the base configuration of your project because because your project already has a custom config set
The self
keyword in Python is analogous to this
keyword in C++ / Java / C#.
In Python 2 it is done implicitly by the compiler (yes Python does compilation internally). It's just that in Python 3 you need to mention it explicitly in the constructor and member functions. example:
class Pump():
//member variable
account_holder
balance_amount
// constructor
def __init__(self,ah,bal):
| self.account_holder = ah
| self.balance_amount = bal
def getPumps(self):
| print("The details of your account are:"+self.account_number + self.balance_amount)
//object = class(*passing values to constructor*)
p = Pump("Tahir",12000)
p.getPumps()
The CSS place-items shorthand property sets the align-items and justify-items properties, respectively. If the second value is not set, the first value is also used for it.
.parent {
display: grid;
place-items: center;
}
For those running pre-java7, named groups are supported by joni (Java port of the Oniguruma regexp library). Documentation is sparse, but it has worked well for us.
Binaries are available via Maven (http://repository.codehaus.org/org/jruby/joni/joni/).
This approach always works for me:
# First of all, delete all broken links. Replace my_project_name` to your virtual env name
find ~/.virtualenvs/my_project_name/ -type l -delete
# Then create new links to the current Python version
virtualenv ~/.virtualenvs/my_project_name/
# It's it. Just repeat for each virtualenv located in ~/.virtualenvs
Taken from:
I very much like this answer which uses attached properties to mediate the behavior. However, I found that answer's implementation overly complicated, and it also doesn't address the secondary goal of preventing the window from being closed even with Alt+F4. So I offer this alternative:
enum CloseButtonVisibility
{
Visible,
Hidden,
CloseDisabled,
}
static class WindowEx
{
private static readonly CancelEventHandler _cancelCloseHandler = (sender, e) => e.Cancel = true;
public static readonly DependencyProperty CloseButtonVisibilityProperty =
DependencyProperty.RegisterAttached(
"CloseButtonVisibility",
typeof(CloseButtonVisibility),
typeof(WindowEx),
new FrameworkPropertyMetadata(CloseButtonVisibility.Visible, new PropertyChangedCallback(_OnCloseButtonChanged)));
[AttachedPropertyBrowsableForType(typeof(Window))]
public static CloseButtonVisibility GetCloseButtonVisibility(Window obj)
{
return (CloseButtonVisibility)obj.GetValue(CloseButtonVisibilityProperty);
}
[AttachedPropertyBrowsableForType(typeof(Window))]
public static void SetCloseButtonVisibility(Window obj, CloseButtonVisibility value)
{
obj.SetValue(CloseButtonVisibilityProperty, value);
}
private static void _OnCloseButtonChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is Window window))
{
return;
}
if (e.OldValue is CloseButtonVisibility oldVisibility)
{
if (oldVisibility == CloseButtonVisibility.CloseDisabled)
{
window.Closing -= _cancelCloseHandler;
}
}
if (e.NewValue is CloseButtonVisibility newVisibility)
{
if (newVisibility == CloseButtonVisibility.CloseDisabled)
{
window.Closing += _cancelCloseHandler;
}
if (!window.IsLoaded)
{
// NOTE: if the property is set multiple times before the window is loaded,
// the window will wind up with multiple event handlers. But they will all
// set the same value, so this is fine from a functionality point of view.
//
// The handler is never unsubscribed, so there is some nominal overhead there.
// But it would be incredibly unusual for this to be set more than once
// before the window is loaded, and even a handful of delegate instances
// being around that are no longer needed is not really a big deal.
window.Loaded += _ApplyCloseButtonVisibility;
}
else
{
_SetVisibility(window, newVisibility);
}
}
}
#region Win32 imports
private const int GWL_STYLE = -16;
private const int WS_SYSMENU = 0x80000;
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
#endregion
private static void _ApplyCloseButtonVisibility(object sender, RoutedEventArgs e)
{
Window window = (Window)sender;
CloseButtonVisibility visibility = GetCloseButtonVisibility(window);
_SetVisibility(window, visibility);
}
private static void _SetVisibility(Window window, CloseButtonVisibility visibility)
{
var hwnd = new WindowInteropHelper(window).Handle;
if (visibility == CloseButtonVisibility.Visible)
{
SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) | WS_SYSMENU);
}
else
{
SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU);
}
}
}
This provides three states to choose from:
Note that by default, a window that is never closed will prevent a WPF program's process from terminating. So if you choose to use the CloseButtonVisibility.CloseDisabled
value, you will need to either customize the Application.Run()
behavior, or re-enable closing of the window before exiting. E.g. in your main window, you might have something like this:
protected override void OnClosed(EventArgs e)
{
WindowEx.SetCloseButtonVisibility(this.toolWindow.Value, CloseButtonVisibility.Hidden);
this.toolWindow.Value.Close();
base.OnClosed(e);
}
where toolWindow
is the Window
reference for the window with the close button disabled.
The above assumes that the window is normally just hidden and shown as needed during the normal UI activity. Of course, you can also choose to close the window explicitly at any time, but the same technique — setting the option to not disable closing, and then explicitly closing the window — would still apply.
The code below worked for me I used part of the code above inside the button class.
public Button signupB;
public void handleButtonClick (){
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("sceneNotAvailable.fxml"));
/*
* if "fx:controller" is not set in fxml
* fxmlLoader.setController(NewWindowController);
*/
Scene scene = new Scene(fxmlLoader.load(), 630, 400);
Stage stage = new Stage();
stage.setTitle("New Window");
stage.setScene(scene);
stage.show();
} catch (IOException e) {
Logger logger = Logger.getLogger(getClass().getName());
logger.log(Level.SEVERE, "Failed to create new Window.", e);
}
}
}
if ([ $NUM1 == 1 ] || [ $NUM2 == 1 ]) && [ -z "$STR" ]
then
echo STR is empty but should have a value.
fi
Here is how to add inline code:
You can add inline code with {\tt code }
or \texttt{ code }
. If you want to format the inline code, then it would be best to make your own command
\newcommand{\code}[1]{\texttt{#1}}
Also, note that code blocks can be loaded from other files with
\lstinputlisting[breaklines]{source.c}
breaklines
isn't required, but I find it useful. Be aware that you'll have to specify \usepackage{
listings }
for this one.
Update: The listings package also includes the \lstinline
command, which has the same syntax highlighting features as the \lstlisting
and \lstinputlisting
commands (see Cloudanger's answer for configuration details). As mentioned in a few other answers, there's also the minted package, which provides the \mintinline
command. Like \lstinline
, \mintinline
provides the same syntax highlighting as a regular minted code block:
\documentclass{article}
\usepackage{minted}
\begin{document}
This is a sentence with \mintinline{python}{def inlineCode(a="ipsum)}
\end{document}
It is possible to use only one variable:
var timer = -performance.now();
// Do something
timer += performance.now();
console.log("Time: " + (timer/1000).toFixed(5) + " sec.")
timer/1000
- to convert milliseconds to seconds
.toFixed(5)
- to trim extra digits
function get_when($date) {
$current = strtotime(date('Y-m-d H:i'));
$date_diff = $date - $current;
$difference = round($date_diff/(60*60*24));
if($difference >= 0) {
return 'Today';
} else if($difference == -1) {
return 'Yesterday';
} else if($difference == -2 || $difference == -3 || $difference == -4 || $difference == -5) {
return date('l', $date);
} else {
return ('on ' . date('jS/m/y', $date));
}
}
get_when(date('Y-m-d H:i', strtotime($your_targeted_date)));
Update Sep 2017 - tl;dr
Download a single file from a remote ftp server to your machine:
sftp {user}@{host}:{remoteFileName} {localFileName}
Upload a single file from your machine to a remote ftp server:
sftp {user}@{host}:{remote_dir} <<< $'put {local_file_path}'
Original answer:
Ok, so I feel a little dumb. But I figured it out. I almost had it at the top with:
sftp user@host remoteFile localFile
The only documentation shown in the terminal is this:
sftp [user@]host[:file ...]
sftp [user@]host[:dir[/]]
However, I came across this site which shows the following under the synopsis:
sftp [-vC1 ] [-b batchfile ] [-o ssh_option ] [-s subsystem | sftp_server ] [-B buffer_size ] [-F ssh_config ] [-P sftp_server path ] [-R num_requests ] [-S program ] host
sftp [[user@]host[:file [file]]]
sftp [[user@]host[:dir[/]]]
So the simple answer is you just do :
after your user and host then the remote file and local filename. Incredibly simple!
Single line, sftp copy remote file:
sftp username@hostname:remoteFileName localFileName
sftp kyle@kylesserver:/tmp/myLogFile.log /tmp/fileNameToUseLocally.log
Update Feb 2016
In case anyone is looking for the command to do the reverse of this and push a file from your local computer to a remote server in one single line sftp
command, user @Thariama below posted the solution to accomplish that. Hat tip to them for the extra code.
sftp {user}@{host}:{remote_dir} <<< $'put {local_file_path}'
Is this what you're looking for? You place you CSS between style
tags in the HTML document header. I'm guessing for iPhone it's webkit so it should work.
<html>
<head>
<style type="text/css">
.title { color: blue; text-decoration: bold; text-size: 1em; }
.author { color: gray; }
</style>
</head>
<body>
<p>
<span class="title">La super bonne</span>
<span class="author">proposée par Jérém</span>
</p>
</body>
</html>
If nested hash maps or arrays can be created, then I can simply go down the table from the beginning and add each item to the nested array. I must trace each line to the root node in order to know which level in the nested array to insert into. I can employ memoization so that I do not need to look up the same parent over and over again.
Edit: I would read the entire table into an array first, so it will not query the DB repeatedly. Of course this won't be practical if your table is very large.
After the structure is built, I must do a depth first traverse through it and print out the HTML.
There's no better fundamental way to store this information using one table (I could be wrong though ;), and would love to see a better solution ). However, if you create a scheme to employ dynamically created db tables, then you opened up a whole new world at the sacrifice of simplicity, and the risk of SQL hell ;).
<!DOCTYPE html>
<html>
<head>
<style>
.container__1{
max-width: 450px;
font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
}
.container__1 label{
display: block;
margin-bottom: 10px;
}
.container__1 label > span{
float: left;
width: 100px;
color: #F072A9;
font-weight: bold;
font-size: 13px;
text-shadow: 1px 1px 1px #fff;
}
.container__1 fieldset{
border-radius: 10px;
-webkit-border-radious:10px;
-moz-border-radoius: 10px;
margin: 0px 0px 0px 0px;
border: 1px solid #FFD2D2;
padding: 20px;
background:#FFF4F4 ;
box-shadow: inset 0px 0px 15px #FFE5E5;
}
.container__1 fieldset legend{
color: #FFA0C9;
border-top: 1px solid #FFD2D2 ;
border-left: 1px solid #FFD2D2 ;
border-right: 1px solid #FFD2D2 ;
border-radius: 5px 5px 0px 0px;
background: #FFF4F4;
padding: 0px 8px 3px 8px;
box-shadow: -0px -1px 2px #F1F1F1;
font-weight: normal;
font-size: 12px;
}
.container__1 textarea{
width: 250px;
height: 100px;
}.container__1 input[type=text],
.container__1 input[type=email],
.container__1 select{
border-radius: 3px;
border: 1px solid #FFC2DC;
outline: none;
color: #F072A9;
padding: 5px 8px 5px 8px;
box-shadow: inset 1px 1px 4px #FFD5E7;
background: #FFEFF6;
}
.container__1 input[type=submit],
.container__1 input[type=button]{
background: #EB3B88;
border: 1px solid #C94A81;
padding: 5px 15px 5px 15px;
color: #FFCBE2;
box-shadow: inset -1px -1px 3px #FF62A7;
border-radius: 3px;
font-weight: bold;
}
.required{
color: red;
}
</style>
</head>
<body>
<div class="container__1">
<form name="RegisterForm" onsubmit="return(SubmitClick())">
<fieldset>
<legend>Personal</legend>
<label for="field1"><span >Name<span class="required">*</span><input id="name" type="text" class="input-field" name="Name" value=""</label>
<label for="field2"><span >Email<span class="required">*</span><input placeholder="Ex: [email protected]" id="email" type="email" class="input-field" name="Email" value=""</label>
<label for="field3"><span >Phone<span class="required">*</span><input placeholder="+919853004369" id="mobile" type="text" class="input-field" name="Mobile" value=""</label>
<label for="field4">
<span>Subject</span>
<select name="subject" id="subject" class="select-field">
<option value="none">Choose Your Sub..</option>
<option value="Appointment">Appiontment</option>
<option value="Interview">Interview</option>
<option value="Regarding a post">Regarding a post</option>
</select>
</label>
<label><span></span><input type="submit" ></label>
</fieldset>
</form>
</div>
</body>
<script>
function SubmitClick(){
_name = document.querySelector('#name').value;
_email = document.querySelector('#email').value;
_mobile = document.querySelector('#mobile').value;
_subject = document.querySelector('#subject').value;
if(_name == '' || _name == null ){
alert('Enter Your Name');
document.RegisterForm.Name.focus();
return false;
}
var atPos = _email.indexOf('@');
var dotPos = _email.lastIndexOf('.');
if(_email == '' || atPos<1 || (dotPos - atPos)<2){
alert('Provide Your Correct Email address');
document.RegisterForm.Email.focus();
return false;
}
var regExp = /^\+91[0-9]{10}$/;
if(_mobile == '' || !regExp.test(_mobile)){
alert('Please Provide your Mobile number as Ex:- +919853004369');
document.RegisterForm.Mobile.focus();
return false;
}
if(_subject == 'none'){
alert('Please choose a subject');
document.RegisterForm.subject.focus();
return false;
}else{
alert (`success!!!:--'\n'Name:${_name},'\n' Mobile: ${_mobile},'\n' Email:${_email},'\n' Subject:${_subject},`)
}
}
</script>
</html>
javascript:var string="false";alert(Boolean(string)?'FAIL':'WIN')
will not work because any non-empty string is true
javascript:var string="false";alert(string!=false.toString()?'FAIL':'WIN')
works because compared with string represenation
BTW, if anyone want to get coordinates of element on screen without jQuery, please try this:
function getOffsetTop (el) {
if (el.offsetParent) return el.offsetTop + getOffsetTop(el.offsetParent)
return el.offsetTop || 0
}
function getOffsetLeft (el) {
if (el.offsetParent) return el.offsetLeft + getOffsetLeft(el.offsetParent)
return el.offsetleft || 0
}
function coordinates(el) {
var y1 = getOffsetTop(el) - window.scrollY;
var x1 = getOffsetLeft(el) - window.scrollX;
var y2 = y1 + el.offsetHeight;
var x2 = x1 + el.offsetWidth;
return {
x1: x1, x2: x2, y1: y1, y2: y2
}
}
It will already work, as David pointed out!
>>> def machineEpsilon(func=float):
... machine_epsilon = func(1)
... while func(1)+func(machine_epsilon) != func(1):
... machine_epsilon_last = machine_epsilon
... machine_epsilon = func(machine_epsilon) / func(2)
... return machine_epsilon_last
...
>>> machineEpsilon(float)
2.220446049250313e-16
>>> import numpy
>>> machineEpsilon(numpy.float64)
2.2204460492503131e-16
>>> machineEpsilon(numpy.float32)
1.1920929e-07
My answer below shows how to embed images using data URIs. This is useful for the web, but will not work reliably for most email clients. For email purposes be sure to read Shadow2531's answer.
Base-64 data is legal in an img
tag and I believe your question is how to properly insert such an image tag.
You can use an online tool or a few lines of code to generate the base 64 string.
The syntax to source the image from inline data is:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">
When you created your repository on GitHub, you created a README.md, which is a new commit.
Your local repository doesn't know about this commit yet. Hence:
Updates were rejected because the remote contains work that you do not have locally.
You may want to find to follow this advice:
You may want to first merge the remote changes (e.g., '
git pull
') before pushing again.
That is:
git pull
# Fix any merge conflicts, if you have a `README.md` locally
git push -u origin master
<asp:Button ID="btnGet" runat="server" Text="Get" OnClick="btnGet_Click" OnClientClick="retun callMethod();" />
<script type="text/javascript">
function callMethod() {
//your logic should be here and make sure your logic code note returing function
return false;
}
</script>
If it’s there, they’ll take it all.
The IRS matches with this regex: .*
$50,000
This will match everything!
See here for an example: Greedy-example
If I ask for a tax refund, the IRS sudden becomes non-greedy, and they use this quantifier:
(.{2,5}?)([0-9]*)
against this input: $50,000
The first group is non-needy and only matches $5
– so I get a $5
refund against the $50,000 input. They're non-greedy. They take as little as possible.
See here: Non-greedy-example.
It becomes important if you are trying to match certain parts of an expression. Sometimes you don't want to match everything.
Hopefully that analogy will help you remember!
Dim text As String = "123.45"
Dim value As Double
If Double.TryParse(text, value) Then
' text is convertible to Double, and value contains the Double value now
Else
' Cannot convert text to Double
End If
One one line (semi-colons necessary):
for i in 0 1 2 3 4 5 6 7 8 9; do for j in 0 1 2 3 4 5 6 7 8 9; do echo "$i$j"; done; done
Formatted for legibility (no semi-colons needed):
for i in 0 1 2 3 4 5 6 7 8 9
do
for j in 0 1 2 3 4 5 6 7 8 9
do
echo "$i$j"
done
done
There are different views on how the shell code should be laid out over multiple lines; that's about what I normally use, unless I put the next operation on the same line as the do
(saving two lines here).
You can write an object to a file using writeObject
in ObjectOutputStream
In relative layout you need specify textview height:
android:layout_height="100dp"
Or specify lines attribute:
android:lines="3"
I was using Xcode beta 3 (the latest at the time of writing) and encountered this issue with an iPhone XS running the latest iOS 14 Beta.
The solution, after trying a lot of suggestions, was to restart my iPhone.
cpp
is the preprocessor.
Run cpp filename.c
to output the preprocessed code, or better, redirect it to a file with
cpp filename.c > filename.preprocessed
.
Your problem is that all chapters, whether they're in the appendix or not, default to starting on an odd-numbered page when you're in two-sided layout mode. A few possible solutions:
The simplest solution is to use the openany
option to your document class, which makes chapters start on the next page, irrespective of whether it's an odd or even numbered page. This is supported in the standard book documentclass, eg \documentclass[openany]{book}
. (memoir
also supports using this as a declaration \openany
which can be used in the middle of a document to change the behavior for subsequent pages.)
Another option is to try the \let\cleardoublepage\clearpage
command before your appendices to avoid the behavior.
Or, if you don't care using a two-sided layout, using the option oneside
to your documentclass
(eg \documentclass[oneside]{book}
) will switch to using a one-sided layout.
I use this to load ko knockout object in console
document.write("<script src='https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-3.5.0.debug.js'></script>");
or host locally
document.write("<script src='http://localhost/js/knockout-3.5.0.debug.js'></script>");
This provides you to retrieve information from your URI strings
$this->uri->segment(n); // n=1 for controller, n=2 for method, etc
Consider this example:
http://example.com/index.php/controller/action/1stsegment/2ndsegment
it will return
$this->uri->segment(1); // controller
$this->uri->segment(2); // action
$this->uri->segment(3); // 1stsegment
$this->uri->segment(4); // 2ndsegment
Unload Me only works when its called from userform self. If you want to close a form from another module code (or userform), you need to use the Unload function + userformtoclose name.
I hope its helps
Besides appendFile
, you can also pass a flag in writeFile
to append data to an existing file.
fs.writeFile('log.txt', 'Hello Node', {'flag':'a'}, function(err) {
if (err) {
return console.error(err);
}
});
By passing flag 'a', data will be appended at the end of the file.
For those coming here with a Mac:
I had the same issue and the problem was, I created an emulator with API Level 29 but removed that SDK and installed 28 instead. The emulator that was not able to be launched anymore.
Therefore check the AVD Manager if your emulator really can be launched.
Here is a mockable singleton using CRTP. It relies on a little helper to enforce a single object at any one time (at most). To enforce a single object over program execution, remove the reset (which we find useful for tests).
A ConcreteSinleton
can be implemented like this:
class ConcreteSingleton : public Singleton<ConcreteSingleton>
{
public:
ConcreteSingleton(const Singleton<ConcreteSingleton>::PrivatePass&)
: Singleton<StandardPaths>::Singleton{pass}
{}
// ... concrete interface
int f() const {return 42;}
};
And then used with
ConcreteSingleton::instance().f();
git restore [filename_path]
For example I need to discard my last changes in index.html
file:
git restore /usr/myPC/folder/index.html
I don't see any mention of flexbox in here, so I will illustrate:
HTML
<div class="wrapper">
<div class="main">top</div>
<div class="footer">bottom</div>
</div>
CSS
.wrapper {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.main {
flex: 1;
}
.footer {
flex: 0;
}
This is one approach:
from xlrd import open_workbook
class Arm(object):
def __init__(self, id, dsp_name, dsp_code, hub_code, pin_code, pptl):
self.id = id
self.dsp_name = dsp_name
self.dsp_code = dsp_code
self.hub_code = hub_code
self.pin_code = pin_code
self.pptl = pptl
def __str__(self):
return("Arm object:\n"
" Arm_id = {0}\n"
" DSPName = {1}\n"
" DSPCode = {2}\n"
" HubCode = {3}\n"
" PinCode = {4} \n"
" PPTL = {5}"
.format(self.id, self.dsp_name, self.dsp_code,
self.hub_code, self.pin_code, self.pptl))
wb = open_workbook('sample.xls')
for sheet in wb.sheets():
number_of_rows = sheet.nrows
number_of_columns = sheet.ncols
items = []
rows = []
for row in range(1, number_of_rows):
values = []
for col in range(number_of_columns):
value = (sheet.cell(row,col).value)
try:
value = str(int(value))
except ValueError:
pass
finally:
values.append(value)
item = Arm(*values)
items.append(item)
for item in items:
print item
print("Accessing one single value (eg. DSPName): {0}".format(item.dsp_name))
print
You don't have to use a custom class, you can simply take a dict()
. If you use a class however, you can access all values via dot-notation, as you see above.
Here is the output of the script above:
Arm object:
Arm_id = 1
DSPName = JaVAS
DSPCode = 1
HubCode = AGR
PinCode = 282001
PPTL = 1
Accessing one single value (eg. DSPName): JaVAS
Arm object:
Arm_id = 2
DSPName = JaVAS
DSPCode = 1
HubCode = AGR
PinCode = 282002
PPTL = 3
Accessing one single value (eg. DSPName): JaVAS
Arm object:
Arm_id = 3
DSPName = JaVAS
DSPCode = 1
HubCode = AGR
PinCode = 282003
PPTL = 5
Accessing one single value (eg. DSPName): JaVAS
Parsing argument based on standard input ( --key=value
)
const argv = (() => {
const arguments = {};
process.argv.slice(2).map( (element) => {
const matches = element.match( '--([a-zA-Z0-9]+)=(.*)');
if ( matches ){
arguments[matches[1]] = matches[2]
.replace(/^['"]/, '').replace(/['"]$/, '');
}
});
return arguments;
})();
Command example
node app.js --name=stackoverflow --id=10 another-argument --text="Hello World"
Result of argv: console.log(argv)
{
name: "stackoverflow",
id: "10",
text: "Hello World"
}
My full example is here, but I will provide a summary below.
Layout
Add a .swift and .xib file each with the same name to your project. The .xib file contains your custom view layout (using auto layout constraints preferably).
Make the swift file the xib file's owner.
Add the following code to the .swift file and hook up the outlets and actions from the .xib file.
import UIKit
class ResuableCustomView: UIView {
let nibName = "ReusableCustomView"
var contentView: UIView?
@IBOutlet weak var label: UILabel!
@IBAction func buttonTap(_ sender: UIButton) {
label.text = "Hi"
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
guard let view = loadViewFromNib() else { return }
view.frame = self.bounds
self.addSubview(view)
contentView = view
}
func loadViewFromNib() -> UIView? {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: nibName, bundle: bundle)
return nib.instantiate(withOwner: self, options: nil).first as? UIView
}
}
Use it
Use your custom view anywhere in your storyboard. Just add a UIView
and set the class name to your custom class name.
For a while Christopher Swasey's approach was the best approach I had found. I asked a couple of the senior devs on my team about it and one of them had the perfect solution! It satisfies every one of the concerns that Christopher Swasey so eloquently addressed and it doesn't require boilerplate subclass code(my main concern with his approach). There is one gotcha, but other than that it is fairly intuitive and easy to implement.
MyCustomClass.swift
MyCustomClass.xib
File's Owner
of the .xib file to be your custom class (MyCustomClass
)class
value (under the identity Inspector
) for your custom view in the .xib file blank. So your custom view will have no specified class, but it will have a specified File's Owner.Assistant Editor
.
Connections Inspector
you will notice that your Referencing Outlets do not reference your custom class (i.e. MyCustomClass
), but rather reference File's Owner
. Since File's Owner
is specified to be your custom class, the outlets will hook up and work propery. NibLoadable
protocol referenced below.
.swift
file name is different from your .xib
file name, then set the nibName
property to be the name of your .xib
file.required init?(coder aDecoder: NSCoder)
and override init(frame: CGRect)
to call setupFromNib()
like the example below.MyCustomClass
).Here is the protocol you will want to reference:
public protocol NibLoadable {
static var nibName: String { get }
}
public extension NibLoadable where Self: UIView {
public static var nibName: String {
return String(describing: Self.self) // defaults to the name of the class implementing this protocol.
}
public static var nib: UINib {
let bundle = Bundle(for: Self.self)
return UINib(nibName: Self.nibName, bundle: bundle)
}
func setupFromNib() {
guard let view = Self.nib.instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Error loading \(self) from nib") }
addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
view.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
view.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
view.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
view.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
}
}
And here is an example of MyCustomClass
that implements the protocol (with the .xib file being named MyCustomClass.xib
):
@IBDesignable
class MyCustomClass: UIView, NibLoadable {
@IBOutlet weak var myLabel: UILabel!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupFromNib()
}
override init(frame: CGRect) {
super.init(frame: frame)
setupFromNib()
}
}
NOTE: If you miss the Gotcha and set the class
value inside your .xib file to be your custom class, then it will not draw in the storyboard and you will get a EXC_BAD_ACCESS
error when you run the app because it gets stuck in an infinite loop of trying to initialize the class from the nib using the init?(coder aDecoder: NSCoder)
method which then calls Self.nib.instantiate
and calls the init
again.
Place your RaisedButton(...)
in a SizedBox
SizedBox(
width: double.infinity,
child: RaisedButton(...),
)
try to implement Application_AuthenticateRequest
instead of Application_Start
.
this method has an instance for HttpContext.Current
, unlike Application_Start
(which fires very soon in app lifecycle, soon enough to not hold a HttpContext.Current
object yet).
hope that helps.
Warning: Each child in an array or iterator should have a unique "key" prop.
This is a warning as for array items which we are going to iterate over will need a unique resemblance.
React handles iterating component rendering as arrays.
Better way to resolve this is provide index on the array items you are going to iterate over.for example:
class UsersState extends Component
{
state = {
users: [
{name:"shashank", age:20},
{name:"vardan", age:30},
{name:"somya", age:40}
]
}
render()
{
return(
<div>
{
this.state.users.map((user, index)=>{
return <UserState key={index} age={user.age}>{user.name}</UserState>
})
}
</div>
)
}
index is React built-in props.
It was KB2553154. Microsoft needs to release a fix. As a developer of Excel applications we can't go to all our clients computers and delete files off them. We are getting blamed for something Microsoft caused.
Can try this too!
Create a dictionary of replacement values.
import pandas as pd
data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])
replace_dict= {0:'Female',1:'Male'}
print(replace_dict)
Use the map function for replacing values
data['sex']=data['sex'].map(replace_dict)
Take a look here: http://longgoldenears.blogspot.com/2007/09/triple-equals-in-javascript.html
The 3 equal signs mean "equality without type coercion". Using the triple equals, the values must be equal in type as well.
0 == false // true
0 === false // false, because they are of a different type
1 == "1" // true, automatic type conversion for value only
1 === "1" // false, because they are of a different type
null == undefined // true
null === undefined // false
'0' == false // true
'0' === false // false
This works for me on the webpack.config.js
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
}),
in another javascript or into HTML add:
global.jQuery = require('jquery');
Please follow below steps :
1.Open Your project.
2.Go to the Left side of the Gradle button.
3.Look at below image.
4.Click button above image show.
5.if this type of view you are not in offline mode.
6.Go to Build and rebuild the project.
All above point is work for me.
"Get" request with appending headers transform to "Options" request. So Cors policy problems occur. You have to implement "Options" request to your server.
simple way can be -
just href="javascript:location.reload(true);
your answer is
location.reload(true);
Thanks
adjust the background-position to move background images in different positions of the div
div {
background-image: url('image url')
background-position: 0 -250px;
}
I'm assuming that you're trying to deal with Ajax navigation and not trying to prevent your users from using the back button, which violates just about every tenet of UI development ever.
Here's some possible solutions: JQuery History Salajax A Better Ajax Back Button
Here lot of good answer but i think this will help someone
select id from campaign where ( NOW() BETWEEN start_date AND end_date)
In newer versions of typescript you can use:
type Customers = Record<string, Customer>
In older versions you can use:
var map: { [email: string]: Customer; } = { };
map['[email protected]'] = new Customer(); // OK
map[14] = new Customer(); // Not OK, 14 is not a string
map['[email protected]'] = 'x'; // Not OK, 'x' is not a customer
You can also make an interface if you don't want to type that whole type annotation out every time:
interface StringToCustomerMap {
[email: string]: Customer;
}
var map: StringToCustomerMap = { };
// Equivalent to first line of above
Instead of if
construct, you can leverage the short-circuit evaluation:
#!/usr/bin/env bash
echo $[1+1]
echo $[2/0] # division by 0 but execution of script proceeds
echo $[3+1]
(echo $[4/0]) || exit $? # script halted with code 1 returned from `echo`
echo $[5+1]
Note the pair of parentheses which is necessary because of priority of alternation operator. $?
is a special variable set to exit code of most recently called command.
I thought Activity was deprecated
No.
So for API Level 22 (with a minimum support for API Level 15 or 16), what exactly should I use both to host the components, and for the components themselves? Are there uses for all of these, or should I be using one or two almost exclusively?
Activity
is the baseline. Every activity inherits from Activity
, directly or indirectly.
FragmentActivity
is for use with the backport of fragments found in the support-v4
and support-v13
libraries. The native implementation of fragments was added in API Level 11, which is lower than your proposed minSdkVersion
values. The only reason why you would need to consider FragmentActivity
specifically is if you want to use nested fragments (a fragment holding another fragment), as that was not supported in native fragments until API Level 17.
AppCompatActivity
is from the appcompat-v7
library. Principally, this offers a backport of the action bar. Since the native action bar was added in API Level 11, you do not need AppCompatActivity
for that. However, current versions of appcompat-v7
also add a limited backport of the Material Design aesthetic, in terms of the action bar and various widgets. There are pros and cons of using appcompat-v7
, well beyond the scope of this specific Stack Overflow answer.
ActionBarActivity
is the old name of the base activity from appcompat-v7
. For various reasons, they wanted to change the name. Unless some third-party library you are using insists upon an ActionBarActivity
, you should prefer AppCompatActivity
over ActionBarActivity
.
So, given your minSdkVersion
in the 15-16 range:
If you want the backported Material Design look, use AppCompatActivity
If not, but you want nested fragments, use FragmentActivity
If not, use Activity
Just adding from comment as note: AppCompatActivity
extends FragmentActivity
, so anyone who needs to use features of FragmentActivity
can use AppCompatActivity
.
Here is my submission!
if you put this code into a file called hello.js and run it using node hello.js it should print out the message hello, it has been sent through 2 sockets.
The code shows how to handle the variables for a hello message bounced from the client to the server via the section of code labelled //Mirror.
The variable names are declared locally rather than all at the top because they are only used in each of the sections between the comments. Each of these could be in a separate file and run as its own node.
// Server_x000D_
var io1 = require('socket.io').listen(8321);_x000D_
_x000D_
io1.on('connection', function(socket1) {_x000D_
socket1.on('bar', function(msg1) {_x000D_
console.log(msg1);_x000D_
});_x000D_
});_x000D_
_x000D_
// Mirror_x000D_
var ioIn = require('socket.io').listen(8123);_x000D_
var ioOut = require('socket.io-client');_x000D_
var socketOut = ioOut.connect('http://localhost:8321');_x000D_
_x000D_
_x000D_
ioIn.on('connection', function(socketIn) {_x000D_
socketIn.on('foo', function(msg) {_x000D_
socketOut.emit('bar', msg);_x000D_
});_x000D_
});_x000D_
_x000D_
// Client_x000D_
var io2 = require('socket.io-client');_x000D_
var socket2 = io2.connect('http://localhost:8123');_x000D_
_x000D_
var msg2 = "hello";_x000D_
socket2.emit('foo', msg2);
_x000D_
From the v3 documentation (Developer's Guide > Concepts > Developing for Mobile Devices):
Android and iOS devices respect the following
<meta>
tag:<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
This setting specifies that the map should be displayed full-screen and should not be resizable by the user. Note that the iPhone's Safari browser requires this
<meta>
tag be included within the page's<head>
element.
You can use https://github.com/keighl/KTCenterFlowLayout like this:
KTCenterFlowLayout *layout = [[KTCenterFlowLayout alloc] init];
[self.collectionView setCollectionViewLayout:layout];
Cool U guys, I just found this:
http://ptomato.wordpress.com/2012/02/09/geek-tip-running-python-guis-in-sublime-text-2/
It explains (like one of the answers above) how to edit this exec.py in the default directory.
I had the problem that my PYTHON UI APPLICATION would not start. I commented out the last line from the following snipped:
# Hide the console window on Windows
startupinfo = None
if os.name == "nt":
startupinfo = subprocess.STARTUPINFO()
#startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
and, taaadaaaa, I could start my app by pressing Ctrl+B. Funny line anyways, uh? And a big thank you to whoever wrote that article ;-)
Try to use this variant:
<?php echo Yii::app()->createAbsoluteUrl('your_yii_application/?lg=pl', array('id'=>$model->id));?>
It is the easiest way, I guess.
Frank Heikens answer will only update database ownership. Often, you also want to update ownership of contained objects (including tables). Starting with Postgres 8.2, REASSIGN OWNED is available to simplify this task.
IMPORTANT EDIT!
Never use REASSIGN OWNED
when the original role is postgres
, this could damage your entire DB instance. The command will update all objects with a new owner, including system resources (postgres0, postgres1, etc.)
First, connect to admin database and update DB ownership:
psql
postgres=# REASSIGN OWNED BY old_name TO new_name;
This is a global equivalent of ALTER DATABASE
command provided in Frank's answer, but instead of updating a particular DB, it change ownership of all DBs owned by 'old_name'.
The next step is to update tables ownership for each database:
psql old_name_db
old_name_db=# REASSIGN OWNED BY old_name TO new_name;
This must be performed on each DB owned by 'old_name'. The command will update ownership of all tables in the DB.
To anyone else who tried most of the solutions and still having problems.
My solution is different from the others, which is located at the bottom of this post, but before you try it make sure you have exhausted the following lists. To be sure, I have tried all of them but to no avail.
Recompile and redeploy from scratch, don't update the existing app. SO Answer
Grant IIS_IUSRS full access to the directory "C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files"
Keep in mind the framework version you are using. If your app is using impersonation, use that identity instead of IIS_IUSRS
Delete all contents of the directory "C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files".
Keep in mind the framework version you are using
Change the identity of the AppPool that your app is using, from ApplicatonPoolIdentity to NetworkService.
IIS > Application Pools > Select current app pool > Advance Settings > Identity.
SO Answer (please restore to default if it doesn't work)
Verify IIS Version and AppPool .NET version compatibility with your app. Highly applicable to first time deployments. SO Answer
Verify impersonation configuration if applicable. SO Answer
My Solution:
I found out that certain anti-virus softwares are actively blocking compilations of DLLs within the directory "Temporary ASP.NET Files", mine was McAfee, the IT people failed to notify me of the installation.
As per advice by both McAfee experts and Microsoft, you need to exclude the directory "Temporary ASP.NET Files" in the real time scanning.
Sources:
Don't disable the Anti-Virus because it is only doing its job. Don't manually copy missing DLL files in the directory \Temporary ASP.NET Files{project name} because thats duct taping.
I would suggest not to use seaborn pointplot
for plotting. This makes things unnecessarily complicated.
Instead use matplotlib plot_date
. This allows to set labels to the plots and have them automatically put into a legend with ax.legend()
.
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
date = pd.date_range("2017-03", freq="M", periods=15)
count = np.random.rand(15,4)
df1 = pd.DataFrame({"date":date, "count" : count[:,0]})
df2 = pd.DataFrame({"date":date, "count" : count[:,1]+0.7})
df3 = pd.DataFrame({"date":date, "count" : count[:,2]+2})
f, ax = plt.subplots(1, 1)
x_col='date'
y_col = 'count'
ax.plot_date(df1.date, df1["count"], color="blue", label="A", linestyle="-")
ax.plot_date(df2.date, df2["count"], color="red", label="B", linestyle="-")
ax.plot_date(df3.date, df3["count"], color="green", label="C", linestyle="-")
ax.legend()
plt.gcf().autofmt_xdate()
plt.show()
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df1,color='blue')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df2,color='green')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df3,color='red')
ax.legend(handles=ax.lines[::len(df1)+1], labels=["A","B","C"])
ax.set_xticklabels([t.get_text().split("T")[0] for t in ax.get_xticklabels()])
plt.gcf().autofmt_xdate()
plt.show()
New, Edited Answer:
Add this in viewDidLayoutSubviews
SWIFT
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let indexPath = IndexPath(item: 12, section: 0)
self.collectionView.scrollToItem(at: indexPath, at: [.centeredVertically, .centeredHorizontally], animated: true)
}
Normally, .centerVertically
is the case
ObjC
-(void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:12 inSection:0];
[self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically | UICollectionViewScrollPositionCenteredHorizontally animated:NO];
}
Old answer working for older iOS
Add this in viewWillAppear
:
[self.view layoutIfNeeded];
[self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];
You have to return JSON error object yourself after setting the StatusCode, like so ...
if (BadRequest)
{
Dictionary<string, object> error = new Dictionary<string, object>();
error.Add("ErrorCode", -1);
error.Add("ErrorMessage", "Something really bad happened");
return Json(error);
}
Another way is to have a JsonErrorModel
and populate it
public class JsonErrorModel
{
public int ErrorCode { get; set;}
public string ErrorMessage { get; set; }
}
public ActionResult SomeMethod()
{
if (BadRequest)
{
var error = new JsonErrorModel
{
ErrorCode = -1,
ErrorMessage = "Something really bad happened"
};
return Json(error);
}
//Return valid response
}
Take a look at the answer here as well
There are at least three ways to disable the use of unobtrusive JavaScript for client-side validation:
<configuration>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
</configuration>
System.Web.UI.ValidationSettings.UnobtrusiveValidationMode
static property to System.Web.UI.UnobtrusiveValidationMode.None
System.Web.UI.Page.UnobtrusiveValidationMode
instance property to System.Web.UI.UnobtrusiveValidationMode.None
To disable the functionality on a per page basis, I prefer to set the Page.UnobtrusiveValidationMode
property using the page directive:
<%@ Page Language="C#" UnobtrusiveValidationMode="None" %>
you need to take out the quotes:
soda = a + b
(You want to refer to the variables a
and b
, not the strings "a" and "b")
this might be repetitive. I was trying to use pycharm to run flask - had anaconda 3, pycharm 2019.1.1 and windows 10. Created a new conda environment - it threw errors. Followed these steps -
Used the cmd to install python and flask after creating environment as suggested above.
Followed this answer.
Obviously kept the correct python interpreter (the one in the environment) everywhere.
I use Mac and Idea 14.1.7. Found idea.vmoptions file here: /Applications/IntelliJ IDEA 14.app/Contents/bin
This works in MSSQL and MySQL:
SELECT *
FROM Village
WHERE CastleType LIKE '%foo%';
public static boolean isPalindrome(String word) {
String str = "";
for (int i=word.length()-1; i>=0; i--){
str = str + word.charAt(i);
}
if(str.equalsIgnoreCase(word)){
return true;
}else{
return false;
}
}
This is my way:
List<String> list = new ArrayList<String>();
list.add("string1");
list.add("string2");
list.add("string3");
list.add("[Select one]");
final int listsize = list.size() - 1;
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, list) {
@Override
public int getCount() {
return(listsize); // Truncate the list
}
};
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(dataAdapter);
mySpinner.setSelection(listsize); // Hidden item to appear in the spinner
=
and LIKE
is not the same;
=
matches the exact string LIKE
matches a string that may contain wildcards (%)I have had reasonable success with a tool named (frustratingly) "JD: Java Decompiler".
I have found it better than most decompilers when dealing with classes compiled for Java 5 and higher. Unfortunately, it can still have some hiccups where JAD would normally succeed.
(Windows 10) I didn't like the path answers. I use choco package manager for node.js. Gulp would not fire for me unless it was:
Globally installed npm i -g gulp
and local dir npm i --save-dev gulp
The problem persisted beyond this once, which was fixed by completely removing node.js and reinstalling it.
I didn't see any comments about local/global and node.js removal/reinstall.
Use border-collapse and border-spacing to get spaces between the table cells. I would not recommend using floating cells as suggested by QQping.
In httpd.conf add (or change if it's already there):
AddDefaultCharset utf-8
You can use the below simple method of sorting:
datatable.DefaultView.Sort = "Col2 ASC,Col3 ASC,Col4 ASC";
By the above method, you will be able to sort N number of columns.
let url = ("https://firebasestorage.googleapis.com/v0/b/qualityaudit-678a4.appspot.com/o/profile_images%2FBFA28EDD-9E15-4CC3-9AF8-496B91E74A11.png?alt=media&token=b4518b07-2147-48e5-93fb-3de2b768412d")
self.myactivityindecator.startAnimating()
let urlString = url
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url)
{
(data, response, error) in
if error != nil {
print("Failed fetching image:", error!)
return
}
guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
print("error")
return
}
DispatchQueue.main.async {
let image = UIImage(data: data!)
let myimageview = UIImageView(image: image)
print(myimageview)
self.imgdata.image = myimageview.image
self.myactivityindecator.stopanimating()
}
}.resume()
The easiest option for me was to rename the title of the terminal instead. Please see: https://superuser.com/questions/362227/how-to-change-the-title-of-the-mintty-window
In this answer, they mention to modify the PS1 variable. Note: my situation was particular to cygwin.
TL;DR Put this in your .bashrc file:
function settitle() {
export PS1="\[\e[32m\]\u@\h \[\e[33m\]\w\[\e[0m\]\n$ "
echo -ne "\e]0;$1\a"
}
Put this in your .tmux.conf file, or similar formatting:
set -g pane-border-status bottom
set -g pane-border-format "#P #T #{pane_current_command}"
Then you can change the title of the pane by typing this in the console:
settitle titlename
Since Spring Boot v2+
I have verified with Spring Boot v2.3.5.RELEASE
With Spring Boot Maven Plugin
You can provide commandline argument like this:
mvn spring-boot:run -Dspring-boot.run.arguments="--spring.profiles.active=dev"
You can provide JVM argument like this:
mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Dspring.profiles.active=dev"
java -jar
java -Dspring.profiles.active=dev -jar app.jar
(Note order)
or
java -jar app.jar --spring.profiles.active=dev
(Note order)
If you only have one bean of type EmployeeService, and the interface EmployeeService does not have other implementations, you can simply put "@Service" before the EmployeeServiceImpl and "@Autowire" before the setter method. Otherwise, you should name the special bean like @Service("myspecial") and put "@autowire @Qualifier("myspecial") before the setter method.
I got this error:
System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions
when the port was used by another program.
On platforms with the select
function (POSIX, Linux, and Windows) you could do:
void sleep(unsigned long msec) {
timeval delay = {msec / 1000, msec % 1000 * 1000};
int rc = ::select(0, NULL, NULL, NULL, &delay);
if(-1 == rc) {
// Handle signals by continuing to sleep or return immediately.
}
}
However, there are better alternatives available nowadays.
Use the date function:
select date(timestamp_field) from table
From a character field representation to a date you can use:
select date(substring('2011/05/26 09:00:00' from 1 for 10));
Test code:
create table test_table (timestamp_field timestamp);
insert into test_table (timestamp_field) values(current_timestamp);
select timestamp_field, date(timestamp_field) from test_table;
Test result:
Create system user some_user
if it doesn't exist
if [[ $(getent passwd some_user) = "" ]]; then
sudo adduser --no-create-home --force-badname --disabled-login --disabled-password --system some_user
fi
The boxplot function returns the values used to do the plotting (which is actually then done by bxp():
bstats <- boxplot(count ~ spray, data = InsectSprays, col = "lightgray")
#need to "waste" this plot
bstats$out <- NULL
bstats$group <- NULL
bxp(bstats) # this will plot without any outlier points
I purposely did not answer the specific question because I consider it statistical malpractice to remove "outliers". I consider it acceptable practice to not plot them in a boxplot, but removing them just because they exceed some number of standard deviations or some number of inter-quartile widths is a systematic and unscientific mangling of the observational record.
Yes. For that ensure that you declare the worksheet
For example
Previous Code
Sub Sample()
Dim ws As Worksheet
Set ws = Sheets("Sheet3")
Debug.Print ws.Cells(23, 4).Value
End Sub
New Code
Sub Sample()
Dim ws As Worksheet
Set ws = Sheets("Sheet4")
Debug.Print ws.Cells(23, 4).Value
End Sub
In case the target page is on the same domain (i.e. shares the same origin with your page) and you don't mind creation of new tabs (1), you can (ab)use some JavaScript:
<a href="javascript:void(window.open('./target.html').onload=function(){this.document.querySelector('p:nth-child(10)').scrollIntoView()})">see tenth paragraph on another page</a>
Trivia:
var w = window.open('some URL of the same origin');
w.onload = function(){
// do whatever you want with `this.document`, like
this.document.querySelecotor('footer').scrollIntoView()
}
Working example of such 'exploit' you can try right now could be:
javascript:(function(url,sel,w,el){w=window.open(url);w.addEventListener('load',function(){w.setTimeout(function(){el=w.document.querySelector(sel);el.scrollIntoView();el.style.backgroundColor='red'},1000)})})('https://stackoverflow.com/questions/45014240/link-to-a-specific-spot-on-a-page-i-cant-edit','footer')
If you enter this into location bar (mind that Chrome removes javascript:
prefix when pasted from clipboard) or make it a href
value of any link on this page (using Developer Tools) and click it, you will get another (duplicate) SO question page scrolled to the footer and footer painted red. (Delay added as a workaround for ajax-loaded content pushing footer down after load.)
Notes
window.open(url,'_self')
seems to be breaking the load
event; basically makes the window.open
behave like a normal a href=""
click navigation; haven't researched more yet.You have two options to abruptly exit out of ForEach-Object
pipeline in PowerShell:
Where-Object
first, then pass objects to Foreach-Object
, orForeach-Object
into a standard Foreach
looping construct.Let's see examples: Following scripts exit out of Foreach-Object loop after 2nd iteration (i.e. pipeline iterates only 2 times)":
Solution-1: use Where-Object
filter BEFORE Foreach-Object
:
[boolean]$exit = $false;
1..10 | Where-Object {$exit -eq $false} | Foreach-Object {
if($_ -eq 2) {$exit = $true} #OR $exit = ($_ -eq 2);
$_;
}
OR
1..10 | Where-Object {$_ -le 2} | Foreach-Object {
$_;
}
Solution-2: Converted Foreach-Object
into standard Foreach
looping construct:
Foreach ($i in 1..10) {
if ($i -eq 3) {break;}
$i;
}
PowerShell should really provide a bit more straightforward way to exit or break out from within the body of a Foreach-Object
pipeline. Note: return
doesn't exit, it only skips specific iteration (similar to continue
in most programming languages), here is an example of return
:
Write-Host "Following will only skip one iteration (actually iterates all 10 times)";
1..10 | Foreach-Object {
if ($_ -eq 3) {return;} #skips only 3rd iteration.
$_;
}
HTH
Another possibility to make composer think you're using the correct version of PHP is to add to the config
section of a composer.json
file a platform option, like this:
"config": {
"platform": {
"php": "<ver>"
}
},
Where <ver>
is the PHP version of your choice.
Snippet from the docs:
Lets you fake platform packages (PHP and extensions) so that you can emulate a production env or define your target platform in the config. Example: {"php": "7.0.3", "ext-something": "4.0.3"}.
I think this should do the trick (untested):
Page.Response.Redirect(Page.Request.Url.ToString(), true);
I recently used this to read all the lines from a file:
alist = open('maze.txt').read().split()
or you can use this for that little bit of extra added safety:
with f as open('maze.txt'):
alist = f.read().split()
It doesn't work with whitespace in-between text in a single line, but it looks like your example file might not have whitespace splitting the values. It is a simple solution and it returns an accurate list of values, and does not add an empty string: ''
for every empty line, such as a newline at the end of the file.
You need to set the LayoutParams of the ViewGroup the ImageView is sitting in. For example if your ImageView is inside a LinearLayout, then you create a
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);
This is because it's the parent of the View that needs to know what size to allocate to the View.
I got it and explained in below:
//This table with two rows containing each row, one select in first td, and one input tags in second td and second input in third td;
<table id="tableID" class="table table-condensed">
<thead>
<tr>
<th><label>From Group</lable></th>
<th><label>To Group</lable></th>
<th><label>Level</lable></th>
</tr>
</thead>
<tbody>
<tr id="rowCount">
<td>
<select >
<option value="">select</option>
<option value="G1">G1</option>
<option value="G2">G2</option>
<option value="G3">G3</option>
<option value="G4">G4</option>
</select>
</td>
<td>
<input type="text" id="" value="" readonly="readonly" />
</td>
<td>
<input type="text" value="" readonly="readonly" />
</td>
</tr>
<tr id="rowCount">
<td>
<select >
<option value="">select</option>
<option value="G1">G1</option>
<option value="G2">G2</option>
<option value="G3">G3</option>
<option value="G4">G4</option>
</select>
</td>
<td>
<input type="text" id="" value="" readonly="readonly" />
</td>
<td>
<input type="text" value="" readonly="readonly" />
</td>
</tr>
</tbody>
</table>
<button type="button" class="btn btn-default generate-btn search-btn white-font border-6 no-border" id="saveDtls">Save</button>
//call on click of Save button;
$('#saveDtls').click(function(event) {
var TableData = []; //initialize array;
var data=""; //empty var;
//Here traverse and read input/select values present in each td of each tr, ;
$("table#tableID > tbody > tr").each(function(row, tr) {
TableData[row]={
"fromGroup": $('td:eq(0) select',this).val(),
"toGroup": $('td:eq(1) input',this).val(),
"level": $('td:eq(2) input',this).val()
};
//Convert tableData array to JsonData
data=JSON.stringify(TableData)
//alert('data'+data);
});
});
To set it programmatically in Activity.java:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.MyTheme); // (for Custom theme)
setTheme(android.R.style.Theme_Holo); // (for Android Built In Theme)
this.setContentView(R.layout.myactivity);
To set in Application scope in Manifest.xml (all activities):
<application
android:theme="@android:style/Theme.Holo"
android:theme="@style/MyTheme">
To set in Activity scope in Manifest.xml (single activity):
<activity
android:theme="@android:style/Theme.Holo"
android:theme="@style/MyTheme">
To build a custom theme, you will have to declare theme in themes.xml file, and set styles in styles.xml file.
From: http://www.danrigsby.com/blog/index.php/2008/06/17/rest-and-max-url-size/
If you include the library System.Data.Entity
you can use an overload of the Include()
method which takes a lambda expression instead of a string. You can then Select()
over children with Linq expressions rather than string
paths.
return DatabaseContext.Applications
.Include(a => a.Children.Select(c => c.ChildRelationshipType));
val drawable = ContextCompat.getDrawable(context, R.drawable.my_icon)
// or resources.getDrawable(R.drawable.my_icon, theme)
val sizePx = 25
drawable?.setBounds(0, 0, sizePx, sizePx)
// (left, top, right, bottom)
my_button.setCompoundDrawables(drawable, null, null, null)
I suggest creating an extension function on TextView (Button extends it) for easy reuse.
button.leftDrawable(R.drawable.my_icon, 25)
// Button extends TextView
fun TextView.leftDrawable(@DrawableRes id: Int = 0, @DimenRes sizeRes: Int) {
val drawable = ContextCompat.getDrawable(context, id)
val size = context.resources.getDimensionPixelSize(sizeRes)
drawable?.setBounds(0, 0, size, size)
this.setCompoundDrawables(drawable, null, null, null)
}
I've tried a pretty ugly solution but it fixed my problem.
var tabPressed = false;
$(document).keydown(function (e) {
// Listening tab button.
if (e.which == 9) {
tabPressed = true;
}
});
$(document).on('focus', '.select2', function() {
if (tabPressed) {
tabPressed = false;
$(this).siblings('select').select2('open');
}
});
How about:
writing-mode:tb-rl
Where top->bottom, right->left?
We will need vertical rule for this.
Is there something special with that directory or are you really just asking how to copy directories?
Copy recursively via CLI:
cp -R <sourcedir> <destdir>
If you're only seeing the files under the sourcedir
being copied (instead of sourcedir
as well), that's happening because you kept the trailing slash for sourcedir
:
cp -R <sourcedir>/ <destdir>
The above only copies the files and their directories inside of sourcedir
. Typically, you want to include the directory you're copying, so drop the trailing slash:
cp -R <sourcedir> <destdir>
Open the private channel, then:
on web client:
if
it's for example https://web.telegram.org/#/im?p=c1192292378_2674311763110923980then
1192292378 is the channel IDon mobile and desktop:
if
it's for example https://t.me/c/1192292378/31then
1192292378 is the channel ID (bonus: 31 is the message ID)on Plus Messenger for Android:
WARNING
be sure to add -100 prefix when using Telegram Bot API:
if
the channel ID is for example 1192292378then
you should use -1001192292378