If the number is stored in a string (which it would be if typed by a user), you can use atoi()
to convert it to an integer.
An integer can be assigned directly to a character. A character is different mostly just because how it is interpreted and used.
char c = atoi("61");
The PowerShell is almost exactly the same.
$webclient = new-object System.Net.WebClient
$webclient.Credentials = new-object System.Net.NetworkCredential($username, $password, $domain)
$webpage = $webclient.DownloadString($url)
Use sys.getsizeof() if you DON'T want to include sizes of linked (nested) objects.
However, if you want to count sub-objects nested in lists, dicts, sets, tuples - and usually THIS is what you're looking for - use the recursive deep sizeof() function as shown below:
import sys
def sizeof(obj):
size = sys.getsizeof(obj)
if isinstance(obj, dict): return size + sum(map(sizeof, obj.keys())) + sum(map(sizeof, obj.values()))
if isinstance(obj, (list, tuple, set, frozenset)): return size + sum(map(sizeof, obj))
return size
You can also find this function in the nifty toolbox, together with many other useful one-liners:
Assuming you can arrange to have a container element you wish to fill, this appears to work, but feels a bit hackish. In essence, I just use min/max-width/height
on a larger area and then scale that area back into the original dimensions.
.container {_x000D_
width: 800px;_x000D_
height: 300px;_x000D_
border: 1px solid black;_x000D_
overflow:hidden;_x000D_
position:relative;_x000D_
}_x000D_
.container.contain img {_x000D_
position: absolute;_x000D_
left:-10000%; right: -10000%; _x000D_
top: -10000%; bottom: -10000%;_x000D_
margin: auto auto;_x000D_
max-width: 10%;_x000D_
max-height: 10%;_x000D_
-webkit-transform:scale(10);_x000D_
transform: scale(10);_x000D_
}_x000D_
.container.cover img {_x000D_
position: absolute;_x000D_
left:-10000%; right: -10000%; _x000D_
top: -10000%; bottom: -10000%;_x000D_
margin: auto auto;_x000D_
min-width: 1000%;_x000D_
min-height: 1000%;_x000D_
-webkit-transform:scale(0.1);_x000D_
transform: scale(0.1);_x000D_
}
_x000D_
<h1>contain</h1>_x000D_
<div class="container contain">_x000D_
<img _x000D_
src="https://www.google.de/logos/doodles/2014/european-parliament-election-2014-day-4-5483168891142144-hp.jpg" _x000D_
/>_x000D_
<!-- 366x200 -->_x000D_
</div>_x000D_
<h1>cover</h1>_x000D_
<div class="container cover">_x000D_
<img _x000D_
src="https://www.google.de/logos/doodles/2014/european-parliament-election-2014-day-4-5483168891142144-hp.jpg" _x000D_
/>_x000D_
<!-- 366x200 -->_x000D_
</div>
_x000D_
Try this:
// I suppose you have already set your JFrame
Icon imgIcon = new ImageIcon(this.getClass().getResource("ajax-loader.gif"));
JLabel label = new JLabel(imgIcon);
label.setBounds(668, 43, 46, 14); // for example, you can use your own values
frame.getContentPane().add(label);
Found on this tutorial on how to display animated gif in java
Or live on youtube : https://youtu.be/_NEnhm9mgdE
I use the following class which implements the Runnable interface. With this class you can easily create new threads with arguments
public abstract class RunnableArg implements Runnable {
Object[] m_args;
public RunnableArg() {
}
public void run(Object... args) {
setArgs(args);
run();
}
public void setArgs(Object... args) {
m_args = args;
}
public int getArgCount() {
return m_args == null ? 0 : m_args.length;
}
public Object[] getArgs() {
return m_args;
}
}
The only way to execute PHP from JS is AJAX. You can send data to server (for eg, GET /ajax.php?do=someFunction) then in ajax.php you write:
function someFunction() {
echo 'Answer';
}
if ($_GET['do'] === "someFunction") {
someFunction();
}
and then, catch the answer with JS (i'm using jQuery for making AJAX requests)
Probably you'll need some format of answer. See JSON or XML, but JSON is easy to use with JavaScript. In PHP you can use function json_encode($array); which gets array as argument.
They are names for the same standard from two different industries with different naming methods, the guys who make & sell movies and the guys who transfer the movies over the internet. Since 2003: "MPEG 4 Part 10" = "H.264" = "AVC". Before that the relationship was a little looser in that they are not equal but an "MPEG 4 Part 2" decoder can render a stream that's "H.263". The Next standard is "MPEG H Part 2" = "H.265" = "HEVC"
A very useful way to fix this is to detect the browsers webkit version and check if it is at least the one we need, else do something else.
Using jQuery it goes like this:
"use strict";_x000D_
_x000D_
$(document).ready(function() {_x000D_
var appVersion = navigator.appVersion;_x000D_
var webkitVersion_positionStart = appVersion.indexOf("AppleWebKit/") + 12;_x000D_
var webkitVersion_positionEnd = webkitVersion_positionStart + 3;_x000D_
var webkitVersion = appVersion.slice(webkitVersion_positionStart, webkitVersion_positionEnd);_x000D_
_x000D_
console.log(webkitVersion);_x000D_
_x000D_
if (webkitVersion < 537) {_x000D_
console.log("webkit outdated.");_x000D_
} else {_x000D_
console.log("webkit ok.");_x000D_
};_x000D_
});
_x000D_
This provides a safe and permanent fix for dealing with problems with browser's different webkit implementations.
Happy coding!
wget -m -p -E -k -K -np http://site/path/
man page will tell you what those options do.
wget
will only follow links, if there is no link to a file from the index page, then wget
will not know about its existence, and hence not download it. ie. it helps if all files are linked to in web pages or in directory indexes.
// Simply:
$date = date('Y-m-d H:i:s');
// Or:
$date = date('Y/m/d H:i:s');
// This would return the date in the following formats respectively:
$date = '2012-03-06 17:33:07';
// Or
$date = '2012/03/06 17:33:07';
/**
* This time is based on the default server time zone.
* If you want the date in a different time zone,
* say if you come from Nairobi, Kenya like I do, you can set
* the time zone to Nairobi as shown below.
*/
date_default_timezone_set('Africa/Nairobi');
// Then call the date functions
$date = date('Y-m-d H:i:s');
// Or
$date = date('Y/m/d H:i:s');
// date_default_timezone_set() function is however
// supported by PHP version 5.1.0 or above.
For a time-zone reference, see List of Supported Timezones.
This is another solution which I use:
public class CustomAnimator {
private static final String TAG = "com.example.CustomAnimator";
private static Stack<AnimationEntry> animation_stack = new Stack<>();
public static final int DIRECTION_LEFT = 1;
public static final int DIRECTION_RIGHT = -1;
public static final int DIRECTION_UP = 2;
public static final int DIRECTION_DOWN = -2;
static class AnimationEntry {
View in;
View out;
int direction;
long duration;
}
public static boolean hasHistory() {
return !animation_stack.empty();
}
public static void reversePrevious() {
if (!animation_stack.empty()) {
AnimationEntry entry = animation_stack.pop();
slide(entry.out, entry.in, -entry.direction, entry.duration, false);
}
}
public static void clearHistory() {
animation_stack.clear();
}
public static void slide(final View in, View out, final int direction, long duration) {
slide(in, out, direction, duration, true);
}
private static void slide(final View in, final View out, final int direction, final long duration, final boolean save) {
ViewGroup in_parent = (ViewGroup) in.getParent();
ViewGroup out_parent = (ViewGroup) out.getParent();
if (!in_parent.equals(out_parent)) {
return;
}
int parent_width = in_parent.getWidth();
int parent_height = in_parent.getHeight();
ObjectAnimator slide_out;
ObjectAnimator slide_in;
switch (direction) {
case DIRECTION_LEFT:
default:
slide_in = ObjectAnimator.ofFloat(in, "translationX", parent_width, 0);
slide_out = ObjectAnimator.ofFloat(out, "translationX", 0, -out.getWidth());
break;
case DIRECTION_RIGHT:
slide_in = ObjectAnimator.ofFloat(in, "translationX", -out.getWidth(), 0);
slide_out = ObjectAnimator.ofFloat(out, "translationX", 0, parent_width);
break;
case DIRECTION_UP:
slide_in = ObjectAnimator.ofFloat(in, "translationY", parent_height, 0);
slide_out = ObjectAnimator.ofFloat(out, "translationY", 0, -out.getHeight());
break;
case DIRECTION_DOWN:
slide_in = ObjectAnimator.ofFloat(in, "translationY", -out.getHeight(), 0);
slide_out = ObjectAnimator.ofFloat(out, "translationY", 0, parent_height);
break;
}
AnimatorSet animations = new AnimatorSet();
animations.setDuration(duration);
animations.playTogether(slide_in, slide_out);
animations.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationCancel(Animator arg0) {
}
@Override
public void onAnimationEnd(Animator arg0) {
out.setVisibility(View.INVISIBLE);
if (save) {
AnimationEntry ae = new AnimationEntry();
ae.in = in;
ae.out = out;
ae.direction = direction;
ae.duration = duration;
animation_stack.push(ae);
}
}
@Override
public void onAnimationRepeat(Animator arg0) {
}
@Override
public void onAnimationStart(Animator arg0) {
in.setVisibility(View.VISIBLE);
}
});
animations.start();
}
}
The usage of class. Let's say you have two fragments (list and details fragments)as shown below
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ui_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="@+id/list_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<FrameLayout
android:id="@+id/details_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone" />
</FrameLayout>
Usage
View details_container = findViewById(R.id.details_container);
View list_container = findViewById(R.id.list_container);
// You can select the direction left/right/up/down and the duration
CustomAnimator.slide(list_container, details_container,CustomAnimator.DIRECTION_LEFT, 400);
You can use the function CustomAnimator.reversePrevious();
to get the previous view when the user pressed back.
You either use :
background-image: url("images/plaid.jpg");
background-repeat: no-repeat;
... or
background: transparent url("images/plaid.jpg") top left no-repeat;
... but definitively not
background-image: url("images/plaid.jpg") no-repeat;
EDIT : Demo at JSFIDDLE using absolute paths (in case you have troubles referring to your images with relative paths).
In your Xampp folder, open php.ini
file inside the PHP folder i.e xampp\php\php.ini
(with a text editor).
Search for extension=mysqli
(Ctrl+F), if there are two, look for the one that has been uncommented (without ";" behind)
Change the mysqli with the correct path address i.e extension=C:\xampp\php\ext\php_mysqli.dll
.
On your Xampp control panel, stop and start apache and MySQL
I found this resource that details the various methods: How to embed TIFF files in HTML documents
As mentioned, it will very much depend on browser support for the format. Viewing that page in Chrome on Windows didn't display any of the images.
It would also be helpful if you posted the code you've tried already.
I had to solve a similar problem--I wanted certain styles to only apply to mobile devices in landscape mode. Essentially the fonts and line spacing looked fine in every other context, so I just needed the one exception for mobile landscape. This media query worked perfectly:
@media all and (max-width: 600px) and (orientation:landscape)
{
/* styles here */
}
The query either returned no rows or is erroneus, thus FALSE
is returned. Change it to
if (!$dbc || mysqli_num_rows($dbc) == 0)
mysqli_num_rows
:
Return Values
Returns TRUE on success or FALSE on failure. For SELECT, SHOW, DESCRIBE or EXPLAIN mysqli_query() will return a result object.
When using nohup
and you put the task in the background, the background operator (&
) will give you the PID at the command prompt. If your plan is to manually manage the process, you can save that PID and use it later to kill the process if needed, via kill PID
or kill -9 PID
(if you need to force kill). Alternatively, you can find the PID later on by ps -ef | grep "command name"
and locate the PID from there. Note that nohup
keyword/command itself does not appear in the ps
output for the command in question.
If you use a script, you could do something like this in the script:
nohup my_command > my.log 2>&1 &
echo $! > save_pid.txt
This will run my_command
saving all output into my.log
(in a script, $!
represents the PID of the last process executed). The 2
is the file descriptor for standard error (stderr
) and 2>&1
tells the shell to route standard error output to the standard output (file descriptor 1
). It requires &1
so that the shell knows it's a file descriptor in that context instead of just a file named 1
. The 2>&1
is needed to capture any error messages that normally are written to standard error into our my.log
file (which is coming from standard output). See I/O Redirection for more details on handling I/O redirection with the shell.
If the command sends output on a regular basis, you can check the output occasionally with tail my.log
, or if you want to follow it "live" you can use tail -f my.log
. Finally, if you need to kill the process, you can do it via:
kill -9 `cat save_pid.txt`
rm save_pid.txt
My rule of thumb is:
Use pointers if you want to do pointer arithmetic with them (e.g. incrementing the pointer address to step through an array) or if you ever have to pass a NULL-pointer.
Use references otherwise.
A temporary table can have 3 kinds, the #
is the most used. This is a temp table that only exists in the current session.
An equivalent of this is @
, a declared table variable. This has a little less "functions" (like indexes etc) and is also only used for the current session.
The ##
is one that is the same as the #
, however, the scope is wider, so you can use it within the same session, within other stored procedures.
You can create a temp table in various ways:
declare @table table (id int)
create table #table (id int)
create table ##table (id int)
select * into #table from xyz
It's about Persian language problem, Just need to rotate your ListView, GridView, or .... and after that rotate your cell. You can do it in xml android:rotate="360".
Remenber run lombok.jar
as a java app, if your using windows7 open a console(cmd.exe) as adminstrator, and run C:"your java instalation"\ java -jar "lombok directory"\lombok.jar
and then lombok ask for yours ides ubication.
This is the way i did it, with a button to add each select tag.
$(document).on("click","#button",function() {
$('#id_table_AddTransactions').append('<option></option>')
}
Simple & short solution worked for me.
Go to File
-> Settings
-> Editor
-> Auto Import
-> Java
(left panel) and make the below things:
Select check box for "Add unambigious imports on the fly
" and "Optimize imports on the fly
"
Refer this.
If anyone has the same problem, one possible solution is to set the bindto
stream context configuration parameter (assuming you're connecting from 11.22.33.44 to 55.66.77.88):
$context = [
'socket' => [
'bindto' => '55.66.77.88'
]
];
$options = [
'soapVersion' => SOAP_1_1,
'stream_context' => stream_context_create($context)
];
$client = new Client('11.22.33.44', $options);
Preserve the name of the column and avoid extra column addition by using the same name as input column:
changedTypedf = joindf.withColumn("show", joindf["show"].cast(DoubleType()))
This usually has to do with a selector not being used properly. Check and make sure that you are using the jQuery selectors like intended. For example I had this problem when creating a click method:
$("[editButton]").click(function () {
this.css("color", "red");
});
Because I was not using the correct selector method $(this) for jQuery it gave me the same error.
So simply enough, check your selectors!
You use the cherry-pick command to get individual commits from one branch.
If the change(s) you want are not in individual commits, then use the method shown here to split the commit into individual commits. Roughly speaking, you use git rebase -i
to get the original commit to edit, then git reset HEAD^
to selectively revert changes, then git commit
to commit that bit as a new commit in the history.
There is another nice method here in Red Hat Magazine, where they use git add --patch
or possibly git add --interactive
which allows you to add just parts of a hunk, if you want to split different changes to an individual file (search in that page for "split").
Having split the changes, you can now cherry-pick just the ones you want.
Relying on column order is generally a bad idea in SQL. SQL is based on Relational theory where order is never guaranteed - by design. You should treat all your columns and rows as having no order and then change your queries to provide the correct results:
For Columns:
For Rows:
Hope this helps...
You can use java.util.Arrays:
String res = Arrays.toString(array);
System.out.println(res);
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
It's a Bash feature called "tilde expansion". It's a function of the shell, not the OS. You'll get different behavior with csh, for example.
To answer your question about where the information comes from: your home directory comes from the variable $HOME
(no matter what you store there), while other user's homes are retrieved real-time using getpwent()
. This function is usually controlled by NSS; so by default values are pulled out of /etc/passwd
, though it can be configured to retrieve the information using any source desired, such as NIS, LDAP or an SQL database.
Tilde expansion is more than home directory lookup. Here's a summary:
~ $HOME
~fred (freds home dir)
~+ $PWD (your current working directory)
~- $OLDPWD (your previous directory)
~1 `dirs +1`
~2 `dirs +2`
~-1 `dirs -1`
dirs
and ~1
, ~-1
, etc., are used in conjunction with pushd
and popd
.
Maybe can be shorter an more elegant. But I did it.
public String getHumanTimeFormatFromMilliseconds(String millisecondS){
String message = "";
long milliseconds = Long.valueOf(millisecondS);
if (milliseconds >= 1000){
int seconds = (int) (milliseconds / 1000) % 60;
int minutes = (int) ((milliseconds / (1000 * 60)) % 60);
int hours = (int) ((milliseconds / (1000 * 60 * 60)) % 24);
int days = (int) (milliseconds / (1000 * 60 * 60 * 24));
if((days == 0) && (hours != 0)){
message = String.format("%d hours %d minutes %d seconds ago", hours, minutes, seconds);
}else if((hours == 0) && (minutes != 0)){
message = String.format("%d minutes %d seconds ago", minutes, seconds);
}else if((days == 0) && (hours == 0) && (minutes == 0)){
message = String.format("%d seconds ago", seconds);
}else{
message = String.format("%d days %d hours %d minutes %d seconds ago", days, hours, minutes, seconds);
}
} else{
message = "Less than a second ago.";
}
return message;
}
If you code in C++ as well as Java, it is better to remember that in C++, the string class has the == operator overloaded. But not so in Java. you need to use equals()
or equalsIgnoreCase()
for that.
JsonObjectRequest
actually accepts JSONObject
as body.
From this blog article,
final String url = "some/url";
final JSONObject jsonBody = new JSONObject("{\"type\":\"example\"}");
new JsonObjectRequest(url, jsonBody, new Response.Listener<JSONObject>() { ... });
Here is the source code and JavaDoc (@param jsonRequest
):
/**
* Creates a new request.
* @param method the HTTP method to use
* @param url URL to fetch the JSON from
* @param jsonRequest A {@link JSONObject} to post with the request. Null is allowed and
* indicates no parameters will be posted along with request.
* @param listener Listener to receive the JSON response
* @param errorListener Error listener, or null to ignore errors.
*/
public JsonObjectRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONObject> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
errorListener);
}
These are includes for using shared memory
#include<sys/ipc.h>
#include<sys/shm.h>
int shmid;
int shmkey = 12222;//u can choose it as your choice
int main()
{
//now your main starting
shmid = shmget(shmkey,1024,IPC_CREAT);
// 1024 = your preferred size for share memory
// IPC_CREAT its a flag to create shared memory
//now attach a memory to this share memory
char *shmpointer = shmat(shmid,NULL);
//do your work with the shared memory
//read -write will be done with the *shmppointer
//after your work is done deattach the pointer
shmdt(&shmpointer, NULL);
Here is how I solved the issue, might be useful to some:
Ajax modal doesn't seem to be available with boostrap 2.1.1
So I ended up coding it myself:
$('[data-toggle="modal"]').click(function(e) {
e.preventDefault();
var url = $(this).attr('href');
//var modal_id = $(this).attr('data-target');
$.get(url, function(data) {
$(data).modal();
});
});
Example of a link that calls a modal:
<a href="{{ path('ajax_get_messages', { 'superCategoryID': 6, 'sex': sex }) }}" data-toggle="modal">
<img src="{{ asset('bundles/yopyourownpoet/images/messageCategories/BirthdaysAnniversaries.png') }}" alt="Birthdays" height="120" width="109"/>
</a>
I now send the whole modal markup through ajax.
Credits to drewjoh
I was able to change the button's text like this:
import android.widget.RemoteViews;
//grab the layout, then set the text of the Button called R.id.Counter:
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.my_layout);
remoteViews.setTextViewText(R.id.Counter, "Set button text here");
Instead of
getApplication().setTheme(R.style.BlackTheme);
use
setTheme(R.style.BlackTheme);
My code: in onCreate() method:
super.onCreate(savedInstanceState);
if(someExpression) {
setTheme(R.style.OneTheme);
} else {
setTheme(R.style.AnotherTheme);
}
setContentView(R.layout.activity_some_layout);
Somewhere (for example, on a button click):
YourActivity.this.recreate();
You have to recreate activity, otherwise - change won't happen
What about trying the which
command?
If you were to run which psql
and Postgres is not installed there appears to be no output. You just get the terminal prompt ready to accept another command:
> which psql
>
But if Postgres is installed you'll get a response with the path to the location of the Postgres install:
> which psql
/opt/boxen/homebrew/bin/psql
Looking at man which
there also appears to be an option that could help you out:
-s No output, just return 0 if any of the executables are found, or
1 if none are found.
So it seems like as long as whatever scripting language you're using can can execute a terminal command you could send which -s psql
and use the return value to determine if Postgres is installed. From there you can print that result however you like.
I do have postgres installed on my machine so I run the following
> which -s psql
> echo $?
0
which tells me that the command returned 0, indicating that the Postgres executable was found on my machine.
Try str_detect()
from the stringr package, which detects the presence or absence of a pattern in a string.
Here is an approach that also incorporates the %>%
pipe and filter()
from the dplyr package:
library(stringr)
library(dplyr)
CO2 %>%
filter(str_detect(Treatment, "non"))
Plant Type Treatment conc uptake
1 Qn1 Quebec nonchilled 95 16.0
2 Qn1 Quebec nonchilled 175 30.4
3 Qn1 Quebec nonchilled 250 34.8
4 Qn1 Quebec nonchilled 350 37.2
5 Qn1 Quebec nonchilled 500 35.3
...
This filters the sample CO2 data set (that comes with R) for rows where the Treatment variable contains the substring "non". You can adjust whether str_detect
finds fixed matches or uses a regex - see the documentation for the stringr package.
If you're dealing with natural language text and need to replace a word, not just part of a string, you have to add a pinch of regular expressions to your gsub as a plain text substitution can lead to disastrous results:
'mislocated cat, vindicating'.gsub('cat', 'dog')
=> "mislodoged dog, vindidoging"
Regular expressions have word boundaries, such as \b
which matches start or end of a word. Thus,
'mislocated cat, vindicating'.gsub(/\bcat\b/, 'dog')
=> "mislocated dog, vindicating"
In Ruby, unlike some other languages like Javascript, word boundaries are UTF-8-compatible, so you can use it for languages with non-Latin or extended Latin alphabets:
'???? ? ??????, ??? ??????'.gsub(/\b????\b/, '?????')
=> "????? ? ??????, ??? ??????"
Confirmed, adding a Key works. I went through the docs to try and understand why.
React wants to be efficient when creating child components. It won't render a new component if it's the same as another child, which makes the page load faster.
Adding a Key forces React to render a new component, thus resetting State for that new component.
https://reactjs.org/docs/reconciliation.html#recursing-on-children
If you have entered 'Debug server host & port for device' in Dev Settings, make sure you remove what you have entered.
res.send()
implements res.write
, res.setHeaders
and res.end
:
res.write
.res.end
to set the end of the request.There are some cases in which you will want to do this manually, for example, if you want to stream a file or a large data set. In these cases, you will want to set the headers yourself and use res.write
to keep the stream flow.
I know this thread is a bit old, but it took me some time to get to the heart of this, so I wanted to share.
In my project, I had the main script in a parent directory, and, to differentiate the modules, I put all the supporting modules in a sub-folder called "modules". In my main script, I import these modules like this (for a module called report.py):
from modules.report import report, reportError
If I call my main script, this works. HOWEVER, I wanted to test each module by including a main()
in each, and calling each directly, as:
python modules/report.py
Now Python complains that it can't find "a module called modules". The key here is that, by default, Python includes the folder of the script in its search path, BUT NOT THE CWD. So what this error says, really, is "I can't find a modules subfolder". The is because there is no "modules" subdirectory from the directory where the report.py module resides.
I find that the neatest solution to this is to append the CWD in Python search path by including this at the top:
import sys
sys.path.append(".")
Now Python searches the CWD (current directory), finds the "modules" sub-folder, and all is well.
While technically correct, the other answers would benefit from an explanation of Angular's URL-to-route matching. I don't think you can fully (pardon the pun) understand what pathMatch: full
does if you don't know how the router works in the first place.
Let's first define a few basic things. We'll use this URL as an example: /users/james/articles?from=134#section
.
It may be obvious but let's first point out that query parameters (?from=134
) and fragments (#section
) do not play any role in path matching. Only the base url (/users/james/articles
) matters.
Angular splits URLs into segments. The segments of /users/james/articles
are, of course, users
, james
and articles
.
The router configuration is a tree structure with a single root node. Each Route
object is a node, which may have children
nodes, which may in turn have other children
or be leaf nodes.
The goal of the router is to find a router configuration branch, starting at the root node, which would match exactly all (!!!) segments of the URL. This is crucial! If Angular does not find a route configuration branch which could match the whole URL - no more and no less - it will not render anything.
E.g. if your target URL is /a/b/c
but the router is only able to match either /a/b
or /a/b/c/d
, then there is no match and the application will not render anything.
Finally, routes with redirectTo
behave slightly differently than regular routes, and it seems to me that they would be the only place where anyone would really ever want to use pathMatch: full
. But we will get to this later.
prefix
) path matchingThe reasoning behind the name prefix
is that such a route configuration will check if the configured path
is a prefix of the remaining URL segments. However, the router is only able to match full segments, which makes this naming slightly confusing.
Anyway, let's say this is our root-level router configuration:
const routes: Routes = [
{
path: 'products',
children: [
{
path: ':productID',
component: ProductComponent,
},
],
},
{
path: ':other',
children: [
{
path: 'tricks',
component: TricksComponent,
},
],
},
{
path: 'user',
component: UsersonComponent,
},
{
path: 'users',
children: [
{
path: 'permissions',
component: UsersPermissionsComponent,
},
{
path: ':userID',
children: [
{
path: 'comments',
component: UserCommentsComponent,
},
{
path: 'articles',
component: UserArticlesComponent,
},
],
},
],
},
];
Note that every single Route
object here uses the default matching strategy, which is prefix
. This strategy means that the router iterates over the whole configuration tree and tries to match it against the target URL segment by segment until the URL is fully matched. Here's how it would be done for this example:
users
.'products' !== 'users'
, so skip that branch. Note that we are using an equality check rather than a .startsWith()
or .includes()
- only full segment matches count!:other
matches any value, so it's a match. However, the target URL is not yet fully matched (we still need to match james
and articles
), thus the router looks for children.:other
is tricks
, which is !== 'james'
, hence not a match.'user' !== 'users
, skip branch.'users' === 'users
- the segment matches. However, this is not a full match yet, thus we need to look for children (same as in step 3).'permissions' !== 'james'
, skip it.:userID
matches anything, thus we have a match for the james
segment. However this is still not a full match, thus we need to look for a child which would match articles
.
:userID
has a child route articles
, which gives us a full match! Thus the application renders UserArticlesComponent
.full
) matchingImagine now that the users
route configuration object looked like this:
{
path: 'users',
component: UsersComponent,
pathMatch: 'full',
children: [
{
path: 'permissions',
component: UsersPermissionsComponent,
},
{
path: ':userID',
component: UserComponent,
children: [
{
path: 'comments',
component: UserCommentsComponent,
},
{
path: 'articles',
component: UserArticlesComponent,
},
],
},
],
}
Note the usage of pathMatch: full
. If this were the case, steps 1-5 would be the same, however step 6 would be different:
'users' !== 'users/james/articles
- the segment does not match because the path configuration users
with pathMatch: full
does not match the full URL, which is users/james/articles
.What if we had this instead:
{
path: 'users/:userID',
component: UsersComponent,
pathMatch: 'full',
children: [
{
path: 'comments',
component: UserCommentsComponent,
},
{
path: 'articles',
component: UserArticlesComponent,
},
],
}
users/:userID
with pathMatch: full
matches only users/james
thus it's a no-match once again, and the application renders nothing.
Let's consider this:
{
path: 'users',
children: [
{
path: 'permissions',
component: UsersPermissionsComponent,
},
{
path: ':userID',
component: UserComponent,
pathMatch: 'full',
children: [
{
path: 'comments',
component: UserCommentsComponent,
},
{
path: 'articles',
component: UserArticlesComponent,
},
],
},
],
}
In this case:
'users' === 'users
- the segment matches, but james/articles
still remains unmatched. Let's look for children.'permissions' !== 'james'
- skip.:userID'
can only match a single segment, which would be james
. However, it's a pathMatch: full
route, and it must match james/articles
(the whole remaining URL). It's not able to do that and thus it's not a match (so we skip this branch)!As you may have noticed, a pathMatch: full
configuration is basically saying this:
Ignore my children and only match me. If I am not able to match all of the remaining URL segments myself, then move on.
Any Route
which has defined a redirectTo
will be matched against the target URL according to the same principles. The only difference here is that the redirect is applied as soon as a segment matches. This means that if a redirecting route is using the default prefix
strategy, a partial match is enough to cause a redirect. Here's a good example:
const routes: Routes = [
{
path: 'not-found',
component: NotFoundComponent,
},
{
path: 'users',
redirectTo: 'not-found',
},
{
path: 'users/:userID',
children: [
{
path: 'comments',
component: UserCommentsComponent,
},
{
path: 'articles',
component: UserArticlesComponent,
},
],
},
];
For our initial URL (/users/james/articles
), here's what would happen:
'not-found' !== 'users'
- skip it.'users' === 'users'
- we have a match.redirectTo: 'not-found'
, which is applied immediately.not-found
.not-found
right away. The application renders NotFoundComponent
.Now consider what would happen if the users
route also had pathMatch: full
:
const routes: Routes = [
{
path: 'not-found',
component: NotFoundComponent,
},
{
path: 'users',
pathMatch: 'full',
redirectTo: 'not-found',
},
{
path: 'users/:userID',
children: [
{
path: 'comments',
component: UserCommentsComponent,
},
{
path: 'articles',
component: UserArticlesComponent,
},
],
},
];
'not-found' !== 'users'
- skip it.users
would match the first segment of the URL, but the route configuration requires a full
match, thus skip it.'users/:userID'
matches users/james
. articles
is still not matched but this route has children.articles
in the children. The whole URL is now matched and the application renders UserArticlesComponent
.path: ''
)The empty path is a bit of a special case because it can match any segment without "consuming" it (so it's children would have to match that segment again). Consider this example:
const routes: Routes = [
{
path: '',
children: [
{
path: 'users',
component: BadUsersComponent,
}
]
},
{
path: 'users',
component: GoodUsersComponent,
},
];
Let's say we are trying to access /users
:
path: ''
will always match, thus the route matches. However, the whole URL has not been matched - we still need to match users
!users
, which matches the remaining (and only!) segment and we have a full match. The application renders BadUsersComponent
.The OP used this router configuration:
const routes: Routes = [
{
path: 'welcome',
component: WelcomeComponent,
},
{
path: '',
redirectTo: 'welcome',
pathMatch: 'full',
},
{
path: '**',
redirectTo: 'welcome',
pathMatch: 'full',
},
];
If we are navigating to the root URL (/
), here's how the router would resolve that:
welcome
does not match an empty segment, so skip it.path: ''
matches the empty segment. It has a pathMatch: 'full'
, which is also satisfied as we have matched the whole URL (it had a single empty segment).welcome
happens and the application renders WelcomeComponent
.pathMatch: 'full'
?Actually, one would expect the whole thing to behave exactly the same. However, Angular explicitly prevents such a configuration ({ path: '', redirectTo: 'welcome' }
) because if you put this Route
above welcome
, it would theoretically create an endless loop of redirects. So Angular just throws an error, which is why the application would not work at all! (https://angular.io/api/router/Route#pathMatch)
Actually, this does not make too much sense to me because Angular also has implemented a protection against such endless redirects - it only runs a single redirect per routing level! This would stop all further redirects (as you'll see in the example below).
path: '**'
?path: '**'
will match absolutely anything (af/frewf/321532152/fsa
is a match) with or without a pathMatch: 'full'
.
Also, since it matches everything, the root path is also included, which makes { path: '', redirectTo: 'welcome' }
completely redundant in this setup.
Funnily enough, it is perfectly fine to have this configuration:
const routes: Routes = [
{
path: '**',
redirectTo: 'welcome'
},
{
path: 'welcome',
component: WelcomeComponent,
},
];
If we navigate to /welcome
, path: '**'
will be a match and a redirect to welcome will happen. Theoretically this should kick off an endless loop of redirects but Angular stops that immediately (because of the protection I mentioned earlier) and the whole thing works just fine.
Given the specific title of this post, here's my suggestion:
ls | grep ' ' | tr ' ' '<' | sed 's|<|\\ |g'
The idea is to convert blanks to any unique character, like '<', and then change that into '\ ', a backslash followed by a blank. You can then pipe that into any command you like, such as:
ls | grep ' ' | tr ' ' '<' | sed 's|<|\\ |g' | xargs -L1 GetFileInfo
The key here lies in the 'tr' and 'sed' commands; and you can use any character besides '<', such as '?' or even a tab-character.
It is Safari specific, at least at time of writing, being introduced in Safari 9.0. From the "What's new in Safari?" documentation for Safari 9.0:
Viewport Changes
Viewport meta tags using
"width=device-width"
cause the page to scale down to fit content that overflows the viewport bounds. You can override this behavior by adding"shrink-to-fit=no"
to your meta tag as shown below. The added value will prevent the page from scaling to fit the viewport.
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
In short, adding this to the viewport meta tag restores pre-Safari 9.0 behaviour.
Here's a worked visual example which shows the difference upon loading the page in the two configurations.
The red section is the width of the viewport and the blue section is positioned outside the initial viewport (eg left: 100vw
). Note how in the first example the page is zoomed to fit when shrink-to-fit=no
is omitted (thus showing the out-of-viewport content) and the blue content remains off screen in the latter example.
The code for this example can be found at https://codepen.io/davidjb/pen/ENGqpv.
In Swift you would do it like this:
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.numberOfLines = 0
(Note that the way the lineBreakMode constant works is different to in ObjC)
You will get selected option's value and text from list/array by using filter.
editobj.FlagName=(EmployeeStatus|filter:{Value:editobj.Flag})[0].KeyName
<select name="statusSelect"
id="statusSelect"
class="form-control"
ng-model="editobj.Flag"
ng-options="option.Value as option.KeyName for option in EmployeeStatus"
ng-change="editobj.FlagName=(EmployeeStatus|filter:{Value:editobj.Flag})[0].KeyName">
</select>
ReactJs defines the following synthetic events for mouse events:
onClick onContextMenu onDoubleClick onDrag onDragEnd onDragEnter onDragExit
onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave
onMouseMove onMouseOut onMouseOver onMouseUp
As you can see there is no hover event, because browsers do not define a hover event natively.
You will want to add handlers for onMouseEnter and onMouseLeave for hover behavior.
For anyone looking for a UI option using IIS Manager.
C++ has no specific feature to do that. However, if you use a std::vector instead of an array (as you probably should do) then you can specify a value to initialise the vector with.
std::vector <char> v( 100, 42 );
creates a vector of size 100 with all values initialised to 42.
Try this:
XmlDocument bodyDoc = new XmlDocument();
bodyDoc.XMLResolver = null;
bodyDoc.Load(body);
If you are uploading your files through GIT from your local machine then you can use the same command you are using in your local machine while you are connected to your live server using BASH or something like.You can use this as like you use locally.
php artisan cache:clear
php artisan route:cache
It should work.
I found the solution! Just copy the sheet with your named variables. Then delete the original sheet. The copied sheet will now have the same named variables, but with a local scope (scope= the copied sheet).
However, I don't know how to change from local variables to global..
When root (sudo) permissions are required, which is usually 90%+ when using scripts, the methods in previous answers always give you root
as the answer.
To get the current "logged in" user is just as simple, but it requires accessing different variables: $SUDO_UID
and $SUDO_USER
.
They can be echoed:
echo $SUDO_UID
echo $SUDO_USER
Or assigned, for example:
myuid=$SUDO_UID
myuname=$SUDO_USER
It is possible to view a html file from terminal using lynx or links. But none of those browswers support the onload javascript feature. By using lynx or links you will have to actively click the submit button.
You can check
if(Looper.myLooper() == Looper.getMainLooper()) {
// You are on mainThread
}else{
// you are on non-ui thread
}
Even better than having it with @Autowired is to let it be injected via constructor. Find some arguments pro constructor injection here
@Component
public class MyClass{
private final ApplicationContext applicationContext;
public MyClass(ApplicationContext applicationContext){
this.applicationContext = applicationContext;
}
//here will be your methods using the applicationcontext
}
For me DownloadSVN is the best SVN client no install no explore shell integration so no need to worry about system instability small and very light weight and it does a great job just recently i had a very bad experience with TortoiseSVN on my WindowsXP_x86:) luckily i found this great SVN client
An example.
$query_new = "INSERT INTO students(courseid, coursename) VALUES ('', ?)";
$query_new = $databaseConnection->prepare($query_new);
$query_new->bind_param('s', $_POST['coursename']);
$query_new->execute();
$course_id = $query_new->insert_id;
$query_new->close();
The code line $course_id = $query_new->insert_id;
will display the ID of the last inserted row.
Hope this helps.
1) This problem occure due to apk file .if your apk file
(output/apk/debug.apk) not generated in this format .
2) you should use always in gradle file .
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
SELECT id, GROUP_CONCAT( string SEPARATOR ' ') FROM table GROUP BY id
More details here.
From the link above, GROUP_CONCAT
: This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values.
How about the following?
irb(main):003:0> my_string = "Some text with a carriage return \r"
=> "Some text with a carriage return \r"
irb(main):004:0> my_string.gsub(/\r/,"")
=> "Some text with a carriage return "
irb(main):005:0>
Or...
irb(main):007:0> my_string = "Some text with a carriage return \r\n"
=> "Some text with a carriage return \r\n"
irb(main):008:0> my_string.gsub(/\r\n/,"\n")
=> "Some text with a carriage return \n"
irb(main):009:0>
ng-if if false will remove elements from DOM. This means that all your events, directives attached to those elements will be lost. For example, ng-click to one of child elements, when ng-if evaluates to false, that element will be removed from DOM and again when it is true it is recreated.
ng-show/ng-hide does not remove the elements from DOM. It uses CSS styles (.ng-hide) to hide/show elements .This way your events, directives that were attached to children will not be lost.
ng-if creates a child scope while ng-show/ng-hide does not.
expanding on the answer above the 'each' function will return you the table-cell html object. wrapping that in $() will then allow you to perform jquery actions on it.
$(this).find('td').each (function( column, td) {
$(td).blah
});
password.setInputType(InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_PASSWORD);
also you have to be careful that cursor moves to the starting point of the editText after this function is called, so make sure that you move cursor to the end point again.
In controller:
function innerItem($scope, $element){
var jQueryInnerItem = $($element);
}
Response.Cookies["UserSettings"].Expires = DateTime.Now.AddDays(-1)
This looks like a behavior difference in the handling of \s
between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).
Note:
GNU grep 2.5.4
echo "foo bar" | grep "\s"
(doesn't match)
whereas
GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar
Probably less trouble (as \s
is not documented):
Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar
My advice is to avoid using \s
... use [ \t]*
or [[:space:]]
or something like it instead.
If you, like me, just want to be able to run the release on your device for testing purposes, consider creating a second keystore for signing, so you can simply put the passwords for it into your build.gradle without worrying for your market key store security.
You can create a new keystore by clicking Build/Generate Signed APK/Create new...
You can use Map.
- A new data structure introduced in JavaScript ES6.
- Alternative to JavaScript Object for storing key/value pairs.
- Has useful methods for iteration over the key/value pairs.
var map = new Map();
map.set('name', 'John');
map.set('id', 11);
// Get the full content of the Map
console.log(map); // Map { 'name' => 'John', 'id' => 11 }
Get value of the Map using key
console.log(map.get('name')); // John
console.log(map.get('id')); // 11
Get size of the Map
console.log(map.size); // 2
Check key exists in Map
console.log(map.has('name')); // true
console.log(map.has('age')); // false
Get keys
console.log(map.keys()); // MapIterator { 'name', 'id' }
Get values
console.log(map.values()); // MapIterator { 'John', 11 }
Get elements of the Map
for (let element of map) {
console.log(element);
}
// Output:
// [ 'name', 'John' ]
// [ 'id', 11 ]
Print key value pairs
for (let [key, value] of map) {
console.log(key + " - " + value);
}
// Output:
// name - John
// id - 11
Print only keys of the Map
for (let key of map.keys()) {
console.log(key);
}
// Output:
// name
// id
Print only values of the Map
for (let value of map.values()) {
console.log(value);
}
// Output:
// John
// 11
Here's a version of the accepted answer that 1) returns
a value from the function (bugfix), and 2) doesn't break when using "use strict";
I use this code to pre-load a .txt
file into my <textarea>
when the user loads the page.
function httpGet(theUrl)
{
let xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
return xmlhttp.responseText;
}
}
xmlhttp.open("GET", theUrl, false);
xmlhttp.send();
return xmlhttp.response;
}
Use \1
instead of $1
.
\number Matches the contents of the group of the same number.
http://docs.python.org/library/re.html#regular-expression-syntax
The Why
java.util.logging has a root logger that defaults to Level.INFO
, and a ConsoleHandler attached to it that also defaults to Level.INFO
.
FINE
is lower than INFO
, so fine messages are not displayed by default.
Solution 1
Create a logger for your whole application, e.g. from your package name or use Logger.getGlobal()
, and hook your own ConsoleLogger to it.
Then either ask root logger to shut up (to avoid duplicate output of higher level messages), or ask your logger to not forward logs to root.
public static final Logger applog = Logger.getGlobal();
...
// Create and set handler
Handler systemOut = new ConsoleHandler();
systemOut.setLevel( Level.ALL );
applog.addHandler( systemOut );
applog.setLevel( Level.ALL );
// Prevent logs from processed by default Console handler.
applog.setUseParentHandlers( false ); // Solution 1
Logger.getLogger("").setLevel( Level.OFF ); // Solution 2
Solution 2
Alternatively, you may lower the root logger's bar.
You can set them by code:
Logger rootLog = Logger.getLogger("");
rootLog.setLevel( Level.FINE );
rootLog.getHandlers()[0].setLevel( Level.FINE ); // Default console handler
Or with logging configuration file, if you are using it:
.level = FINE
java.util.logging.ConsoleHandler.level = FINE
By lowering the global level, you may start seeing messages from core libraries, such as from some Swing or JavaFX components. In this case you may set a Filter on the root logger to filter out messages not from your program.
You need to use the select new
LINQ keyword to explicitly convert your tbcourse
entity into the custom type course
. Example of select new
:
var q = from o in db.Orders
where o.Products.ProductName.StartsWith("Asset") &&
o.PaymentApproved == true
select new { name = o.Contacts.FirstName + " " +
o.Contacts.LastName,
product = o.Products.ProductName,
version = o.Products.Version +
(o.Products.SubVersion * 0.1)
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.actionbar));
}
Put this code in your Activity's onCreate
method. This helped me.
Adding to @Vityata 's answer, below is the function I use to convert a row / column vector in a 1D array:
Function convertVecToArr(ByVal rng As Range) As Variant
'convert two dimension array into a one dimension array
Dim arr() As Variant, slicedArr() As Variant
arr = rng.value 'arr = rng works too (https://bettersolutions.com/excel/cells-ranges/vba-working-with-arrays.htm)
If UBound(arr, 1) > UBound(arr, 2) Then
slicedArr = Application.WorksheetFunction.Transpose(arr)
Else
slicedArr = Application.WorksheetFunction.index(arr, 1, 0) 'If you set row_num or column_num to 0 (zero), Index returns the array of values for the entire column or row, respectively._
'To use values returned as an array, enter the Index function as an array formula in a horizontal range of cells for a row,_
'and in a vertical range of cells for a column.
'https://usefulgyaan.wordpress.com/2013/06/12/vba-trick-of-the-week-slicing-an-array-without-loop-application-index/
End If
convertVecToArr = slicedArr
End Function
Another way:
Regex.Replace(urlString, "www.(.+)", "$1");
use enum its the easy and fastest
i will not recommend enum or tinyint(1) as bit(1) needs only 1 bit for storing boolean value while tinyint(1) needs 8 bits.
ref
You can use external library:
org.apache.commons.lang.ArrayUtils.remove(java.lang.Object[] array, int index)
It is in project Apache Commons Lang http://commons.apache.org/lang/
The ubuntu package name is qt5-default
, not qt
.
This question has been posted long time ago, but I found an alternative way to answer it. So I decided to share it here.
Firstly, one must know that: if two vectors are perpendicular, their dot product equals zero.
The normal vector (x',y')
is perpendicular to the line connecting (x1,y1)
and (x2,y2)
. This line has direction (x2-x1,y2-y1)
, or (dx,dy)
.
So,
(x',y').(dx,dy) = 0
x'.dx + y'.dy = 0
The are plenty of pairs (x',y') that satisfy the above equation. But the best pair that ALWAYS satisfies is either (dy,-dx)
or (-dy,dx)
Adding return false;
worked for me:
jQuery version:
$(document).on('click', '#video-id', function (e) {
var video = $(this).get(0);
if (video.paused === false) {
video.pause();
} else {
video.play();
}
return false;
});
Vanilla JavaScript version:
var v = document.getElementById('videoid');
v.addEventListener(
'play',
function() {
v.play();
},
false);
v.onclick = function() {
if (v.paused) {
v.play();
} else {
v.pause();
}
return false;
};
What is the problem? To use multiple controllers, just use multiple ngController directives:
<div class="widget" ng-controller="widgetController">
<p>Stuff here</p>
</div>
<div class="menu" ng-controller="menuController">
<p>Other stuff here</p>
</div>
You will need to have the controllers available in your application module, as usual.
The most basic way to do it could be as simple as declaring the controller functions like this:
function widgetController($scope) {
// stuff here
}
function menuController($scope) {
// stuff here
}
Add -storepass to keytool arguments.
keytool -storepasswd -storepass '' -keystore mykeystore.jks
But also notice that -list command does not always require a password. I could execute follow command in both cases: without password or with valid password
$JAVA_HOME/bin/keytool -list -keystore $JAVA_HOME/jre/lib/security/cacerts
.c_str()
returns a const char*
. If you need a mutable version, you will need to produce a copy yourself.
That's a difficult problem to solve since visually similar PDFs may have a wildly differing structure depending on how they were produced. In the worst case the library would need to basically act like an OCR. On the other hand, the PDF may contain sufficient structure and metadata for easy removal of tables and figures, which the library can be tailored to take advantage of.
I'm pretty sure there are no open source tools which solve your problem for a wide variety of PDFs, but I remember having heard of commercial software claiming to do exactly what you ask for. I'm sure you'll run into them while googling.
You can do it with using a FileOutputStream
and the writeTo
method.
ByteArrayOutputStream byteArrayOutputStream = getByteStreamMethod();
try(OutputStream outputStream = new FileOutputStream("thefilename")) {
byteArrayOutputStream.writeTo(outputStream);
}
Source: "Creating a file from ByteArrayOutputStream in Java." on Code Inventions
This makes a difference on Windows, at least. See that link for details.
Python's standard out is buffered (meaning that it collects some of the data "written" to standard out before it writes it to the terminal). Calling sys.stdout.flush()
forces it to "flush" the buffer, meaning that it will write everything in the buffer to the terminal, even if normally it would wait before doing so.
Here's some good information about (un)buffered I/O and why it's useful:
http://en.wikipedia.org/wiki/Data_buffer
Buffered vs unbuffered IO
What about just defining multiple patterns? They might come from a config file containing known patterns, hard coded it reads like:
List<SimpleDateFormat> knownPatterns = new ArrayList<SimpleDateFormat>();
knownPatterns.add(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"));
knownPatterns.add(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm.ss'Z'"));
knownPatterns.add(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"));
knownPatterns.add(new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss"));
knownPatterns.add(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"));
for (SimpleDateFormat pattern : knownPatterns) {
try {
// Take a try
return new Date(pattern.parse(candidate).getTime());
} catch (ParseException pe) {
// Loop on
}
}
System.err.println("No known Date format found: " + candidate);
return null;
b = a[a>threshold]
this should do
I tested as follows:
import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()
t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetime.datetime.now() - t0
t0 = datetime.datetime.now()
flt = np.array(filter(lambda x:x==0, lrg))
print datetime.datetime.now() - t0
I got
$ python test.py
0:00:00.028000
0:00:02.461000
http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays
Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with AND if appropriate,
$this->db->where_in()
ex : $this->db->where_in('id', array('1','2','3'));
Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with OR if appropriate
$this->db->or_where_in()
ex : $this->db->where_in('id', array('1','2','3'));
This is a bug in the Android Connector for M2E (m2e-android) that was recently fixed:
https://github.com/rgladwell/m2e-android/commit/2b490f900153cd34fff1cec47fe5aeffabe44d87
This fix has been merged and will be available with the next release. In the meantime you can test the new fix by installing from the following update site:
The issue is with this line
xlo.Worksheets(1).Cells(2, 2) = TextBox1.Text
You have the textbox defined at some other location which you are not using here. Excel is unable to find the textbox object in the current sheet while this textbox was defined in xlw.
Hence replace this with
xlo.Worksheets(1).Cells(2, 2) = worksheets("xlw").TextBox1.Text
Sounds like you want a view instead of altering actual table data.
Coalesce(NullIf(rtrim(Address.Country),''),'United States')
This will force your column to be null if it is actually an empty string (or blank string) and then the coalesce will have a null to work with.
Same issue here, I have Oracle JDK installed and my keystore was created using that, but in the jceks
format
keytool -importkeystore -destkeystore client.keystore \
-srckeystore redislabs_user.p12 -srcstoretype pkcs12 \
-deststoretype jceks -alias client-cert
I deleted the -deststoretype jceks
option and it worked fine :)
You could use RAISE_APPLICATION_ERROR like this:
DECLARE
ex_custom EXCEPTION;
BEGIN
RAISE ex_custom;
EXCEPTION
WHEN ex_custom THEN
RAISE_APPLICATION_ERROR(-20001,'My exception was raised');
END;
/
That will raise an exception that looks like:
ORA-20001: My exception was raised
The error number can be anything between -20001 and -20999.
Try connecting to a vpn, if possible. That was the reason I was facing problem. Tip: if you're using an ec2 machine, try rebooting it. This worked for me the other day :)
Download the JDK version of the JRE to the installed JRE's and use that instead.
In Eclipse Indigo, if you check the classpath tab on the run configuration for ant, you will see that it defaults to adding the tools.jar from the system. So if you launch Eclipse using Java7 and run an ant build using a separate JRE6 it generates an UnsupportedClassVersionError. When I added the JDK version Eclipse picked up the tools.jar from the JDK and my ant task ran successfully.
Starting from a byte array you can use the binary package to do the conversions.
For example if you want to read ints :
buf := bytes.NewBuffer(b) // b is []byte
myfirstint, err := binary.ReadVarint(buf)
anotherint, err := binary.ReadVarint(buf)
The same package allows the reading of unsigned int or floats, with the desired byte orders, using the general Read function.
I solved it by deleting WC_Lock record in the SQLite ".svn\wc.db" file lock record in the WC_LOCK table.
Just open "wc.db" file with SQLite editor and executed
delete from WC_LOCK
The solution was given in another link that I cannot find right now. But really quite a fix; without worrying about deleting all directories
I suggest using JavaScript's Array method filter()
to identify an element by value. It filters data by using a "function to test each element of the array. Return true to keep the element, false otherwise.."
The following function filters the data, returning data for which the callback returns true
, i.e. where data.code
equals the requested country code.
function getCountryByCode(code) {
return data.filter(
function(data){ return data.code == code }
);
}
var found = getCountryByCode('DZ');
See the demonstration below:
var data = [{_x000D_
"name": "Afghanistan",_x000D_
"code": "AF"_x000D_
}, {_x000D_
"name": "Åland Islands",_x000D_
"code": "AX"_x000D_
}, {_x000D_
"name": "Albania",_x000D_
"code": "AL"_x000D_
}, {_x000D_
"name": "Algeria",_x000D_
"code": "DZ"_x000D_
}];_x000D_
_x000D_
_x000D_
function getCountryByCode(code) {_x000D_
return data.filter(_x000D_
function(data) {_x000D_
return data.code == code_x000D_
}_x000D_
);_x000D_
}_x000D_
_x000D_
var found = getCountryByCode('DZ');_x000D_
_x000D_
document.getElementById('output').innerHTML = found[0].name;
_x000D_
<div id="output"></div>
_x000D_
Here is a guide by @CTS_AE on how to use NPM with standalone node.exe: https://stackoverflow.com/a/31148216/228508
You can use a plugin available here..
https://plugins.jquery.com/cookie/
and then to write a cookie do
$.cookie("test", 1);
to access the set cookie do
$.cookie("test");
select CustomerName,count(1) from Customers group by CustomerName having count(1) > 1
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.
You need to set the return value of setInterval
to a variable within the scope of the click handler, then use clearInterval()
like this:
var interval = null;
$(document).on('ready',function(){
interval = setInterval(updateDiv,3000);
});
function updateDiv(){
$.ajax({
url: 'getContent.php',
success: function(data){
$('.square').html(data);
},
error: function(){
clearInterval(interval); // stop the interval
$.playSound('oneday.wav');
$('.square').html('<span style="color:red">Connection problems</span>');
}
});
}
I encountered this error when inheriting from an abstract class and not implementing all of the pure virtual methods in my subclass.
list[:10]
will give you the first 10 elements of this list using slicing.
However, note, it's best not to use list
as a variable identifier as it's already used by Python: list()
To find out more about these type of operations you might find this tutorial on lists helpful and the link @DarenThomas provided Explain Python's slice notation - thanks Daren)
If a pipeline is too complicated to wrap in $(...)
, consider writing a function. Any local variables available at the time of definition will be accessible.
function getHash {
genhash --use-ssl -s $IP -p 443 --url $URL | grep MD5 | grep -c $MD5
}
hash=$(getHash)
http://www.gnu.org/software/bash/manual/bashref.html#Shell-Functions
Can do the following
PRINT dbo.[FunctionName] ( [Parameter/Argument] )
E.g.:
PRINT dbo.StringSplit('77,54')
Just found out a great plugin for this:
http://flexslider.woothemes.com/
Regards
This might not be what you want to hear, but I would recommend not focusing on narrow technologies, but on general programming and problem solving skills. Solid developers can learn whatever you want them to do quickly.
I, for instance, am not a Compact Framework guy, so I might fail your interview if you went that direction. But if I needed to use it I could do some research and jump right in.
Joel's book, Smart and Gets Things Done, has great advice for hiring devs and there are large juicy sections about the kinds of questions to ask. I highly recommend it.
The current windows 10 (Version 1803 (OS Build 17134.1)) has SSH built in. With that, just enable SSH from the Control Panel, Terminal & SNMP, be sure you are using an account in the Administrator's group, and you're all set.
Launch Powershell or CMD, enter ssh yourAccountName@diskstation
The first time it will cache off your certificate.
Further detailed explanations can be found on the synology docs page:
The flexbox grid should do what you want. You're not clear as to what limitation you ran into, so it's hard to address your specifics.
Here's a codepen with a working sample that generates your table with the first couple rows and a header: http://codepen.io/anon/pen/pjzKMZ
HTML
<html ng-app="ionicApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>Ionic Template</title>
<link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">
<script src="//code.ionicframework.com/nightly/js/ionic.bundle.js"></script>
</head>
<body ng-controller="MyCtrl as ctrl">
<ion-header-bar class="bar-stable">
<h1 class="title">Service Provider Details</h1>
</ion-header-bar>
<ion-content>
<div class="row header">
<div class="col">Utility Company Name</div>
<div class="col">Service Code</div>
<div class="col">Pay Limit</div>
<div class="col">Account Number to Use</div>
<div class="col"></div>
</div>
<div class="row" ng-repeat="data in ctrl.data">
<div class="col">{{data.name}}</div>
<div class="col">{{data.code}}</div>
<div class="col">LK {{data.limit}}</div>
<div class="col">{{data.account}}</div>
<div class="col"><button class="button" ng-click="ctrl.add($index)">Add</button></div>
</div>
</ion-content>
</body>
</html>
CSS
body {
cursor: url('http://ionicframework.com/img/finger.png'), auto;
}
.header .col {
background-color:lightgrey;
}
.col {
border: solid 1px grey;
border-bottom-style: none;
border-right-style: none;
}
.col:last-child {
border-right: solid 1px grey;
}
.row:last-child .col {
border-bottom: solid 1px grey;
}
Javascript
angular.module('ionicApp', ['ionic'])
.controller('MyCtrl', function($scope) {
var ctrl = this;
ctrl.add = add;
ctrl.data = [
{
name: "AiA",
code: "AI101",
limit: 25000,
account: "Life Insurance"
},
{
name: "Cargills",
code: "CF001",
limit: 30000,
account: "Food City"
}
]
////////
function add(index) {
window.alert("Added: " + index);
}
});
$time = strtotime('10:00');
$startTime = date("H:i", strtotime('-30 minutes', $time));
$endTime = date("H:i", strtotime('+30 minutes', $time));
Having looked at the documentation, I believe that the following is cleaner:
let version =
NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString")
as? String
Source: "Use of this method is preferred over other access methods because it returns the localized value of a key when one is available."
@gnarf answer is right . wanted to add more information .
Mozilla Bug Reference : https://bugzilla.mozilla.org/show_bug.cgi?id=627942
Terminate these steps if header is a case-insensitive match for one of the following headers:
Accept-Charset
Accept-Encoding
Access-Control-Request-Headers
Access-Control-Request-Method
Connection
Content-Length
Cookie
Cookie2
Date
DNT
Expect
Host
Keep-Alive
Origin
Referer
TE
Trailer
Transfer-Encoding
Upgrade
User-Agent
Via
Source : https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#dom-xmlhttprequest-setrequestheader
go to services and start the ones related to SQL
function printDiv() {
var divToPrint = document.getElementById('printArea');
newWin= window.open();
newWin.document.write(divToPrint.innerHTML);
newWin.location.reload();
newWin.focus();
newWin.print();
newWin.close();
}
Your @drawable/list_divide
should look like this:
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line">
<stroke
android:height="1dp"
android:color="#8F8F8F"
android:dashWidth="1dp"
android:dashGap="1dp" />
</shape>
In your version you provide an android:width="1dp"
, simply change it to an android:height="1dp"
and it should work!
You Could just use NSTimer to call a selector:
[NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(yourMethod:) userInfo:nil repeats:NO]
First open a console then cd to where you've downloaded your file like some-package.whl and use
pip install some-package.whl
Note: if pip.exe is not recognized, you may find it in the "Scripts" directory from where python has been installed. I have multiple Python installations, and needed to use the pip associated with Python 3 to install a version 3 wheel.
If pip is not installed, and you are using Windows: How to install pip on Windows?
This may help you!
$latlng='{"lat":29.5345741,"lng":75.0342196}';
$latlng=json_decode($latlng,TRUE); // array
echo "Lat=".$latlng['lat'];
echo '<br/>';
echo "Lng=".$latlng['lng'];
echo '<br/>';
$latlng2='{"lat":29.5345741,"lng":75.0342196}';
$latlng2=json_decode($latlng2); // object
echo "Lat=".$latlng2->lat;
echo '<br/>';
echo "Lng=".$latlng2->lng;
echo '<br/>';
Try this way:
select * from tab
where DateCol between DateAdd(DD,-7,GETDATE() ) and GETDATE()
You should assume it does something useful and call Dispose even if it does nothing in current .NET Framework incarnations. There's no guarantee it will stay that way in future versions leading to inefficient resource usage.
You can put a KeyPress
handler on your TextBoxes, and see which key was used.
To handle the text selection, put a handler on the GotFocus
event.
You may also want to consider how to (or if you need to) handle multi-line TextBoxes.
You can also use array_keys()
. Newbie friendly:
$keys = array_keys($arrayToWalk);
$arraySize = count($arrayToWalk);
for($i=0; $i < $arraySize; $i++) {
echo '<option value="' . $keys[$i] . '">' . $arrayToWalk[$keys[$i]] . '</option>';
}
Try the "-o StrictHostKeyChecking=no" option to ssh("-o" being the flag that tells ssh that your are going to use an option). This accepts any incoming RSA key from your ssh connection, even if the key is not in the "known host" list.
sshpass -p 'password' ssh -o StrictHostKeyChecking=no user@host 'command'
This is more a workaround than a real solution. You can create a new object test_data
with another column name:
left_join("names<-"(test_data, "name"), kantrowitz, by = "name")
name gender
1 john M
2 bill either
3 madison M
4 abby either
5 zzz <NA>
2018 edit: This answer is from 2011, before browsers had widely supported array filtering methods and arrow functions. Have a look at CAFxX's answer.
There is no "magic" way to check for something in an array without a loop. Even if you use some function, the function itself will use a loop. What you can do is break out of the loop as soon as you find what you're looking for to minimize computational time.
var found = false;
for(var i = 0; i < vendors.length; i++) {
if (vendors[i].Name == 'Magenic') {
found = true;
break;
}
}
this
points to the object in whose member function it is reffered, so it is optional.
I have the same issue and solved it by reading this post, while solving it, I hitted a problem: auth failed
.
And I finally solved it by using a ssh key
way to authorize myself. I found the EGit offical guide very useful and I configured the ssh
way successfully by refer to the Eclipse SSH Configuration
section in the link provided.
Hope it helps.
Your comparator is not transitive.
Let A
be the parent of B
, and B
be the parent of C
. Since A > B
and B > C
, then it must be the case that A > C
. However, if your comparator is invoked on A
and C
, it would return zero, meaning A == C
. This violates the contract and hence throws the exception.
It's rather nice of the library to detect this and let you know, rather than behave erratically.
One way to satisfy the transitivity requirement in compareParents()
is to traverse the getParent()
chain instead of only looking at the immediate ancestor.
If you want something beyond the ID column that's there in all lists, you're probably going to have to resort to an Event Receiver on the list that "calculates" what the value of your unique identified should be or using a custom field type that has the required logic embedded in this. Unfortunately, both of these options will require writing and deploying custom code to the server and deploying assemblies to the GAC, which can be frowned upon in environments where you don't have complete control over the servers.
If you don't need the unique identifier to show up immediately, you could probably generate it via a workflow (either with SharePoint Designer or a custom WF workflow built in Visual Studio).
Unfortunately, calculated columns, which seem like an obvious solution, won't work for this purpose because the ID is not yet assigned when the calculation is attempted. If you go in after the fact and edit the item, the calculation may achieve what you want, but on initial creation of a new item it will not be calculated correctly.
The problem with the Automation API solution is, that it required a reference to the Framework assembly UIAutomationProvider
as project/package dependency.
An alternative is to emulate the behaviour. In the following there is my extended solution which also condiders the MVVM-pattern with its bound commands - implemented as extension method:
public static class ButtonExtensions
{
/// <summary>
/// Performs a click on the button.<br/>
/// This is the WPF-equivalent of the Windows Forms method "<see cref="M:System.Windows.Forms.Button.PerformClick" />".
/// <para>This simulates the same behaviours as the button was clicked by the user by keyboard or mouse:<br />
/// 1. The raising the ClickEvent.<br />
/// 2.1. Checking that the bound command can be executed, calling <see cref="ICommand.CanExecute" />, if a command is bound.<br />
/// 2.2. If command can be executed, then the <see cref="ICommand.Execute(object)" /> will be called and the optional bound parameter is p
/// </para>
/// </summary>
/// <param name="sourceButton">The source button.</param>
/// <exception cref="ArgumentNullException">sourceButton</exception>
public static void PerformClick(this Button sourceButton)
{
// Check parameters
if (sourceButton == null)
throw new ArgumentNullException(nameof(sourceButton));
// 1.) Raise the Click-event
sourceButton.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent));
// 2.) Execute the command, if bound and can be executed
ICommand boundCommand = sourceButton.Command;
if (boundCommand != null)
{
object parameter = sourceButton.CommandParameter;
if (boundCommand.CanExecute(parameter) == true)
boundCommand.Execute(parameter);
}
}
}
For default browser,
<head>
select {
display: inline !important;
}
</head>
Or the Jquery solution after the link t Jquery library and your local/CDN materialize files
<script>
(function($){
$(function(){
// Plugin initialization
$('select').not('.disabled').formSelect();
});
})(jQuery); // end of jQuery name space
I really like this framework, but what on earth to have display:none...
Read the W3C spec. (this is CSS 2.1, find the appropriate version for your assumption of browsers)
edit: relevant paragraph follows:
In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-z0-9] and ISO 10646 characters U+00A1 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B\&W\?" or "B\26 W\3F".
edit 2: as @mipadi points out in Triptych's answer, there's this caveat, also in the same webpage:
In CSS, identifiers may begin with '-' (dash) or '_' (underscore). Keywords and property names beginning with '-' or '_' are reserved for vendor-specific extensions. Such vendor-specific extensions should have one of the following formats:
'-' + vendor identifier + '-' + meaningful name '_' + vendor identifier + '-' + meaningful name
Example(s):
For example, if XYZ organization added a property to describe the color of the border on the East side of the display, they might call it -xyz-border-east-color.
Other known examples:
-moz-box-sizing -moz-border-radius -wap-accesskey
An initial dash or underscore is guaranteed never to be used in a property or keyword by any current or future level of CSS. Thus typical CSS implementations may not recognize such properties and may ignore them according to the rules for handling parsing errors. However, because the initial dash or underscore is part of the grammar, CSS 2.1 implementers should always be able to use a CSS-conforming parser, whether or not they support any vendor-specific extensions.
Authors should avoid vendor-specific extensions
Most simple solution
Activator.CreateInstance<T>()
You already have the right answer. And if you want to make more complicated and interesting operations between Lists (collections) use apache commons collections (CollectionUtils) It allows you to make conjuction/disjunction, find intersection, check if one collection is a subset of another and other nice things.
As suggested in a similar question, use JavaScript to call window.open
with the target
argument set to _system
, as per the InAppBrowser documentation:
<a href="#" onclick="window.open('http://www.kidzout.com', '_system'); return false;">www.kidzout.com</a>
This should work, though a better and more flexible solution would be to intercept all links' click
events, and call window.open
with arguments read from the link's attributes.
Remember you must install the InAppBrowser plugin for this to work:
cordova plugin add cordova-plugin-inappbrowser
create a database schema in SQL Server 2008
1. Navigate to Security > Schemas
2. Right click on Schemas and select New Schema
3. Complete the details in the General tab for the new schema. Like, the schema name is "MySchema" and the schema owner is "Admin".
4. Add users to the schema as required and set their permissions:
5. Add any extended properties (via the Extended Properties tab)
6. Click OK.
Add a Table to the New Schema "MySchema"
1. In Object Explorer, right click on the table name and select "Design":
2. Changing database schema for a table in SQL Server Management Studio
3. From Design view, press F4 to display the Properties window.
4. From the Properties window, change the schema to the desired schema:
5. Close Design View by right clicking the tab and selecting "Close":
6. Closing Design View
7. Click "OK" when prompted to save
8. Your table has now been transferred to the "MySchema" schema.
Refresh the Object Browser view To confirm the changes
Done
This is useful to check the status of autocommit;
select @@autocommit;
Since JavaFX 8u60
you can use(assuming tableView
is an instance of TableView class):
tableView.refresh();
From the documentation:
Calling refresh() forces the TableView control to recreate and repopulate the cells necessary to populate the visual bounds of the control. In other words, this forces the TableView to update what it is showing to the user. This is useful in cases where the underlying data source has changed in a way that is not observed by the TableView itself.
Update Android emulator alone from SDK tool
The database uses the same lock for all #temp tables so if you are using a lot you will get deadlock problems. It is better to use @ table variables for concurrency.
calling the method is like this
[className methodName]
however if you want to call the method in the same class you can use self
[self methodName]
all the above is because your method was not taking any parameters
however if your method takes parameters you will need to do it like this
[self methodName:Parameter]
marc_s's answer is good but it has a flaw if the primary key column(s) appear in other indexes in that those columns will appear more than once. e.g.
Demo:
create table dbo.DummyTable
(
id int not null identity(0,1) primary key,
Msg varchar(80) null
);
create index NC_DummyTable_id ON DummyTable(id);
Here's my stored procedure to solve problem:
create or alter procedure dbo.GetTableColumns
(
@schemaname nvarchar(128),
@tablename nvarchar(128)
)
AS
BEGIN
SET NOCOUNT ON;
with ctePKCols as
(
select
i.object_id,
ic.column_id
from
sys.indexes i
join sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
where
i.is_primary_key = 1
)
SELECT
c.name AS column_name,
t.name AS typename,
c.max_length AS MaxLength,
c.precision,
c.scale,
c.is_nullable,
is_primary_key = CASE WHEN ct.column_id IS NOT NULL THEN 1 ELSE 0 END
FROM
sys.columns c
JOIN sys.types t ON t.user_type_id = c.user_type_id
LEFT JOIN ctePKCols ct ON ct.column_id = c.column_id AND ct.object_id = c.object_id
WHERE
c.object_ID = OBJECT_ID(quotename(@schemaname) + '.' + quotename(@tablename))
END
GO
exec dbo.GetTableColumns 'dbo', 'DummyTable'
function getExample() {
var retA, retB;
return promiseA(…).then(function(resultA) {
retA = resultA;
// Some processing
return promiseB(…);
}).then(function(resultB) {
// More processing
//retA is value of promiseA
return // How do I gain access to resultA here?
});
}
easy way :D
Add bellow line in build.gradle:
compile 'com.commit451:PhotoView:1.2.4'
or
compile 'com.github.chrisbanes:PhotoView:1.3.0'
In Java file:
PhotoViewAttacher photoAttacher;
photoAttacher= new PhotoViewAttacher(Your_Image_View);
photoAttacher.update();
You should not make an ajax call, just put the src of the img element as the url of the image.
This would be useful if you use GET instead of POST
<script type="text/javascript" >
$(document).ready( function() {
$('.div_imagetranscrits').html('<img src="get_image_probes_via_ajax.pl?id_project=xxx" />')
} );
</script>
If you want to POST to that image and do it the way you do (trying to parse the contents of the image on the client side, you could try something like this: http://en.wikipedia.org/wiki/Data_URI_scheme
You'll need to encode the data
to base64, then you could put data:[<MIME-type>][;charset=<encoding>][;base64],<data>
into the img src
as example:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot img" />
To encode to base64:
For this case to import Bar.py into Foo.py, first I'd turn these folders into Python packages like so:
dirFoo\
__init__.py
Foo.py
dirBar\
__init__.py
Bar.py
Then I would do it like this in Foo.py:
from .dirBar import Bar
If I wanted the namespacing to look like Bar.whatever, or
from . import dirBar
If I wanted the namespacing dirBar.Bar.whatever. This second case is useful if you have more modules under the dirBar package.
Can try this too, almost similar previous answers.
d = {'filename': ['M66_MI_NSRh35d32kpoints.dat', 'F71_sMI_DMRI51d.dat', 'F62_sMI_St22d7.dat', 'F41_Car_HOC498d.dat', 'F78_MI_547d.dat'], 'alpha1': [0.8016, 0.0, 1.721, 1.167, 1.897], 'alpha2': [0.9283, 0.0, 3.833, 2.809, 5.459], 'gamma1': [1.0, np.nan, 0.23748000000000002, 0.36419, 0.095319], 'gamma2': [0.074804, 0.0, 0.15, 0.3, np.nan], 'chi2min': [39.855990000000006, 1e+25, 10.91832, 7.966335000000001, 25.93468]}
df = pd.DataFrame(d).set_index('filename')
Count of null values in each column.
df.isnull().sum()
df.isnull().any(axis=1)
You aren't really using the doGet() method. When you're opening the page, it issues a GET request, not POST.
Try changing doPost() to service() instead... then you're using the same method to handle GET and POST requests.
...
first I had to delete my registry by using npm config delete registry
and register new value using npm config set registry "http://registry.npmjs.org"
If that's so bothering, you could try to switch to windows explorer alternative like freecommander which has a toolbar button for that purpose.
You can use jQuery load method to get the contents and insert into an element.
Try this:
$(document).ready(function() {
$("#lesen").click(function() {
$(".text").load("helloworld.txt");
});
});
You, can also add a call back to execute something once the load process is complete
e.g:
$(document).ready(function() {
$("#lesen").click(function() {
$(".text").load("helloworld.txt", function(){
alert("Done Loading");
});
});
});
You could create a basket service. And generally in JS you use objects instead of lots of parameters.
Here's an example: http://jsfiddle.net/2MbZY/
var app = angular.module('myApp', []);
app.factory('basket', function() {
var items = [];
var myBasketService = {};
myBasketService.addItem = function(item) {
items.push(item);
};
myBasketService.removeItem = function(item) {
var index = items.indexOf(item);
items.splice(index, 1);
};
myBasketService.items = function() {
return items;
};
return myBasketService;
});
function MyCtrl($scope, basket) {
$scope.newItem = {};
$scope.basket = basket;
}
You need to use this function.
JSON.parse(yourJsonString);
And it will return the object / array that was contained within the string.
As found there : Detect Click into Iframe using JavaScript
=> We can use iframeTracker-jquery :
$('.carousel-inner .item').each(function(e) {
var item = this;
var iFrame = $(item).find('iframe');
if (iFrame.length > 0) {
iFrame.iframeTracker({
blurCallback: function(){
// Do something when iFrame is clicked (like firing an XHR request)
onItemClick.bind(item)(); // calling regular click with right context
console.log('IFrameClick => OK');
}
});
console.log('IFrameTrackingRegistred => OK');
}
})
For applications such as games and embedded systems where memory and performance are both critical, float is usually the numeric type of choice as it is faster and half the size of a double. Integers used to be the weapon of choice, but floating point performance has overtaken integer in modern processors. Decimal is right out!
I wrote a CustomViewPager
with a swiping control:
public class ScrollableViewPager extends ViewPager {
private boolean canScroll = true;
public ScrollableViewPager(Context context) {
super(context);
}
public ScrollableViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setCanScroll(boolean canScroll) {
this.canScroll = canScroll;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
return canScroll && super.onTouchEvent(ev);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return canScroll && super.onInterceptTouchEvent(ev);
}
}
If you set canScroll
to true
, this ViewPager
can be swiping with finger, false
on the contrary.
I use this in my project, and it works great until now.
By using EntityManager, code is no longer tightly coupled with hibernate. But for this, in usage we should use :
javax.persistence.EntityManager
instead of
org.hibernate.ejb.HibernateEntityManager
Similarly, for EntityManagerFactory, use javax interface. That way, the code is loosely coupled. If there is a better JPA 2 implementation than hibernate, switching would be easy. In extreme case, we could type cast to HibernateEntityManager.
try below:
var temp_datetime_obj = new Date();
collection.find({
start_date:{
$gte: new Date(temp_datetime_obj.toISOString())
}
}).toArray(function(err, items) {
/* you can console.log here */
});
Go to your HTTP bindings in IIS (select your website, then on the right click on Bindings...). Delete your SSL and your HTTP binding. Re-Add them.
This usually fixes this for me.
http://pchart.sourceforge.net/ looks very good and it's free.
You can do injection on Directives, and it looks just like it does everywhere else.
app.directive('changeIt', ['myData', function(myData){
return {
restrict: 'C',
link: function (scope, element, attrs) {
scope.name = myData.name;
}
}
}]);
From the vuejs/vetur issue page https://github.com/vuejs/vetur/issues/986# This solution worked for me.
In VSCodes settings.json
file add this entry
"vetur.format.defaultFormatterOptions": {
"prettier": {
"singleQuote": true
}
},
JQuery UI already has this, in my example below I included a maxchar attribute to focus on the next focus-able element (input, select, textarea, button and object) if i typed in the max number of characters
HTML:
text 1 <input type="text" value="" id="txt1" maxchar="5" /><br />
text 2 <input type="text" value="" id="txt2" maxchar="5" /><br />
checkbox 1 <input type="checkbox" value="" id="chk1" /><br />
checkbox 2 <input type="checkbox" value="" id="chk2" /><br />
dropdown 1 <select id="dd1" >
<option value="1">1</option>
<option value="1">2</option>
</select><br />
dropdown 2 <select id="dd2">
<option value="1">1</option>
<option value="1">2</option>
</select>
Javascript:
$(function() {
var focusables = $(":focusable");
focusables.keyup(function(e) {
var maxchar = false;
if ($(this).attr("maxchar")) {
if ($(this).val().length >= $(this).attr("maxchar"))
maxchar = true;
}
if (e.keyCode == 13 || maxchar) {
var current = focusables.index(this),
next = focusables.eq(current+1).length ? focusables.eq(current+1) : focusables.eq(0);
next.focus();
}
});
});
To understand this let's consider an example where we have a class Mammal
which defines readAndGet
method which is reading some file, doing some operation on it and returning an instance of class Mammal
.
class Mammal {
public Mammal readAndGet() throws IOException {//read file and return Mammal`s object}
}
Class Human
extends class Mammal
and overrides readAndGet
method to return the instance of Human
instead of the instance of Mammal
.
class Human extends Mammal {
@Override
public Human readAndGet() throws FileNotFoundException {//read file and return Human object}
}
To call readAndGet
we will need to handle IOException
because its a checked exception and mammal's readAndMethod
is throwing it.
Mammal mammal = new Human();
try {
Mammal obj = mammal.readAndGet();
} catch (IOException ex) {..}
And we know that for compiler mammal.readAndGet()
is getting called from the object of class Mammal
but at, runtime JVM will resolve mammal.readAndGet()
method call to a call from class Human
because mammal
is holding new Human()
.
Method readAndMethod
from Mammal
is throwing IOException
and because it is a checked exception compiler will force us to catch it whenever we call readAndGet
on mammal
Now suppose readAndGet
in Human
is throwing any other checked exception e.g. Exception and we know readAndGet
will get called from the instance of Human
because mammal
is holding new Human()
.
Because for compiler the method is getting called from Mammal
, so the compiler will force us to handle only IOException
but at runtime we know method will be throwing Exception
exception which is not getting handled and our code will break if the method throws the exception.
That's why it is prevented at the compiler level itself and we are not allowed to throw any new or broader checked exception because it will not be handled by JVM at the end.
There are other rules as well which we need to follow while overriding the methods and you can read more on Why We Should Follow Method Overriding Rules to know the reasons.
Contrary to @Andre Luus, setting Height="Auto"
will not make the TextBox
stretch. The solution I found was to set VerticalAlignment="Stretch"
The latest solution for passing data between fragments can be implemented by using android architectural components such as ViewModel and LiveData. With this solution, you don't need to define interface for communication and can get the advantages of using viewmodel like data survival due to configuration changes.
In this solution, the fragments involved in the communication share the same viewmodel object which is tied to their activity lifecycle. The view model object contains livedata object. One fragment sets data to be passed on livedata object and second fragment observers livedata changes and received the data.
Here is the complete example http://www.zoftino.com/passing-data-between-android-fragments-using-viewmodel
$('#select_id option:eq(0)').prop('selected', 'selected');
its good
its pretty simple
Date someDate = new DateTime();
string timeOfDay = someDate.ToString("hh:mm tt");
// hh - shows hour and mm - shows minute - tt - shows AM or PM
Delete the table and remove its record from migration table.
After that you just run migration again:
php artisan migrate
Dear All with all respict to answers up there there are case gives this error when web.config value is
<httpCookies httpOnlyCookies="true" requireSSL="true"/>
and link is http not https
If your compiler supports C++11 standard, there is a constructor inheritance using using
(pun intended). For more see Wikipedia C++11 article. You write:
class A
{
public:
explicit A(int x) {}
};
class B: public A
{
using A::A;
};
This is all or nothing - you cannot inherit only some constructors, if you write this, you inherit all of them. To inherit only selected ones you need to write the individual constructors manually and call the base constructor as needed from them.
Historically constructors could not be inherited in the C++03 standard. You needed to inherit them manually one by one by calling base implementation on your own.
The new urllib3 library has a nice documentation here
In order to get your desired result you shuld follow that:
Import urllib3
from bs4 import BeautifulSoup
url = 'http://www.thefamouspeople.com/singers.php'
http = urllib3.PoolManager()
response = http.request('GET', url)
soup = BeautifulSoup(response.data.decode('utf-8'))
The "decode utf-8" part is optional. It worked without it when i tried, but i posted the option anyway.
Source: User Guide
For example:
you can use:
df %>% filter(!is.na(a))
to remove the NA in column a.
Have you tried exit(0)
?
Alternatively, [[NSThread mainThread] exit]
, although I have not tried that it seems like the more appropriate solution.
What worked for me in Xcode 11 was going to General -> Frameworks, Libraries, and Embedded Content and changing the "Embed" option for the framework in question to "Embed & Sign"
Global variables are not extern
nor static
by default on C and C++.
When you declare a variable as static
, you are restricting it to the current source file. If you declare it as extern
, you are saying that the variable exists, but are defined somewhere else, and if you don't have it defined elsewhere (without the extern
keyword) you will get a link error (symbol not found).
Your code will break when you have more source files including that header, on link time you will have multiple references to varGlobal
. If you declare it as static
, then it will work with multiple sources (I mean, it will compile and link), but each source will have its own varGlobal
.
What you can do in C++, that you can't in C, is to declare the variable as const
on the header, like this:
const int varGlobal = 7;
And include in multiple sources, without breaking things at link time. The idea is to replace the old C style #define
for constants.
If you need a global variable visible on multiple sources and not const
, declare it as extern
on the header, and then define it, this time without the extern keyword, on a source file:
Header included by multiple files:
extern int varGlobal;
In one of your source files:
int varGlobal = 7;
I had this error with Firebase Admin, the solution was configure the Firebase Admin correctly following this link
I think I tried everything mentioned here, and it still didn't work. Turns out it didn't recognize my domain login to the server as being in the Administrators group because it was implicit through my membership in another group ( Developers ) which is a member of the Administrators group.
I added my individual domain\login to the Administrators group explicitly, logged off and then logged back on to the box, and IE admitted me to the Report Manager homepage without requiring me to run IE as administrator.
I hope it helps!
Here is a way to check is virtualization is enabled or disabled by the firmware as suggested by this link in parallels.com.
How to check that Intel VT-x is supported in CPU:
Open Terminal application from Application/Utilities
Copy/paste command bellow
sysctl -a | grep machdep.cpu.features
Mac:~ user$ sysctl -a | grep machdep.cpu.features
kern.exec: unknown type returned
machdep.cpu.features: FPU VME DE PSE TSC MSR PAE MCE CX8 APIC SEP MTRR PGE MCA CMOV PAT CLFSH DS ACPI MMX FXSR SSE SSE2 SS HTT TM SSE3 MON VMX EST TM2 TPR PDCM
If you see VMX entry then CPU supports Intel VT-x feature, but it still may be disabled.
Refer to this link on Apple.com to enable hardware support for virtualization:
You can try this. Override the OnPaint event of the TextBox.
protected override void OnPaint(PaintEventArgs e)
{
SolidBrush drawBrush = new SolidBrush(ForeColor); //Use the ForeColor property
// Draw string to screen.
e.Graphics.DrawString(Text, Font, drawBrush, 0f,0f); //Use the Font property
}
set the ControlStyles to "UserPaint"
public MyTextBox()//constructor
{
// This call is required by the Windows.Forms Form Designer.
this.SetStyle(ControlStyles.UserPaint,true);
InitializeComponent();
// TODO: Add any initialization after the InitForm call
}
Or you can try this hack
In Enter event set the focus
int index=this.Controls.IndexOf(this.textBox1);
this.Controls[index-1].Focus();
So your control will not focussed and behave like disabled.
Also working in privateStatic.cpp file :
#include <iostream>
using namespace std;
class A
{
private:
static int v;
};
int A::v = 10; // possible initializing
int main()
{
A a;
//cout << A::v << endl; // no access because of private scope
return 0;
}
// g++ privateStatic.cpp -o privateStatic && ./privateStatic
Unfortunately MySQL does not support SQL check constraints. You can define them in your DDL query for compatibility reasons but they are just ignored.
There is a simple alternative
You can create BEFORE INSERT
and BEFORE UPDATE
triggers which either cause an error or set the field to its default value when the requirements of the data are not met.
Example for BEFORE INSERT
working after MySQL 5.5
DELIMITER $$
CREATE TRIGGER `test_before_insert` BEFORE INSERT ON `Test`
FOR EACH ROW
BEGIN
IF CHAR_LENGTH( NEW.ID ) < 4 THEN
SIGNAL SQLSTATE '12345'
SET MESSAGE_TEXT := 'check constraint on Test.ID failed';
END IF;
END$$
DELIMITER ;
Prior to MySQL 5.5 you had to cause an error, e.g. call a undefined procedure.
In both cases this causes an implicit transaction rollback. MySQL does not allow the ROLLBACK statement itself within procedures and triggers.
If you don't want to rollback the transaction ( INSERT / UPDATE should pass even with a failed "check constraint" you can overwrite the value using SET NEW.ID = NULL
which will set the id to the fields default value, doesn't really make sense for an id tho
Edit: Removed the stray quote.
Concerning the :=
operator:
Unlike
=
, the:=
operator is never interpreted as a comparison operator. This means you can use:=
in any valid SQL statement (not just in SET statements) to assign a value to a variable.
https://dev.mysql.com/doc/refman/5.6/en/assignment-operators.html
Concerning backtick identifier quotes:
The identifier quote character is the backtick (“`”)
If the ANSI_QUOTES SQL mode is enabled, it is also permissible to quote identifiers within double quotation marks
If elements are in tree order, as shown in your example, you can use something like the following Python example:
delimiter = '.'
stack = []
for item in items:
while stack and not item.startswith(stack[-1]+delimiter):
print "</div>"
stack.pop()
print "<div>"
print item
stack.append(item)
What this does is maintain a stack representing the current position in the tree. For each element in the table, it pops stack elements (closing the matching divs) until it finds the parent of the current item. Then it outputs the start of that node and pushes it to the stack.
If you want to output the tree using indenting rather than nested elements, you can simply skip the print statements to print the divs, and print a number of spaces equal to some multiple of the size of the stack before each item. For example, in Python:
print " " * len(stack)
You could also easily use this method to construct a set of nested lists or dictionaries.
Edit: I see from your clarification that the names were not intended to be node paths. That suggests an alternate approach:
idx = {}
idx[0] = []
for node in results:
child_list = []
idx[node.Id] = child_list
idx[node.ParentId].append((node, child_list))
This constructs a tree of arrays of tuples(!). idx[0] represents the root(s) of the tree. Each element in an array is a 2-tuple consisting of the node itself and a list of all its children. Once constructed, you can hold on to idx[0] and discard idx, unless you want to access nodes by their ID.
To install Python 2.7.2 use this script - https://github.com/bngsudheer/bangadmin/blob/master/linux/centos/6/x86_64/build-python-27.sh
It also makes sure you get sqlite and readline support.
By adb shell input keyevent
, either an event_code
or a string
will be sent to the device.
usage: input [text|keyevent]
input text <string>
input keyevent <event_code>
Some possible values for event_code
are:
0 --> "KEYCODE_UNKNOWN"
1 --> "KEYCODE_MENU"
2 --> "KEYCODE_SOFT_RIGHT"
3 --> "KEYCODE_HOME"
4 --> "KEYCODE_BACK"
5 --> "KEYCODE_CALL"
6 --> "KEYCODE_ENDCALL"
7 --> "KEYCODE_0"
8 --> "KEYCODE_1"
9 --> "KEYCODE_2"
10 --> "KEYCODE_3"
11 --> "KEYCODE_4"
12 --> "KEYCODE_5"
13 --> "KEYCODE_6"
14 --> "KEYCODE_7"
15 --> "KEYCODE_8"
16 --> "KEYCODE_9"
17 --> "KEYCODE_STAR"
18 --> "KEYCODE_POUND"
19 --> "KEYCODE_DPAD_UP"
20 --> "KEYCODE_DPAD_DOWN"
21 --> "KEYCODE_DPAD_LEFT"
22 --> "KEYCODE_DPAD_RIGHT"
23 --> "KEYCODE_DPAD_CENTER"
24 --> "KEYCODE_VOLUME_UP"
25 --> "KEYCODE_VOLUME_DOWN"
26 --> "KEYCODE_POWER"
27 --> "KEYCODE_CAMERA"
28 --> "KEYCODE_CLEAR"
29 --> "KEYCODE_A"
30 --> "KEYCODE_B"
31 --> "KEYCODE_C"
32 --> "KEYCODE_D"
33 --> "KEYCODE_E"
34 --> "KEYCODE_F"
35 --> "KEYCODE_G"
36 --> "KEYCODE_H"
37 --> "KEYCODE_I"
38 --> "KEYCODE_J"
39 --> "KEYCODE_K"
40 --> "KEYCODE_L"
41 --> "KEYCODE_M"
42 --> "KEYCODE_N"
43 --> "KEYCODE_O"
44 --> "KEYCODE_P"
45 --> "KEYCODE_Q"
46 --> "KEYCODE_R"
47 --> "KEYCODE_S"
48 --> "KEYCODE_T"
49 --> "KEYCODE_U"
50 --> "KEYCODE_V"
51 --> "KEYCODE_W"
52 --> "KEYCODE_X"
53 --> "KEYCODE_Y"
54 --> "KEYCODE_Z"
55 --> "KEYCODE_COMMA"
56 --> "KEYCODE_PERIOD"
57 --> "KEYCODE_ALT_LEFT"
58 --> "KEYCODE_ALT_RIGHT"
59 --> "KEYCODE_SHIFT_LEFT"
60 --> "KEYCODE_SHIFT_RIGHT"
61 --> "KEYCODE_TAB"
62 --> "KEYCODE_SPACE"
63 --> "KEYCODE_SYM"
64 --> "KEYCODE_EXPLORER"
65 --> "KEYCODE_ENVELOPE"
66 --> "KEYCODE_ENTER"
67 --> "KEYCODE_DEL"
68 --> "KEYCODE_GRAVE"
69 --> "KEYCODE_MINUS"
70 --> "KEYCODE_EQUALS"
71 --> "KEYCODE_LEFT_BRACKET"
72 --> "KEYCODE_RIGHT_BRACKET"
73 --> "KEYCODE_BACKSLASH"
74 --> "KEYCODE_SEMICOLON"
75 --> "KEYCODE_APOSTROPHE"
76 --> "KEYCODE_SLASH"
77 --> "KEYCODE_AT"
78 --> "KEYCODE_NUM"
79 --> "KEYCODE_HEADSETHOOK"
80 --> "KEYCODE_FOCUS"
81 --> "KEYCODE_PLUS"
82 --> "KEYCODE_MENU"
83 --> "KEYCODE_NOTIFICATION"
84 --> "KEYCODE_SEARCH"
85 --> "TAG_LAST_KEYCODE"
The sendevent
utility sends touch or keyboard events, as well as other events for simulating the hardware events. Refer to this article for details: Android, low level shell click on screen.
ssh-keygen -f private.pem -y > public.pub
Fnd the answer.
I have use some styles inorder to achive this.
<span
class="pseudolink"
onclick="location='https://jsfiddle.net/'">
Go TO URL
</span>
.pseudolink {
color:blue;
text-decoration:underline;
cursor:pointer;
}
Just in case you have pre-stored the values in an array, you can call them in the following format:
for i in range(0,n):
print arr[i],