You can add the src
folder to build path by:
- Select Java perspective.
- Right click on
src
folder. - Select Build Path > Use a source folder.
And you are done. Hope this help.
EDIT: Refer to the Eclipse documentation
The getimagesize() should be the most definite way of working out whether the file is an image:
if(@is_array(getimagesize($mediapath))){
$image = true;
} else {
$image = false;
}
because this is a sample getimagesize() output:
Array (
[0] => 800
[1] => 450
[2] => 2
[3] => width="800" height="450"
[bits] => 8
[channels] => 3
[mime] => image/jpeg)
This turns out to be a pretty deep area of theory, but the basic outline is simple.
Essentially, a hash function is just a function that takes things from one space (say strings of arbitrary length) and maps them to a space useful for indexing (unsigned integers, say).
If you only have a small space of things to hash, you might get away with just interpreting those things as integers, and you're done (e.g. 4 byte strings)
Usually, though, you've got a much larger space. If the space of things you allow as keys is bigger than the space of things you are using to index (your uint32's or whatever) then you can't possibly have a unique value for each one. When two or more things hash to the same result, you'll have to handle the redundancy in an appropriate way (this is usually referred to as a collision, and how you handle it or don't will depend a bit on what you are using the hash for).
This implies you want it to be unlikely to have the same result, and you probably also would really like the hash function to be fast.
Balancing these two properties (and a few others) has kept many people busy!
In practice you usually should be able to find a function that is known to work well for your application and use that.
Now to make this work as a hashtable: Imagine you didn't care about memory usage. Then you can create an array as long as your indexing set (all uint32's, for example). As you add something to the table, you hash it's key and look at the array at that index. If there is nothing there, you put your value there. If there is already something there, you add this new entry to a list of things at that address, along with enough information (your original key, or something clever) to find which entry actually belongs to which key.
So as you go a long, every entry in your hashtable (the array) is either empty, or contains one entry, or a list of entries. Retrieving is a simple as indexing into the array, and either returning the value, or walking the list of values and returning the right one.
Of course in practice you typically can't do this, it wastes too much memory. So you do everything based on a sparse array (where the only entries are the ones you actually use, everything else is implicitly null).
There are lots of schemes and tricks to make this work better, but that's the basics.
You can also use query
which is very readable in my opinion and straightforward to use:
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [10, 20, 50, 80], 'C': [6, 7, 8, 9]})
df = df.set_index(['A', 'B'])
C
A B
1 10 6
2 20 7
3 50 8
4 80 9
For what you had in mind you can now simply do:
df.query('A == 1')
C
A B
1 10 6
You can also have more complex queries using and
df.query('A >= 1 and B >= 50')
C
A B
3 50 8
4 80 9
and or
df.query('A == 1 or B >= 50')
C
A B
1 10 6
3 50 8
4 80 9
You can also query on different index levels, e.g.
df.query('A == 1 or C >= 8')
will return
C
A B
1 10 6
3 50 8
4 80 9
If you want to use variables inside your query, you can use @
:
b_threshold = 20
c_threshold = 8
df.query('B >= @b_threshold and C <= @c_threshold')
C
A B
2 20 7
3 50 8
Long story short: Don't use FileInputStream as a parameter or variable type. Use the abstract base class, in this case InputStream instead.
Open IIS manager, select Application Pools, select the application pool you are using, click on Advanced Settings in the right-hand menu. Under General, set "Enable 32-Bit Applications" to "True".
Note that there are things that happen between the calls to onStart() and onResume(). Namely, onNewIntent(), which I've painfully found out.
If you are using the SINGLE_TOP flag, and you send some data to your activity, using intent extras, you will be able to access it only in onNewIntent(), which is called after onStart() and before onResume(). So usually, you will take the new (maybe only modified) data from the extras and set it to some class members, or use setIntent() to set the new intent as the original activity intent and process the data in onResume().
This is a old question, and the OP seems to mix C++ and C in his intends/examples. In C, when you pass a array to a function, it's decayed to pointer. So, there is no way to pass the array size except by using a second argument in your function that stores the array size:
void func(int A[])
// should be instead: void func(int * A, const size_t elemCountInA)
They are very few cases, where you don't need this, like when you're using multidimensional arrays:
void func(int A[3][whatever here]) // That's almost as if read "int* A[3]"
Using the array notation in a function signature is still useful, for the developer, as it might be an help to tell how many elements your functions expects. For example:
void vec_add(float out[3], float in0[3], float in1[3])
is easier to understand than this one (although, nothing prevent accessing the 4th element in the function in both functions):
void vec_add(float * out, float * in0, float * in1)
If you were to use C++, then you can actually capture the array size and get what you expect:
template <size_t N>
void vec_add(float (&out)[N], float (&in0)[N], float (&in1)[N])
{
for (size_t i = 0; i < N; i++)
out[i] = in0[i] + in1[i];
}
In that case, the compiler will ensure that you're not adding a 4D vector with a 2D vector (which is not possible in C without passing the dimension of each dimension as arguments of the function). There will be as many instance of the vec_add function as the number of dimensions used for your vectors.
Creating firewall rules
Please review the firewall rule components [1] if you are unfamiliar with firewall rules in GCP. Firewall rules are defined at the network level, and only apply to the network where they are created; however, the name you choose for each of them must be unique to the project.
For Cloud Console:
Specify the Targets of the rule.
For an ingress rule, specify the Source filter:
For an egress rule, specify the Destination filter:
Define the Protocols and ports to which the rule will apply:
Select Allow all or Deny all, depending on the action, to have the rule apply to all protocols and ports.
Define specific protocols and ports:
(Optional) You can create the firewall rule but not enforce it by setting its enforcement state to disabled. Click Disable rule, then select Disabled.
(Optional) You can enable firewall rules logging:
Click Create.
Link: [1] https://cloud.google.com/vpc/docs/firewalls#firewall_rule_components
I had an issue with the parseActivityForResult arguments. I got this to work:
package JMA.BarCodeScanner;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class JMABarcodeScannerActivity extends Activity {
Button captureButton;
TextView tvContents;
TextView tvFormat;
Activity activity;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
activity = this;
captureButton = (Button)findViewById(R.id.capture);
captureButton.setOnClickListener(listener);
tvContents = (TextView)findViewById(R.id.tvContents);
tvFormat = (TextView)findViewById(R.id.tvFormat);
}
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
switch (requestCode)
{
case IntentIntegrator.REQUEST_CODE:
if (resultCode == Activity.RESULT_OK)
{
IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (intentResult != null)
{
String contents = intentResult.getContents();
String format = intentResult.getFormatName();
tvContents.setText(contents.toString());
tvFormat.setText(format.toString());
//this.elemQuery.setText(contents);
//this.resume = false;
Log.d("SEARCH_EAN", "OK, EAN: " + contents + ", FORMAT: " + format);
} else {
Log.e("SEARCH_EAN", "IntentResult je NULL!");
}
}
else if (resultCode == Activity.RESULT_CANCELED) {
Log.e("SEARCH_EAN", "CANCEL");
}
}
}
private View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.initiateScan();
}
};
}
Latyout for Activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/capture"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Take a Picture"/>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tvContents"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tvFormat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
@GianCarlo: You can try calling System property user.dir that will give you root of your java project and then do append this path to your relative path for example:
String root = System.getProperty("user.dir");
String filepath = "/path/to/yourfile.txt"; // in case of Windows: "\\path \\to\\yourfile.txt
String abspath = root+filepath;
// using above path read your file into byte []
File file = new File(abspath);
FileInputStream fis = new FileInputStream(file);
byte []filebytes = new byte[(int)file.length()];
fis.read(filebytes);
Use which(mydata_2$height_chad1 == 2585)
Short example
df <- data.frame(x = c(1,1,2,3,4,5,6,3),
y = c(5,4,6,7,8,3,2,4))
df
x y
1 1 5
2 1 4
3 2 6
4 3 7
5 4 8
6 5 3
7 6 2
8 3 4
which(df$x == 3)
[1] 4 8
length(which(df$x == 3))
[1] 2
count(df, vars = "x")
x freq
1 1 2
2 2 1
3 3 2
4 4 1
5 5 1
6 6 1
df[which(df$x == 3),]
x y
4 3 7
8 3 4
As Matt Weller pointed out, you can use the length
function.
The count
function in plyr
can be used to return the count of each unique column value.
Open Project References, I had lots of yellow warning triangles on the various packages. Click Add Reference, just doing that seems to get VS to refresh it references, and the yellow triangles disappeared and the errors from the code also.
You might have to do this in a few projects if your solution reference to other projects
Since the fields are empty they are not valid, so the ng-invalid
and ng-invalid-required
classes are added properly.
You can use the class ng-pristine
to check out whether the fields have already been used or not.
Assuming you have other data types (and not only string) in your list try this. This removes trailing and leading zeros from strings and leaves other data types untouched. This also handles the special case s = '0'
e.g
a = ['001', '200', 'akdl00', 200, 100, '0']
b = [(lambda x: x.strip('0') if isinstance(x,str) and len(x) != 1 else x)(x) for x in a]
b
>>>['1', '2', 'akdl', 200, 100, '0']
If your query has blob data, this issue can be fixed by applying a my.ini
change as proposed in this answer:
[mysqld]
max_allowed_packet=16M
By default, this will be 1M (the allowed maximum value is 1024M). If the supplied value is not a multiple of 1024K, it will automatically be rounded to the nearest multiple of 1024K.
While the referenced thread is about the MySQL error 2006, setting the max_allowed_packet
from 1M to 16M did fix the 2013 error that showed up for me when running a long query.
For WAMP users: you'll find the flag in the [wampmysqld]
section.
In iOS 8.3 (perhaps earlier) with Swift, it's as simple as overriding the motionBegan
or motionEnded
methods in your view controller:
class ViewController: UIViewController {
override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent) {
println("started shaking!")
}
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) {
println("ended shaking!")
}
}
You can use System.currentTimeMillis()
.
At least in OpenJDK, Date
uses this under the covers.
The call in System
is to a native JVM method, so we can't say for sure there's no allocation happening under the covers, though it seems unlikely here.
The logic applies to many other objectives. And how to read .sh_history of each user from /home/ filesystem? What if there are thousand of them?
#!/bin/ksh
last |head -10|awk '{print $1}'|
while IFS= read -r line
do
su - "$line" -c 'tail .sh_history'
done
Here is the script https://github.com/imvieira/SysAdmin_DevOps_Scripts/blob/master/get_and_run.sh
you can also use below solution -
public static String getRoundOffValue(double value){
DecimalFormat df = new DecimalFormat("##,##,##,##,##,##,##0.00");
return df.format(value);
}
If you want to run .py files in Windows, Try installing Git bash Then download python(Required Version) from python.org and install in the main c drive folder
For me, its :
"C:\Python38"
then open Git Bash and go to the respective folder where your .py file is stored :
For me, its :
File Location : "Downloads" File Name : Train.py
So i changed my Current working Directory From "C:/User/(username)/" to "C:/User/(username)/Downloads"
then i will run the below command
" /c/Python38/python Train.py "
and it will run successfully.
But if it give the below error :
from sklearn.model_selection import train_test_split ModuleNotFoundError: No module named 'sklearn'
Then Do not panic :
and use this command :
" /c/Python38/Scripts/pip install sklearn "
and after it has installed sklearn go back and run the previous command :
" /c/Python38/python Train.py "
and it will run successfully.
!!!!HAPPY LEARNING !!!!
According to the latest document when state is set to be directory, you don't need to use parameter recurse to create parent directories, file module will take care of it.
- name: create directory with parent directories
file:
path: /data/test/foo
state: directory
this is fare enough to create the parent directories data and test with foo
please refer the parameter description - "state" http://docs.ansible.com/ansible/latest/modules/file_module.html
<input type="file">
, add an image and <input style="position:absolute">
it will occupy the space of <input type="file">
Use the following CSS to the file element
position:relative;
opacity:0;
z-index:99;
You're trying to pass file objects as filenames. Try using
infile = '110331_HS1A_1_rtTA.result'
outfile = '2.txt'
at the top of your code.
(Not only does the doubled usage of open()
cause that problem with trying to open the file again, it also means that infile
and outfile
are never closed during the course of execution, though they'll probably get closed once the program ends.)
Easiest way to do this with Chartjs. Just add below line in options:
pieceLabel: {
fontColor: '#000'
}
Best of luck
I was getting this error when executing in python3,I got the same program working by simply executing in python2
The below code illustrates how using a generator returns a result before completion, unlike the traditional non generator approach that returns a complete array after full iteration. With the generator below, the values are returned when ready, no need to wait for an array to be completely filled:
<?php
function sleepiterate($length) {
for ($i=0; $i < $length; $i++) {
sleep(2);
yield $i;
}
}
foreach (sleepiterate(5) as $i) {
echo $i, PHP_EOL;
}
java.util.Date class has before and after method to compare dates.
Date date1 = new Date();
Date date2 = new Date();
if(date1.before(date2)){
//Do Something
}
if(date1.after(date2)){
//Do Something else
}
jQlite (angular's "jQuery" port) doesn't support lookup by classes.
One solution would be to include jQuery in your app.
Another is using QuerySelector
or QuerySelectorAll
:
link: function(scope, element, attrs) {
console.log(element[0].querySelector('.list-scrollable'))
}
We use the first item in the element
array, which is the HTML element. element.eq(0)
would yield the same.
In case, you want to keep old field (For ex: name). The query will be:
INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE
name=name, age=19;
IE 6 and 7: 2
IE 8: 6
IE 9: 6
IE 10: 8
IE 11: 8
Firefox 2: 2
Firefox 3: 6
Firefox 4 to 46: 6
Opera 9.63: 4
Opera 10: 8
Opera 11 and 12: 6
Chrome 1 and 2: 6
Chrome 3: 4
Chrome 4 to 23: 6
Safari 3 and 4: 4
source: http://p2p.wrox.com/book-professional-website-performance-optimizing-front-end-back-end-705/
Multiplexed support(one single TCP connection for all requests)
Did you import the packages for the file reading stuff.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
also here
cfiltering(numberOfUsers, numberOfMovies);
Are you trying to create an object or calling a method?
also another thing:
user_movie_matrix[userNo][movieNo]=rating;
you are assigning a value to a member of an instance as if it was a static variable
also remove the Th
in
private int user_movie_matrix[][];Th
Hope this helps.
One more solution:
#footer { display:table; margin:0 auto; }
#footer li { display:table-cell; padding: 0px 10px; }
Then ul doesn't jump to the next line in case of zooming text.
If using a SASS version (eg: thomas-mcdonald's one), then you may want to be slightly more dynamic (honor existing variables) and create all badge contexts using the same technique as used for labels:
// Colors
// Contextual variations of badges
// Bootstrap 3.0 removed contexts for badges, we re-introduce them, based on what is done for labels
.badge-default {
@include label-variant($label-default-bg);
}
.badge-primary {
@include label-variant($label-primary-bg);
}
.badge-success {
@include label-variant($label-success-bg);
}
.badge-info {
@include label-variant($label-info-bg);
}
.badge-warning {
@include label-variant($label-warning-bg);
}
.badge-danger {
@include label-variant($label-danger-bg);
}
The LESS equivalent should be straightforward.
why not just put the ng-controller one level higher,
<body ng-controller="ProjectController">
<div ng-view><div>
And don't set controller in the route,
.when('/', { templateUrl: "abc.html" })
it works for me.
In Android studio canary build(3.+), you can do the following:
File -> Project Structure -> Look in Modules Section, there are names of modules of your class. Click on the module in which you want to upgrade java to 1.8 version. -> Change "Source Compatibility" and "Target Compatibility" to 1.8 from 1.7 or lower. Do not change anything else. -> Click Apply
now gradle will re-sync and your error will be removed.
I understand this question is for sql server 2012, but if the same scenario for SQL Server 2017 or SQL Azure you can use Trim
directly as below:
UPDATE *tablename*
SET *columnname* = trim(*columnname*);
You may use Dynamic Programmining. Algo complexity is O(Sum * N) and use O(Sum) memory.
Here's my implementation in C#:
private static int GetmNumberOfSubsets(int[] numbers, int sum)
{
int[] dp = new int[sum + 1];
dp[0] = 1;
int currentSum =0;
for (int i = 0; i < numbers.Length; i++)
{
currentSum += numbers[i];
for (int j = Math.Min(sum, currentSum); j >= numbers[i]; j--)
dp[j] += dp[j - numbers[i]];
}
return dp[sum];
}
Notes: As number of subsets may have value 2^N it easy may overflows int type.
Algo works only for positive numbers.
I would probably do something along the lines of
<div id='search-logo-bar'><input type='text'/></div>
with css
div#search-logo-bar {
padding-left:10%;
background:#333 url(logo.png) no-repeat left center;
background-size:10%;
}
input[type='text'] {
display:block;
width:100%;
}
DEMO
You are calling setTimeout()
ten times in a row, so they all expire almost at the same time. What you actually want is this:
window.onload = function start() {
slide(10);
}
function slide(repeats) {
if (repeats > 0) {
document.getElementById('container').style.marginLeft='-600px';
document.getElementById('container').style.marginLeft='-1200px';
document.getElementById('container').style.marginLeft='-1800px';
document.getElementById('container').style.marginLeft='0px';
window.setTimeout(
function(){
slide(repeats - 1)
},
3000
);
}
}
This will call slide(10), which will then set the 3-second timeout to call slide(9), which will set timeout to call slide(8), etc. When slide(0) is called, no more timeouts will be set up.
The Simple Difference is: console.log() methods automatically append new line character. It means if we are looping through and printing the result, each result get printed in new line.
process.stdout.write() methods don't append new line character. useful for printing patterns.
1) Download Ruby 1.9.3
2) cmd check command: ruby -v
'return result ruby 1.9.3 then success full install ruby
3) Download DevKit file from http://rubyinstaller.org/downloads (DevKit-tdm-32-4.5.2-20110712-1620-sfx.exe)
4) Extract DevKit to path C:\Ruby193\DevKit
5) cd C:\Ruby193\DevKit
6) ruby dk.rb init
7) ruby dk.rb review
8) ruby dk.rb install
9) cmd : gem install rails -v3.1.1
'few time installing full process'
10) cmd : rails -v
'return result rails 3.1.1 then its success fully install'
enjoy Ruby on Rails...
My 5 cents.
This problem started after a solution wide clean.
I managed to get the problem to go away by setting the Active Solution configuration in: Build -> Configuration manager to release. Then build and set it back to debug again. The build succeeded after that.
Use IsNumeric Function :
IsNumeric(number)
If you want to validate a phone number you should use a regular expression, for example:
^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{3})$
What version of the framework? With 3.5 you could presumably use:
List<ManagementObject> managementList = managementObjects.Cast<ManagementObject>().ToList();
(edited to remove simpler version; I checked and ManagementObjectCollection
only implements the non-generic IEnumerable
form)
No need to add commands anymore. For those who are new to Visual Studio Code and searching for an easy way to format code on saving, kindly follow the below steps.
[Cmd+,]
in Mac or using the below screenshot.You are done. Thank you.
Add '\t' for tab
<string name="tab">\u0009</string>
It's not possible with CSS3. There is a proposed CSS4 selector, $
, to do just that, which could look like this (Selecting the li
element):
ul $li ul.sub { ... }
See the list of CSS4 Selectors here.
As an alternative, with jQuery, a one-liner you could make use of would be this:
$('ul li:has(ul.sub)').addClass('has_sub');
You could then go ahead and style the li.has_sub
in your CSS.
The approach I've found workable is git's submodule system. Using that you can submodule in a given version of the code and upgrading/downgrading is explicit and recorded - never haphazard.
The folder structure I've taken with this is:
+ myproject
++ src
+++ myproject
+++ github.com
++++ submoduled_project of some kind.
Simply floating both elements left achieves the same result.
div {
background:yellow;
vertical-align:middle;
margin:10px;
}
a {
background-color:#FFF;
width:20px;
height:20px;
display:inline-block;
border:solid black 1px;
float:left;
}
span {
background:red;
display:inline-block;
float:left;
}
2 month old thread, but better late than never! On 10.6, I have my webserver documents folder set to:
owner:root
group:_www
permission:755
_www is the user that runs apache under Mac OS X. I then added an ACL to allow full permissions to the Administrators group. That way, I can still make any changes with my admin user without having to authenticate as root. Also, when I want to allow the webserver to write to a folder, I can simply chmod to 775, leaving everyone other than root:_www with only read/execute permissions (excluding any ACLs that I have applied)
Create your own conversion function that applies the needed math, and invoke those instead. http://en.wikipedia.org/wiki/Radian#Conversion_between_radians_and_degrees
You can't combine a WHERE clause with a VALUES clause. You have two options as far as I am aware-
INSERT specifying values
INSERT INTO Users(weight, desiredWeight)
VALUES (160,145)
INSERT using a SELECT statement
INSERT INTO Users(weight, desiredWeight)
SELECT weight, desiredWeight
FROM AnotherTable
WHERE id = 1
Old post, but I thought I would share my solution because there aren't many solutions out there for this issue.
If you're running an old Windows Server 2003 machine, you likely need to install a hotfix (KB938397).
This problem occurs because the Cryptography API 2 (CAPI2) in Windows Server 2003 does not support the SHA2 family of hashing algorithms. CAPI2 is the part of the Cryptography API that handles certificates.
https://support.microsoft.com/en-us/kb/938397
For whatever reason, Microsoft wants to email you this hotfix instead of allowing you to download directly. Here's a direct link to the hotfix from the email:
http://hotfixv4.microsoft.com/Windows Server 2003/sp3/Fix200653/3790/free/315159_ENU_x64_zip.exe
We can use the get_locale
function:
if (get_locale() == 'en_GB') {
// drink tea
}
Check the partition where you have installed docker. In most cases, the partition is at 100% capacity so you may need to look into that.
I do not know if your still looking for the answer to this problem but today I happened the same problem and solved it. You need to specify in the HTML code,
**<Div class = "navbar"**>
div class = "container">
<Div class = "navbar-header">
or
**<Div class = "navbar navbar-default">**
div class = "container">
<Div class = "navbar-header">
You got that place in your CSS
.navbar-default-toggle .navbar .icon-bar {
background-color: # 0000ff;
}
and what I did was add above
.navbar .navbar-toggle .icon-bar {
background-color: # ff0000;
}
Because my html code is
**<Div class = "navbar">**
div class = "container">
<Div class = "navbar-header">
and if you associate a file less / css
search this section and also here placed the color you want to change, otherwise it will self-correct the css file to the state it was before
// Toggle Navbar
@ Navbar-default-toggle-hover-bg: #ddd;
**@ Navbar-default-toggle-icon-bar-bg: # 888;**
@ Navbar-default-toggle-border-color: #ddd;
if your html code is like mine and is not navbar-default, add it as you did with the css.
// Toggle Navbar
@ Navbar-default-toggle-hover-bg: #ddd;
**@ Navbar-toggle-icon-bar-bg : #888;**
@ Navbar-default-toggle-icon-bar-bg: # 888;
@ Navbar-default-toggle-border-color: #ddd;
good luck
According to 'Getting Started With LLVM Core Libraries' book (c):
In fact, the name LLVM might refer to any of the following:
The LLVM project/infrastructure: This is an umbrella for several projects that, together, form a complete compiler: frontends, backends, optimizers, assemblers, linkers, libc++, compiler-rt, and a JIT engine. The word "LLVM" has this meaning, for example, in the following sentence: "LLVM is comprised of several projects".
An LLVM-based compiler: This is a compiler built partially or completely with the LLVM infrastructure. For example, a compiler might use LLVM for the frontend and backend but use GCC and GNU system libraries to perform the final link. LLVM has this meaning in the following sentence, for example: "I used LLVM to compile C programs to a MIPS platform".
LLVM libraries: This is the reusable code portion of the LLVM infrastructure. For example, LLVM has this meaning in the sentence: "My project uses LLVM to generate code through its Just-in-Time compilation framework".
LLVM core: The optimizations that happen at the intermediate language level and the backend algorithms form the LLVM core where the project started. LLVM has this meaning in the following sentence: "LLVM and Clang are two different projects".
The LLVM IR: This is the LLVM compiler intermediate representation. LLVM has this meaning when used in sentences such as "I built a frontend that translates my own language to LLVM".
Only reason to use linked list is that insert the element is easy (removing also).
Disadvatige could be that pointers take a lot of space.
And about that coding is harder: Usually you don't need code linked list (or only once) they are included in STL and it is not so complicated if you still have to do it.
Your route isn't ok, it should be like this (with ':')
app.get('/documents/:format/:type', function (req, res) {
var format = req.params.format,
type = req.params.type;
});
Also you cannot interchange parameter order unfortunately.
For more information on req.params
(and req.query
) check out the api reference here.
The simple way of doing this would be (assuming your list is in 'l'):
>>> counter = {}
>>> for i in l: counter[i] = counter.get(i, 0) + 1
>>> sorted([ (freq,word) for word, freq in counter.items() ], reverse=True)[:3]
[(6, 'Jellicle'), (5, 'Cats'), (3, 'to')]
Complete sample:
>>> l = ['Jellicle', 'Cats', 'are', 'black', 'and', 'white,', 'Jellicle', 'Cats', 'are', 'rather', 'small;', 'Jellicle', 'Cats', 'are', 'merry', 'and', 'bright,', 'And', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.', 'Jellicle', 'Cats', 'have', 'cheerful', 'faces,', 'Jellicle', 'Cats', 'have', 'bright', 'black', 'eyes;', 'They', 'like', 'to', 'practise', 'their', 'airs', 'and', 'graces', 'And', 'wait', 'for', 'the', 'Jellicle', 'Moon', 'to', 'rise.', '']
>>> counter = {}
>>> for i in l: counter[i] = counter.get(i, 0) + 1
...
>>> counter
{'and': 3, '': 1, 'merry': 1, 'rise.': 1, 'small;': 1, 'Moon': 1, 'cheerful': 1, 'bright': 1, 'Cats': 5, 'are': 3, 'have': 2, 'bright,': 1, 'for': 1, 'their': 1, 'rather': 1, 'when': 1, 'to': 3, 'airs': 1, 'black': 2, 'They': 1, 'practise': 1, 'caterwaul.': 1, 'pleasant': 1, 'hear': 1, 'they': 1, 'white,': 1, 'wait': 1, 'And': 2, 'like': 1, 'Jellicle': 6, 'eyes;': 1, 'the': 1, 'faces,': 1, 'graces': 1}
>>> sorted([ (freq,word) for word, freq in counter.items() ], reverse=True)[:3]
[(6, 'Jellicle'), (5, 'Cats'), (3, 'to')]
With simple I mean working in nearly every version of python.
if you don't understand some of the functions used in this sample, you can always do this in the interpreter (after pasting the code above):
>>> help(counter.get)
>>> help(sorted)
The easyest way is to change .attr() function to a javascript function .setAttribute()
$('#stop').click(function() {
$('next')[0].setAttribute('onclick','stopMoving()');
}
For very large output logs it could be difficult to open (network delay, scrolling). This is the solution I'm using to check big log files:
https://${URL}/jenkins/job/${jobName}/${buildNumber}/
in the left column you see: View as plain text
. Do a right mouse click on it and choose save links as
. Now you can save your big log as .txt file. Open it with notepad++ and you can go through your logs easily without network delays during scrolling.
$JAVA_HOME
should be the directory where java was installed, not one of its parts:
export JAVA_HOME=/usr/lib/jvm/java-7-oracle
You can add the src
folder to build path by:
src
folder.And you are done. Hope this help.
EDIT: Refer to the Eclipse documentation
Here is the unpowerful official command:
npm view <PACKAGE> dependencies
It prints only the direct dependencies, not the whole tree.
Want to align an image which have after a text / title and both are inside a div?
See on JSfiddle or Run Code Snippet.
Just be sure to have an ID or a class at all your elements (div, img, title, etc.).
For me works this solution on all browsers (for mobile devices you must to adapt your code with: @media).
h2.h2red {_x000D_
color: red;_x000D_
font-size: 14px;_x000D_
}_x000D_
.mydivclass {_x000D_
margin-top: 30px;_x000D_
display: block;_x000D_
}_x000D_
img.mydesiredclass {_x000D_
margin-right: 10px;_x000D_
display: block;_x000D_
float: left; /* If you want to allign the text with an image on the same row */_x000D_
width: 100px;_x000D_
heght: 100px;_x000D_
margin-top: -40px /* Change this value to adapt to your page */;_x000D_
}
_x000D_
<div class="mydivclass">_x000D_
<br />_x000D_
<img class="mydesiredclass" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b3/Wikipedia-logo-v2-en.svg/2000px-Wikipedia-logo-v2-en.svg.png">_x000D_
<h2 class="h2red">Text aligned after image inside a div by negative manipulate the img position</h2>_x000D_
</div>
_x000D_
All strings meant for humans should use u"".
I found that the following mindset helps a lot when dealing with Python strings: All Python manifest strings should use the u""
syntax. The ""
syntax is for byte arrays, only.
Before the bashing begins, let me explain. Most Python programs start out with using ""
for strings. But then they need to support documentation off the Internet, so they start using "".decode
and all of a sudden they are getting exceptions everywhere about decoding this and that - all because of the use of ""
for strings. In this case, Unicode does act like a virus and will wreak havoc.
But, if you follow my rule, you won't have this infection (because you will already be infected).
Don't like any of those solutions.
this is how i do it:
$update_query = "UPDATE db.tablename SET insert_time=now() WHERE username='"
. sqlEsc($somename) . "' ;";
then i use my own sqlEsc function:
function sqlEsc($val)
{
global $mysqli;
return mysqli_real_escape_string($mysqli, $val);
}
I once ran into this situation and I had the dependencies in classpath. The solution was to include javax.mail and javax.activation libraries in the container's (eg. tomcat) lib folder. Using maven -set them to provided scope and it should work. You will have shared email libs in classpath for all projects.
Useful source: http://haveacafe.wordpress.com/2008/09/26/113/
I actually just found this today for something I'm working on. This will return file paths for all files in a folder and its subfolders.
Dim colFiles As New Collection
RecursiveDir colFiles, "C:\Users\Marek\Desktop\Makro\", "*.*", True
Dim vFile As Variant
For Each vFile In colFiles
'file operation here or store file name/path in a string array for use later in the script
filepath(n) = vFile
filename = fso.GetFileName(vFile) 'If you want the filename without full path
n=n+1
Next vFile
'These two functions are required
Public Function RecursiveDir(colFiles As Collection, strFolder As String, strFileSpec As String, bIncludeSubfolders As Boolean)
Dim strTemp As String
Dim colFolders As New Collection
Dim vFolderName As Variant
strFolder = TrailingSlash(strFolder)
strTemp = Dir(strFolder & strFileSpec)
Do While strTemp <> vbNullString
colFiles.Add strFolder & strTemp
strTemp = Dir
Loop
If bIncludeSubfolders Then
strTemp = Dir(strFolder, vbDirectory)
Do While strTemp <> vbNullString
If (strTemp <> ".") And (strTemp <> "..") Then
If (GetAttr(strFolder & strTemp) And vbDirectory) <> 0 Then
colFolders.Add strTemp
End If
End If
strTemp = Dir
Loop
'Call RecursiveDir for each subfolder in colFolders
For Each vFolderName In colFolders
Call RecursiveDir(colFiles, strFolder & vFolderName, strFileSpec, True)
Next vFolderName
End If
End Function
Public Function TrailingSlash(strFolder As String) As String
If Len(strFolder) > 0 Then
If Right(strFolder, 1) = "\" Then
TrailingSlash = strFolder
Else
TrailingSlash = strFolder & "\"
End If
End If
End Function
This is adapted from a post by Ammara Digital Image Solutions.(http://www.ammara.com/access_image_faq/recursive_folder_search.html).
ReSharper - Ctrl + Alt + F
Visual Studio 2010 - Ctrl + K, Ctrl + D
Considere the case that Java is Multiplatform:
int lastPath = fileName.lastIndexOf(File.separator);
if (lastPath!=-1){
fileName = fileName.substring(lastPath+1);
}
Try this out to execute a command on 30th March 2011 at midnight:
0 0 30 3 ? 2011 /command
WARNING: As noted in comments, the year column is not supported in standard/default implementations of cron. Please refer to TomOnTime answer below, for a proper way to run a script at a specific time in the future in standard implementations of cron.
Another way to rename the database or taking image of the database is by using Reverse engineering option in the database tab. It will create a ERR diagram for the database. Rename the schema there.
after that go to file menu and go to export and forward engineer the database.
Then you can import the database.
It's the new feature in C# 6 called Interpolated Strings
.
The easiest way to understand it is: an interpolated string expression creates a string by replacing the contained expressions with the ToString representations of the expressions' results.
For more details about this, please take a look at MSDN.
Now, think a little bit more about it. Why this feature is great?
For example, you have class Point
:
public class Point
{
public int X { get; set; }
public int Y { get; set; }
}
Create 2 instances:
var p1 = new Point { X = 5, Y = 10 };
var p2 = new Point { X = 7, Y = 3 };
Now, you want to output it to the screen. The 2 ways that you usually use:
Console.WriteLine("The area of interest is bounded by (" + p1.X + "," + p1.Y + ") and (" + p2.X + "," + p2.Y + ")");
As you can see, concatenating string like this makes the code hard to read and error-prone. You may use string.Format()
to make it nicer:
Console.WriteLine(string.Format("The area of interest is bounded by({0},{1}) and ({2},{3})", p1.X, p1.Y, p2.X, p2.Y));
This creates a new problem:
For those reasons, we should use new feature:
Console.WriteLine($"The area of interest is bounded by ({p1.X},{p1.Y}) and ({p2.X},{p2.Y})");
The compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.
For the full post, please read this blog.
No you can't.
You can change the size to make it larger... similar to Dreas idea, but it is the size you need to change.
<select id="countries" size="6">
<option value="1">Country 1</option>
<option value="2">Country 2</option>
<option value="3">Country 3</option>
<option value="4">Country 4</option>
<option value="5">Country 5</option>
<option value="6">Country 6</option>
</select>
You will find much information about JavaDoc at the Documentation Comment Specification for the Standard Doclet, including the information on the
tag (that you are looking for). The corresponding example from the documentation is as follows
For example, here is a comment that refers to the getComponentAt(int, int) method:
Use the {@link #getComponentAt(int, int) getComponentAt} method.
The package.class
part can be ommited if the referred method is in the current class.
Other useful links about JavaDoc are:
It's short for Dimension, as it was originally used in BASIC to specify the size of arrays.
DIM — (short for dimension) define the size of arrays
Ref: http://en.wikipedia.org/wiki/Dartmouth_BASIC
A part of the original BASIC compiler source code, where it would jump when finding a DIM
command, in which you can clearly see the original intention for the keyword:
DIM LDA XR01 BACK OFF OBJECT POINTER
SUB N3
STA RX01
LDA L 2 GET VARIABLE TO BE DIMENSIONED
STA 3
LDA S 3
CAB N36 CHECK FOR $ ARRAY
BRU *+7 NOT $
...
Ref: http://dtss.dartmouth.edu/scans/BASIC/BASIC%20Compiler.pdf
Later on it came to be used to declare all kinds of variables, when the possibility to specify the type for variables was added in more recent implementations.
If you use yum search you can find the python dev package for your version of python.
For me I was using python 3.5. I ran the following
yum search python | grep devel
Which returned the following
I was then able to install the correct package for my version of python with the following cmd.
sudo yum install python35u-devel.x86_64
This works on centos for ubuntu or debian you would need to use apt-get
Instead of returning a resultsArray
you return a promise for a results array and then then
that on the call site - this has the added benefit of the caller knowing the function is performing asynchronous I/O. Coding concurrency in JavaScript is based on that - you might want to read this question to get a broader idea:
function resultsByName(name)
{
var Card = Parse.Object.extend("Card");
var query = new Parse.Query(Card);
query.equalTo("name", name.toString());
var resultsArray = [];
return query.find({});
}
// later
resultsByName("Some Name").then(function(results){
// access results here by chaining to the returned promise
});
You can see more examples of using parse promises with queries in Parse's own blog post about it.
I think you can use
sys.exit(0)
You may check it here in the python 2.7 doc:
The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like.
I just found a solution that I think works really well and gets around all of the pitfalls of custom symbols. The main problem with the li:before solution is that if list-items are longer than one line will not indent properly after the first line of text. By using text-indent with a negative padding we can circumvent that problem and have all the lines aligned properly:
ul{
padding-left: 0; // remove default padding
}
li{
list-style-type: none; // remove default styles
padding-left: 1.2em;
text-indent:-1.2em; // remove padding on first line
}
li::before{
margin-right: 0.5em;
width: 0.7em; // margin-right and width must add up to the negative indent-value set above
height: 0.7em;
display: inline-block;
vertical-align: middle;
border-radius: 50%;
background-color: orange;
content: ' '
}
The embedded code of youtube has autoplay off by default. Simply add autoplay=1
at the end of "src" attribute. For example:
<iframe src="http://www.youtube.com/embed/xzvScRnF6MU?autoplay=1" width="960" height="447" frameborder="0" allowfullscreen></iframe>
By definition dictionaries are unordered, and therefore cannot be indexed. For that kind of functionality use an ordered dictionary. Python Ordered Dictionary
In case you are as talented as me and have made the Window menu invisible, there is no way back, as the Customize and Reset Perspective are no longer available. Having good other perspectives do not help, as you only can apparently edit the current perspective only. To get out without nuking all the workspace settings, the following may work:
<persistedState key="persp.hiddenItems"
for the perspective in question. value
, which is a comma-separated list. You may look through the list and manually remove list items from this value which look like they need to be unhidden. In my case, the offending element appeared close to the beginning of the file:
<children xsi:type="advanced:Perspective" xmi:id="..." elementId="org.eclipse.cdt.ui.CPerspective" selectedElement="..." label="C/C++" iconURI="platform:/plugin/org.eclipse.cdt.ui/icons/view16/c_pers.gif">
<persistedState key="persp.hiddenItems" value="persp.hideToolbarSC:org.eclipse.jdt.ui.actions.OpenProjectWizard,...,"/>
where some parts were replaced with dots. Obviously, you need to be careful editing machine-generated files. Somebody may be able to write a script.
Now you can safely lock you out again.
The other solution are OK, but there is no need to add separator at the very last if using :after or at the very beginning if using :before.
SO:
case :after
.link:after {
content: '|';
padding: 0 1rem;
}
.link:last-child:after {
content: '';
}
case :before
.link:before {
content: '|';
padding: 0 1rem;
}
.link:first-child:before {
content: '';
}
Look, the sed script that prints the 100 last lines you can find in the documentation for sed (https://www.gnu.org/software/sed/manual/sed.html#tail):
$ cat sed.cmd
1! {; H; g; }
1,100 !s/[^\n]*\n//
$p
$ sed -nf sed.cmd logfilename
For me it is way more difficult than your script so
tail -n 100 logfilename
is much much simpler. And it is quite efficient, it will not read all file if it is not necessary. See my answer with strace report for tail ./huge-file
: https://unix.stackexchange.com/questions/102905/does-tail-read-the-whole-file/102910#102910
If your administrator changed your password, and Windows 10 still stores your old password you will not be asked for a new password. Windows 10 will use the stored old password, and authentication will fail.
You can delete your old password by
If you delete a password, when you try to use SVN, you will be asked for the new password.
The numpy and scipy libraries include the composite trapezoidal (numpy.trapz) and Simpson's (scipy.integrate.simps) rules.
Here's a simple example. In both trapz
and simps
, the argument dx=5
indicates that the spacing of the data along the x axis is 5 units.
from __future__ import print_function
import numpy as np
from scipy.integrate import simps
from numpy import trapz
# The y values. A numpy array is used here,
# but a python list could also be used.
y = np.array([5, 20, 4, 18, 19, 18, 7, 4])
# Compute the area using the composite trapezoidal rule.
area = trapz(y, dx=5)
print("area =", area)
# Compute the area using the composite Simpson's rule.
area = simps(y, dx=5)
print("area =", area)
Output:
area = 452.5
area = 460.0
or hide any br that follows the p tag, which are obviously not wanted
p + br {
display: none;
}
I know for there's Fluid and Prism (there are others, that's the one I used to use) that let you load a website into what looks like a standalone app.
In Chrome, you can create desktop shortcuts for websites. (you do that from within Chrome, you can't/shouldn't package that with your app) Chrome Frame is different:
Google Chrome Frame is a plug-in designed for Internet Explorer based on the open-source Chromium project; it brings Google Chrome's open web technologies to Internet Explorer.
You'd need to have some sort of wrapper like that for your webapp, and then the rest is the web technologies you're used to. You can use HTML5 local storage to store data while the app is offline. I think you might even be able to work with SQLite.
I don't know how you would go about accessing OS specific features, though. What I described above has the same limitations as any "regular" website. Hopefully this gives you some sort of guidance on where to start.
we can do it in more easy way like by adding a function on button and on click we call that function for append.
<div id="Content">
<button id="Add" onclick="append();">Add Text</button>
</div>
<script type="text/javascript">
function append()
{
$('<p>Text</p>').appendTo('#Content');
}
</script>
Here you get all available services and their status in your local machine.
ServiceController[] services = ServiceController.GetServices();
foreach(ServiceController service in services)
{
Console.WriteLine(service.ServiceName+"=="+ service.Status);
}
You can Compare your service with service.name property inside loop and you get status of your service. For details go with the http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.aspx also http://msdn.microsoft.com/en-us/library/microsoft.windows.design.servicemanager(v=vs.90).aspx
I think this issue following model class wrong import.
import org.springframework.data.annotation.Id;
Normally, it should be:
import javax.persistence.Id;
I can confirm that the solution by delphifirst works and is the easiest, simplest solution to the problem of running a python script with elevated privileges.
I created a shortcut to the python executable (python.exe) and then modified the shortcut by adding my script's name after the call to python.exe. Next I checked "run as administrator" on the "compatibility tab" of the shortcut. When the shortcut is executed, you get a prompt asking permission to run the script as an administrator.
My particular python application was an installer program. The program allows installing and uninstalling another python app. In my case I created two shortcuts, one named "appname install" and the other named "appname uninstall". The only difference between the two shortcuts is the argument following the python script name. In the installer version the argument is "install". In the uninstall version the argument is "uninstall". Code in the installer script evaluates the argument supplied and calls the appropriate function (install or uninstall) as needed.
I hope my explanation helps others more quickly figure out how to run a python script with elevated privileges.
In general, fixing corrupt objects can be pretty difficult. However, in this case, we're confident that the problem is an aborted transfer, meaning that the object is in a remote repository, so we should be able to safely remove our copy and let git get it from the remote, correctly this time.
The temporary object file, with zero size, can obviously just be removed. It's not going to do us any good. The corrupt object which refers to it, d4a0e75...
, is our real problem. It can be found in .git/objects/d4/a0e75...
. As I said above, it's going to be safe to remove, but just in case, back it up first.
At this point, a fresh git pull
should succeed.
...assuming it was going to succeed in the first place. In this case, it appears that some local modifications prevented the attempted merge, so a stash
, pull
, stash pop
was in order. This could happen with any merge, though, and didn't have anything to do with the corrupted object. (Unless there was some index cleanup necessary, and the stash did that in the process... but I don't believe so.)
This error happened to me because I had @@model instead of @model... copy & paste error in my case. Changing to @model fixed it for me.
It is possible. Have a look at JSch.addIdentity(...)
This allows you to use key either as byte array or to read it from file.
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class UserAuthPubKey {
public static void main(String[] arg) {
try {
JSch jsch = new JSch();
String user = "tjill";
String host = "192.18.0.246";
int port = 10022;
String privateKey = ".ssh/id_rsa";
jsch.addIdentity(privateKey);
System.out.println("identity added ");
Session session = jsch.getSession(user, host, port);
System.out.println("session created.");
// disabling StrictHostKeyChecking may help to make connection but makes it insecure
// see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
//
// java.util.Properties config = new java.util.Properties();
// config.put("StrictHostKeyChecking", "no");
// session.setConfig(config);
session.connect();
System.out.println("session connected.....");
Channel channel = session.openChannel("sftp");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
System.out.println("shell channel connected....");
ChannelSftp c = (ChannelSftp) channel;
String fileName = "test.txt";
c.put(fileName, "./in/");
c.exit();
System.out.println("done");
} catch (Exception e) {
System.err.println(e);
}
}
}
mod_rewrite can only rewrite/redirect requested URIs. So you would need to request /apple/…
to get it rewritten to a corresponding /folder1/…
.
Try this:
RewriteEngine on
RewriteRule ^apple/(.*) folder1/$1
This rule will rewrite every request that starts with the URI path /apple/…
internally to /folder1/…
.
Edit As you are actually looking for the other way round:
RewriteCond %{THE_REQUEST} ^GET\ /folder1/
RewriteRule ^folder1/(.*) /apple/$1 [L,R=301]
This rule is designed to work together with the other rule above. Requests of /folder1/…
will be redirected externally to /apple/…
and requests of /apple/…
will then be rewritten internally back to /folder1/…
.
No, you can't change scrollbars placement without any additional issues.
You can change text-direction to right-to-left ( rtl ), but it also change text position inside block.
This code can helps you, but I not sure it works in all browsers and OS.
<element style="direction: rtl; text-align: left;" />
I had the same problem but when I looked closely I found that, it was causing because I was trying to put the foreign key values into the tables before that key was assigned its primary key value. e.g. I had two tables "customers" and "films", "cust_id" and "film_id" were primary key respectively. "customer" had one-to-many relation with "films" so I had "cust_id" as foreign key in "films" tables. But I was trying to put values to "films" table first, so I got that problem.
ES6 - I am including an example, which was helpful for me:
In a "short if statement" you can pass empty function like this:
isReady ? ()=>{} : onClick
This seems to be the shortest approach.
()=>{}
SELECT t1.credit,
t2.debit
FROM (SELECT Sum(c.total_amount) AS credit
FROM credit c
WHERE c.status = "a") AS t1,
(SELECT Sum(d.total_amount) AS debit
FROM debit d
WHERE d.status = "a") AS t2
Python doesn't have the quite the extensive range of "built-in" data structures as Java does. However, because Python is dynamic, a general tree is easy to create. For example, a binary tree might be:
class Tree:
def __init__(self):
self.left = None
self.right = None
self.data = None
You can use it like this:
root = Tree()
root.data = "root"
root.left = Tree()
root.left.data = "left"
root.right = Tree()
root.right.data = "right"
If you need an arbitrary number of children per node, then use a list of children:
class Tree:
def __init__(self, data):
self.children = []
self.data = data
left = Tree("left")
middle = Tree("middle")
right = Tree("right")
root = Tree("root")
root.children = [left, middle, right]
try this
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Linuxbrew/linuxbrew/go/install)"
Just Add this code in the class @Overide
public boolean dispatchTouchEvent(MotionEvent ev) {
View view = getCurrentFocus();
if (view != null && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) && view instanceof EditText && !view.getClass().getName().startsWith("android.webkit.")) {
int scrcoords[] = new int[2];
view.getLocationOnScreen(scrcoords);
float x = ev.getRawX() + view.getLeft() - scrcoords[0];
float y = ev.getRawY() + view.getTop() - scrcoords[1];
if (x < view.getLeft() || x > view.getRight() || y < view.getTop() || y > view.getBottom())
((InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow((this.getWindow().getDecorView().getApplicationWindowToken()), 0);
}
return super.dispatchTouchEvent(ev);
}
videoId = videoUrl.split('v=')[1].substring(0,11);
Inside CONCATENATE
you can use TRANSPOSE
if you expand it (F9) then remove the surrounding {}
brackets like this recommends
=CONCATENATE(TRANSPOSE(B2:B19))
Becomes
=CONCATENATE("Oh ","combining ", "a " ...)
You may need to add your own separator on the end, say create a column C and transpose that column.
=B1&" "
=B2&" "
=B3&" "
This is fixed in npm 7. See npm/cli#PR169
I have head around lots of solutions and none of them works perfectly. I've used variation of solutions available in my project which is here as below. Please use this code inside class where you are initialising toolbar and drawer layout.
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
drawerFragment.mDrawerToggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);// show back button
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
} else {
//show hamburger
drawerFragment.mDrawerToggle.setDrawerIndicatorEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
drawerFragment.mDrawerToggle.syncState();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawerFragment.mDrawerLayout.openDrawer(GravityCompat.START);
}
});
}
}
});
You just need to create a deleter class:
struct BarDeleter {
void operator()(Bar* b) { destroy(b); }
};
and provide it as the template argument of unique_ptr
. You'll still have to initialize the unique_ptr in your constructors:
class Foo {
public:
Foo() : bar(create()), ... { ... }
private:
std::unique_ptr<Bar, BarDeleter> bar;
...
};
As far as I know, all the popular c++ libraries implement this correctly; since BarDeleter
doesn't actually have any state, it does not need to occupy any space in the unique_ptr
.
What about:
datetime.now().strftime('%M:%S.%f')[:-4]
I'm not sure what you mean by "Milliseconds only 2 digits", but this should keep it to 2 decimal places. There may be a more elegant way by manipulating the strftime format string to cut down on the precision as well -- I'm not completely sure.
EDIT
If the %f
modifier doesn't work for you, you can try something like:
now=datetime.now()
string_i_want=('%02d:%02d.%d'%(now.minute,now.second,now.microsecond))[:-4]
Again, I'm assuming you just want to truncate the precision.
For completeness these are the cmap choices I encountered so far:
Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r, GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r, Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r, Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn, RdYlGn_r, Reds, Reds_r, Set1, Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, YlGn_r, YlOrBr, YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r, cividis, cividis_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r, flag, flag_r, gist_earth, gist_earth_r, gist_gray, gist_gray_r, gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, gist_rainbow_r, gist_stern, gist_stern_r, gist_yarg, gist_yarg_r, gnuplot, gnuplot2, gnuplot2_r, gnuplot_r, gray, gray_r, hot, hot_r, hsv, hsv_r, inferno, inferno_r, jet, jet_r, magma, magma_r, nipy_spectral, nipy_spectral_r, ocean, ocean_r, pink, pink_r, plasma, plasma_r, prism, prism_r, rainbow, rainbow_r, seismic, seismic_r, spring, spring_r, summer, summer_r, tab10, tab10_r, tab20, tab20_r, tab20b, tab20b_r, tab20c, tab20c_r, terrain, terrain_r, twilight, twilight_r, twilight_shifted, twilight_shifted_r, viridis, viridis_r, winter, winter_r
Firstly, application.properties in the @PropertySource should read application-test.properties
if that's what the file is named (matching these things up matters):
@PropertySource("classpath:application-test.properties ")
That file should be under your /src/test/resources
classpath (at the root).
I don't understand why you'd specify a dependency hard coded to a file called application-test.properties
. Is that component only to be used in the test environment?
The normal thing to do is to have property files with the same name on different classpaths. You load one or the other depending on whether you are running your tests or not.
In a typically laid out application, you'd have:
src/test/resources/application.properties
and
src/main/resources/application.properties
And then inject it like this:
@PropertySource("classpath:application.properties")
The even better thing to do would be to expose that property file as a bean in your spring context and then inject that bean into any component that needs it. This way your code is not littered with references to application.properties and you can use anything you want as a source of properties. Here's an example: how to read properties file in spring project?
The NSDictionary and NSMutableDictionary docs are probably your best bet. They even have some great examples on how to do various things, like...
...create an NSDictionary
NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", nil];
NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects
forKeys:keys];
...iterate over it
for (id key in dictionary) {
NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}
...make it mutable
NSMutableDictionary *mutableDict = [dictionary mutableCopy];
Note: historic version before 2010: [[dictionary mutableCopy] autorelease]
...and alter it
[mutableDict setObject:@"value3" forKey:@"key3"];
...then store it to a file
[mutableDict writeToFile:@"path/to/file" atomically:YES];
...and read it back again
NSMutableDictionary *anotherDict = [NSMutableDictionary dictionaryWithContentsOfFile:@"path/to/file"];
...read a value
NSString *x = [anotherDict objectForKey:@"key1"];
...check if a key exists
if ( [anotherDict objectForKey:@"key999"] == nil ) NSLog(@"that key is not there");
...use scary futuristic syntax
From 2014 you can actually just type dict[@"key"] rather than [dict objectForKey:@"key"]
Python 2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.pi
3.141592653589793
Check out the Python tutorial on modules and how to use them.
As for the second part of your question, Python comes with batteries included, of course:
>>> math.radians(90)
1.5707963267948966
>>> math.radians(180)
3.141592653589793
I asked the same question to Xamarin support team, they replied with following:
You can develop an app with Xamarin for commercial usage - there is no extra charge! We only require you to comply with Visual Studio's licensing terms,
which means that in companies of less than 250 employees with less than $1million USD annual revenue, you may use Visual Studio completely free (including Xamarin) for up to 5 developers.
However after you pass those barriers, you would need a Visual Studio license (which includes Xamarin).
Refer the screenshot below.
Try using this code instead. Note: In the "from address" give your correct email id and password.
protected void btn_send_Click(object sender, EventArgs e)
{
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.To.Add("to gmail address");
mail.From = new MailAddress("from gmail address", "Email head", System.Text.Encoding.UTF8);
mail.Subject = "This mail is send from asp.net application";
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.Body = "This is Email Body Text";
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = true;
mail.Priority = MailPriority.High;
SmtpClient client = new SmtpClient();
client.Credentials = new System.Net.NetworkCredential("from gmail address", "your gmail account password");
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
try
{
client.Send(mail);
Page.RegisterStartupScript("UserMsg", "<script>alert('Successfully Send...');if(alert){ window.location='SendMail.aspx';}</script>");
}
catch (Exception ex)
{
Exception ex2 = ex;
string errorMessage = string.Empty;
while (ex2 != null)
{
errorMessage += ex2.ToString();
ex2 = ex2.InnerException;
}
Page.RegisterStartupScript("UserMsg", "<script>alert('Sending Failed...');if(alert){ window.location='SendMail.aspx';}</script>");
}
}
Compiler knows by type cast. Given a void *x
:
x+1
adds one byte to x
, pointer goes to byte x+1
(int*)x+1
adds sizeof(int)
bytes, pointer goes to byte x + sizeof(int)
(float*)x+1
addres sizeof(float)
bytes,
etc.Althought the first item is not portable and is against the Galateo of C/C++, it is nevertheless C-language-correct, meaning it will compile to something on most compilers possibly necessitating an appropriate flag (like -Wpointer-arith)
Example as per doc
@Component({
selector: 'date-pipe',
template: `<div>
<p>Today is {{today | date}}</p>
<p>Or if you prefer, {{today | date:'fullDate'}}</p>
<p>The time is {{today | date:'jmZ'}}</p>
</div>`
})
export class DatePipeComponent {
today: number = Date.now();
}
Template
{{ dateObj | date }} // output is 'Jun 15, 2015'
{{ dateObj | date:'medium' }} // output is 'Jun 15, 2015, 9:43:11 PM'
{{ dateObj | date:'shortTime' }} // output is '9:43 PM'
{{ dateObj | date:'mmss' }} // output is '43:11'
{{dateObj | date: 'dd/MM/yyyy'}} // 15/06/2015
To Use in your component.
@Injectable()
import { DatePipe } from '@angular/common';
class MyService {
constructor(private datePipe: DatePipe) {}
transformDate(date) {
this.datePipe.transform(myDate, 'yyyy-MM-dd'); //whatever format you need.
}
}
In your app.module.ts
providers: [DatePipe,...]
all you have to do is use this service now.
Note that On Error Resume Next
is not set globally. You can put your unsafe part of code eg into a function, which will interrupted immediately if error occurs, and call this function from sub containing precedent OERN
statement.
ErrCatch()
Sub ErrCatch()
Dim Res, CurrentStep
On Error Resume Next
Res = UnSafeCode(20, CurrentStep)
MsgBox "ErrStep " & CurrentStep & vbCrLf & Err.Description
End Sub
Function UnSafeCode(Arg, ErrStep)
ErrStep = 1
UnSafeCode = 1 / (Arg - 10)
ErrStep = 2
UnSafeCode = 1 / (Arg - 20)
ErrStep = 3
UnSafeCode = 1 / (Arg - 30)
ErrStep = 0
End Function
You could run it without the -jar
command line argument if you happen to know the name of the main class you wish to run:
java -classpath .;myjar.jar;lib/referenced-class.jar my.package.MainClass
If perchance you are using linux, you should use ":" instead of ";" in the classpath.
Read the Advanced Bash-Scripting Guide Chapter 19. Here Documents.
Here's an example which will write the contents to a file at /tmp/yourfilehere
cat << EOF > /tmp/yourfilehere
These contents will be written to the file.
This line is indented.
EOF
Note that the final 'EOF' (The LimitString
) should not have any whitespace in front of the word, because it means that the LimitString
will not be recognized.
In a shell script, you may want to use indentation to make the code readable, however this can have the undesirable effect of indenting the text within your here document. In this case, use <<-
(followed by a dash) to disable leading tabs (Note that to test this you will need to replace the leading whitespace with a tab character, since I cannot print actual tab characters here.)
#!/usr/bin/env bash
if true ; then
cat <<- EOF > /tmp/yourfilehere
The leading tab is ignored.
EOF
fi
If you don't want to interpret variables in the text, then use single quotes:
cat << 'EOF' > /tmp/yourfilehere
The variable $FOO will not be interpreted.
EOF
To pipe the heredoc through a command pipeline:
cat <<'EOF' | sed 's/a/b/'
foo
bar
baz
EOF
Output:
foo
bbr
bbz
... or to write the the heredoc to a file using sudo
:
cat <<'EOF' | sed 's/a/b/' | sudo tee /etc/config_file.conf
foo
bar
baz
EOF
It depends on what function you want to run. If you need something done on server side, like querying a database or setting something in the session or anything that can not be done on client side, you need AJAX, else you can do it on client-side with JavaScript. Don't make the server work when you can do what you need to do on client side.
jQuery provides an easy way to do ajax : http://api.jquery.com/jQuery.ajax/
if (pictureBox1.Image != null)
{
pictureBox1.Image.Dispose();
pictureBox1.Image = null;
}
I suppose repr function can help you:
s = 't\n'
repr(s)
"'t\\n'"
repr(s)[1:-1]
't\\n'
It's working with
Set WSHELL = CreateObject("Wscript.Shell")
WSHELL.Exec("Application_Path")
But what should be the parameter in case we want to enter the application name only
e.g in case of Internet Explorer
WSHELL.Run("iexplore")
The download attribute is new for the <a>
tag in HTML5
<a href="http://www.odin.com/form.pdf" download>Download Form</a>
or
<a href="http://www.odin.com/form.pdf" download="Form">Download Form</a>
I prefer the first one it is preferable in respect to any extension.
Modern browsers support native querySelectorAll
so you can do:
document.querySelectorAll('[data-foo="value"]');
https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll
Details about browser compatibility:
You can use jQuery to support obsolete browsers (IE9 and older):
$('[data-foo="value"]');
Change the minDate dynamically
.datepicker("destroy")
For example
<script>
$(function() {
$( "#datepicker" ).datepicker("destroy");
$( "#datepicker" ).datepicker();
});
</script>
<p>Date: <input type="text" id="datepicker" /></p>
The code:
// x>=1;
unsigned func(unsigned x) {
double d = x ;
int p= (*reinterpret_cast<long long*>(&d) >> 52) - 1023;
printf( "The left-most non zero bit of %d is bit %d\n", x, p);
}
Or get the integer part of FPU instruction FYL2X (Y*Log2 X) by setting Y=1
We have a winXP build pc, and use Visual Build Pro 6 to build our software. since some of our developers use VS 2010 the project files now contain reference to "tool version 4.0" and from what I can tell, this tells Visual Build it needs to find a sdk7.x somewhere, even though we only build for .NET 3.5. This caused it not to find lc.exe. I tried to fool it by pointing all the macros to the 6.0A sdk that came with VS2008 which is installed on the pc, but that did not work.
I eventually got it working by downloading and installing sdk 7.1. I then created a registry key for 7.0A and pointed the install path to the install path of the 7.1 sdk. now it happily finds a compatible "lc.exe" and all the code compiles fine. I have a feeling I will now also be able to compile .NET 4.0 code even though VS2010 is not installed, but I have not tried that yet.
list()
is inherently slower than []
, because
there is symbol lookup (no way for python to know in advance if you did not just redefine list to be something else!),
there is function invocation,
then it has to check if there was iterable argument passed (so it can create list with elements from it) ps. none in our case but there is "if" check
In most cases the speed difference won't make any practical difference though.
Since iOS 11, you can use the native framework called PDFKit for displaying and manipulating PDFs.
After importing PDFKit, you should initialize a PDFView
with a local or a remote URL and display it in your view.
if let url = Bundle.main.url(forResource: "example", withExtension: "pdf") {
let pdfView = PDFView(frame: view.frame)
pdfView.document = PDFDocument(url: url)
view.addSubview(pdfView)
}
Read more about PDFKit in the Apple Developer documentation.
Here's the solution that works fine for me.
Here's a function that is also based on cloneNode
, but with an option to clone only the parent node and move all the children (to preserve their event listeners):
function recreateNode(el, withChildren) {
if (withChildren) {
el.parentNode.replaceChild(el.cloneNode(true), el);
}
else {
var newEl = el.cloneNode(false);
while (el.hasChildNodes()) newEl.appendChild(el.firstChild);
el.parentNode.replaceChild(newEl, el);
}
}
Remove event listeners on one element:
recreateNode(document.getElementById("btn"));
Remove event listeners on an element and all of its children:
recreateNode(document.getElementById("list"), true);
If you need to keep the object itself and therefore can't use cloneNode
, then you have to wrap the addEventListener
function and track the listener list by yourself, like in this answer.
I found the easiest way to check if installed was to:
cmd
, then OK)powershell
then hit return. You should then get the PowerShell PS
prompt:C:\Users\MyUser>powershell
Windows PowerShell
Copyright (C) 2009 Microsoft Corporation. All rights reserved.
PS C:\Users\MyUser>
You can then check the version from the PowerShell prompt by typing $PSVersionTable.PSVersion
:
PS C:\Users\MyUser> $PSVersionTable.PSVersion
Major Minor Build Revision
----- ----- ----- --------
2 0 -1 -1
PS C:\Users\MyUser>
Type exit
if you want to go back to the command prompt (exit
again if you want to also close the command prompt).
To run scripts, see http://ss64.com/ps/syntax-run.html.
High quality for Mac OS works perfectly!
ffmpeg -i input.wma -q:a 0 output.mp3
Table with Fixed Header
<table cellspacing="0" cellpadding="0" border="0" width="325">_x000D_
<tr>_x000D_
<td>_x000D_
<table cellspacing="0" cellpadding="1" border="1" width="300" >_x000D_
<tr style="color:white;background-color:grey">_x000D_
<th>Header 1</th>_x000D_
<th>Header 2</th>_x000D_
</tr>_x000D_
</table>_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
<div style="width:320px; height:80px; overflow:auto;">_x000D_
<table cellspacing="0" cellpadding="1" border="1" width="300" >_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Result
This is working in all browser
Demo jsfiddle http://jsfiddle.net/nyCKE/6302/
I was investigating this problem with regard to login-off via Azure Access Control Services, and wasn't able to connect head and tails of anything.
Then, stumbled over this post https://blogs.msdn.microsoft.com/ieinternals/2011/03/10/beware-cookie-sharing-in-cross-zone-scenarios/
In short, IE doesn't share cookies across zones (eg. Internet vs. Trusted sites).
So, if your IFrame target and html page are in different zone's P3P won't help with anything.
Try Case
SELECT stock.name,
CASE
WHEN stock.quantity <20 THEN 'Buy urgent'
ELSE 'There is enough'
END
FROM stock
In short: I don't think you can, but there seems to be a workaround:.
If you take a look into the Android Resource here:
http://developer.android.com/guide/topics/resources/string-resource.html
You see than under the array section (string array, at least), the "RESOURCE REFERENCE" (as you get from an XML) does not specify a way to address the individual items. You can even try in your XML to use "@array/yourarrayhere". I know that in design time you will get the first item. But that is of no practical use if you want to use, let's say... the second, of course.
HOWEVER, there is a trick you can do. See here:
Referencing an XML string in an XML Array (Android)
You can "cheat" (not really) the array definition by addressing independent strings INSIDE the definition of the array. For example, in your strings.xml:
<string name="earth">Earth</string>
<string name="moon">Moon</string>
<string-array name="system">
<item>@string/earth</item>
<item>@string/moon</item>
</string-array>
By using this, you can use "@string/earth" and "@string/moon" normally in your "android:text" and "android:title" XML fields, and yet you won't lose the ability to use the array definition for whatever purposes you intended in the first place.
Seems to work here on my Eclipse. Why don't you try and tell us if it works? :-)
I was getting the same exact error as well. Here is the fix. When you are specifying where to write to, Android will automatically resolve your path into either /data/
or /mnt/sdcard/
. Let me explain.
If you execute the following statement:
File resolveMe = new File("/data/myPackage/files/media/qmhUZU.jpg");
resolveMe.createNewFile();
It will resolve the path to the root /data/
somewhere higher up in Android.
I figured this out, because after I executed the following code, it was placed automatically in the root /mnt/
without me translating anything on my own.
File resolveMeSDCard = new File("/sdcard/myPackage/files/media/qmhUZU.jpg");
resolveMeSDCard.createNewFile();
A quick fix would be to change your following code:
File f = new File(getLocalPath().replace("/data/data/", "/"));
Hope this helps
I had this problem working with pycurl and I solved it using
c.setopt(pycurl.HTTP_VERSION, pycurl.CURL_HTTP_VERSION_1_0)
like Eric Caron says.
This is an issue distinct to Chrome, but there are two paths you can take to fix it.
I noticed the error once I added this specific header to my PHP script.
header('Content-Type: application/json');
The error appears to be related to PHP sessions when sending response headers. So according to chromium bug report 424599, this was fixed and you can just update to a newer version of Chrome. But if for some reason you can't or don't want to update, the workaround would be to remove these response headers from your PHP script if possible (that's what I did because it wasn't required).
Slight modification to this @CodeMaker 's answer, for anyone like me who is trying to modify a MongoDB service to use authentication.
When I looked at the "Path to executable" in "Services" the executed line already contained speech marks. So I had to make minor modification to his example.
To be specific.
For me the path was (note the speech marks)
"C:\Program Files\MongoDB\Server\4.2\bin\mongod.exe" --config "C:\Program Files\MongoDB\Server\4.2\bin\mongod.cfg" --service
In a command line type
sc config MongoDB binPath= "<Modified string with \" to replace ">"
In my case this was
sc config MongoDB binPath= "\"C:\Program Files\MongoDB\Server\4.2\bin\mongod.exe\" --config \"C:\Program Files\MongoDB\Server\4.2\bin\mongod.cfg\" --service -- auth"
To repair a corrupt database you can use the sqlite3 commandline utility. Type in the following commands in a shell after setting the environment variables:
cd $DATABASE_LOCATION
echo '.dump'|sqlite3 $DB_NAME|sqlite3 repaired_$DB_NAME
mv $DB_NAME corrupt_$DB_NAME
mv repaired_$DB_NAME $DB_NAME
This code helped me recover a SQLite database I use as a persistent store for Core Data and which produced the following error upon save:
Could not save: NSError 259 in Domain NSCocoaErrorDomain { NSFilePath = mydata.db NSUnderlyingException = Fatal error. The database at mydata.db is corrupted. SQLite error code:11, 'database disk image is malformed' }
Use the entire path, like this:
exportcert -alias androiddebugkey -keystore ~/.android
/debug.keystore | "C:\openssl\bin\openssl.exe" sha1 -binary | "C:\openssl\bin\op
enssl.exe" base64
It worked for me.
Kill the braces.
var defaults = {
backgroundcolor: '#000',
color: '#fff',
weekdays: ['sun','mon','tue','wed','thu','fri','sat']
};
You can use readelf
to explore the ELF headers. readelf -d
will list the direct dependencies as NEEDED
sections.
$ readelf -d elfbin
Dynamic section at offset 0xe30 contains 22 entries:
Tag Type Name/Value
0x0000000000000001 (NEEDED) Shared library: [libssl.so.1.0.0]
0x0000000000000001 (NEEDED) Shared library: [libc.so.6]
0x000000000000000c (INIT) 0x400520
0x000000000000000d (FINI) 0x400758
...
You are probably behind a firewall. Try cloning via https – that has a higher chance of not being blocked:
git clone https://github.com/angular/angular-phonecat.git
For AWS users who work with Amazon SES in conjunction with PHPMailer, this error also appears when your "from" mail sender isn't a verified sender.
To add a verified sender:
Log in to your Amazon AWS console: https://console.aws.amazon.com
Select "Amazon SES" from your list of available AWS applications
Select, under "Verified Senders", the "Email Addresses" --> "Verify a new email address"
Navigate to that new sender's email, click the confirmation e-mail's link.
And you're all set.
You can use File.WriteAllBytes
parser.add_argument
also has a switch required. You can use required=False
.
Here is a sample snippet with Python 2.7:
parser = argparse.ArgumentParser(description='get dir')
parser.add_argument('--dir', type=str, help='dir', default=os.getcwd(), required=False)
args = parser.parse_args()
You need also $sce.trustAsResourceUrl
or it won't open the website inside the iframe:
angular.module('myApp', [])_x000D_
.controller('dummy', ['$scope', '$sce', function ($scope, $sce) {_x000D_
_x000D_
$scope.url = $sce.trustAsResourceUrl('https://www.angularjs.org');_x000D_
_x000D_
$scope.changeIt = function () {_x000D_
$scope.url = $sce.trustAsResourceUrl('https://docs.angularjs.org/tutorial');_x000D_
}_x000D_
}]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="dummy">_x000D_
<iframe ng-src="{{url}}" width="300" height="200"></iframe>_x000D_
<br>_x000D_
<button ng-click="changeIt()">Change it</button>_x000D_
</div>
_x000D_
I use ngx-bootstrap for my project.
You can find the demo here
The github is here
How to use:
Install ngx-bootstrap
Import to your module
// RECOMMENDED (doesn't work with system.js) import { ModalModule } from 'ngx-bootstrap/modal'; // or import { ModalModule } from 'ngx-bootstrap'; @NgModule({ imports: [ModalModule.forRoot(),...] }) export class AppModule(){}
<button type="button" class="btn btn-primary" (click)="staticModal.show()">Static modal</button> <div class="modal fade" bsModal #staticModal="bs-modal" [config]="{backdrop: 'static'}" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title pull-left">Static modal</h4> <button type="button" class="close pull-right" aria-label="Close" (click)="staticModal.hide()"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> This is static modal, backdrop click will not close it. Click <b>×</b> to close modal. </div> </div> </div> </div>
You have to use v-html directive for displaying html content inside a vue component
<div v-html="html content data property"></div>
<td style = "display:none" >
<p> Content display none </p>
</td>
or
<td style="visibility:hidden"> Your content is hidden </td>
Notice that: 2 those ways are differnce. You should try it to check the result.
The MSDN documentation for environment variables tells you what to do:
To programmatically add or modify system environment variables, add them to the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment registry key, then broadcast a WM_SETTINGCHANGE message with lParam set to the string "Environment". This allows applications, such as the shell, to pick up your updates.
You will of course need admin rights to do this. I know of no way to broadcast a windows message from Windows batch so you'll need to write a small program to do this.
Use the power of Python and lean on one of the best libraries around: requests
import requests
r = requests.get('https://my.website.com/rest/path', auth=('myusername', 'mybasicpass'))
print(r.text)
Variable r (requests response) has a lot more parameters that you can use. Best thing is to pop into the interactive interpreter and play around with it, and/or read requests docs.
ubuntu@hostname:/home/ubuntu$ python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> r = requests.get('https://my.website.com/rest/path', auth=('myusername', 'mybasicpass'))
>>> dir(r)
['__attrs__', '__bool__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_content', '_content_consumed', 'apparent_encoding', 'close', 'connection', 'content', 'cookies', 'elapsed', 'encoding', 'headers', 'history', 'iter_content', 'iter_lines', 'json', 'links', 'ok', 'raise_for_status', 'raw', 'reason', 'request', 'status_code', 'text', 'url']
>>> r.content
b'{"battery_status":0,"margin_status":0,"timestamp_status":null,"req_status":0}'
>>> r.text
'{"battery_status":0,"margin_status":0,"timestamp_status":null,"req_status":0}'
>>> r.status_code
200
>>> r.headers
CaseInsensitiveDict({'x-powered-by': 'Express', 'content-length': '77', 'date': 'Fri, 20 May 2016 02:06:18 GMT', 'server': 'nginx/1.6.3', 'connection': 'keep-alive', 'content-type': 'application/json; charset=utf-8'})
Maybe you can try pyshmht, sharing memory based hash table extension for Python.
Notice
It's not fully tested, just for your reference.
It currently lacks lock/sem mechanisms for multiprocessing.
If it's already in the classpath, then just obtain it from the classpath instead of from the disk file system. Don't fiddle with relative paths in java.io.File
. They are dependent on the current working directory over which you have totally no control from inside the Java code.
Assuming that ListStopWords.txt
is in the same package as your FileLoader
class, then do:
URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.getPath());
Or if all you're ultimately after is actually an InputStream
of it:
InputStream input = getClass().getResourceAsStream("ListStopWords.txt");
This is certainly preferred over creating a new File()
because the url
may not necessarily represent a disk file system path, but it could also represent virtual file system path (which may happen when the JAR is expanded into memory instead of into a temp folder on disk file system) or even a network path which are both not per definition digestable by File
constructor.
If the file is -as the package name hints- is actually a fullworthy properties file (containing key=value
lines) with just the "wrong" extension, then you could feed the InputStream
immediately to the load()
method.
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("ListStopWords.txt"));
Note: when you're trying to access it from inside static
context, then use FileLoader.class
(or whatever YourClass.class
) instead of getClass()
in above examples.
Delete Without Rebooting
The OP's question indeed has been answered extensively, including how to avoid rebooting through powershell, vbscript, or you name it.
However, if you need to stick to cmd commands only and don't have the luxury of being able to call powershell or vbscript, you could use the following approach:
rem remove from current cmd instance
SET FOOBAR=
rem remove from the registry if it's a user variable
REG delete HKCU\Environment /F /V FOOBAR
rem remove from the registry if it's a system variable
REG delete "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /F /V FOOBAR
rem tell Explorer.exe to reload the environment from the registry
SETX DUMMY ""
rem remove the dummy
REG delete HKCU\Environment /F /V DUMMY
So the magic here is that by using "setx" to assign something to a variable you don't need (in my example DUMMY), you force Explorer.exe to reread the variables from the registry, without needing powershell. You then clean up that dummy, and even though that one will stay in Explorer's environment for a little while longer, it will probably not harm anyone.
Or if after deleting variables you need to set new ones, then you don't even need any dummy. Just using SETX to set the new variables will automatically clear the ones you just removed from any new cmd tasks that might get started.
Background information: I just used this approach successfully to replace a set of user variables by system variables of the same name on all of the computers at my job, by modifying an existing cmd script. There are too many computers to do it manually, nor was it practical to copy extra powershell or vbscripts to all of them. The reason I urgently needed to replace user with system variables was that user variables get synchronized in roaming profiles (didn't think about that), so multiple machines using the same windows login but needing different values, got mixed up.
This solution is better. Some of the more popular options on here don't correct handle checkboxes when the checkbox is not checked.
getData: function(element){
//@todo may need additional logic for radio buttons
var select = $(element).find('select');
var input = $(element).find('input');
var inputs = $.merge(select,input);
var data = {};
//console.log(input,'input');
$.each(inputs,function(){
if($(this).attr('type') != undefined){
switch($(this).attr('type')){
case 'checkbox':
data[$(this).attr('name')] = ( ($(this).attr('checked') == 'checked') ? $(this).val():0 );
break;
default:
data[$(this).attr('name')] = $(this).val();
break;
}
}
else{
data[$(this).attr('name')] = $(this).val();
}
})
return data;
}
With adb, you can install GApps and ARM Support zips without a drag & drop. emuking from XDA Developers has instructions for it:
I used 4.2.2, which is acceptable for my testing purposes. I then extracted both zip's "/system/..." folders to a folder on my desktop. In cmd prompt I used the following commands (step 1 is optional and for verification that adb is working):
You'll have to change the folder name in "adb push" line to where you actually extracted both zip files. After doing it, I recommend you to "adb reboot" the device.
You can just use following git command which can revert back all the uncommitted changes made in your repository:
git checkout .
Example:
ABC@ABC-PC MINGW64 /c/xampp/htdocs/pod_admin (master)
$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: application/controllers/Drivers.php
modified: application/views/drivers/add.php
modified: application/views/drivers/load_driver_info.php
modified: uploads/drivers/drivers.xlsx
no changes added to commit (use "git add" and/or "git commit -a")
ABC@ABC-PC MINGW64 /c/xampp/htdocs/pod_admin (master)
$ git checkout .
ABC@ABC-PC MINGW64 /c/xampp/htdocs/pod_admin (master)
$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
nothing to commit, working tree clean
Nothing fancy? Try MessageBox
$cfg['Servers'][$i]['auth_type'] = 'cookie';
should work.
From the manual:
auth_type = 'cookie' prompts for a MySQL username and password in a friendly HTML form. This is also the only way by which one can log in to an arbitrary server (if $cfg['AllowArbitraryServer'] is enabled). Cookie is good for most installations (default in pma 3.1+), it provides security over config and allows multiple users to use the same phpMyAdmin installation. For IIS users, cookie is often easier to configure than http.
You need only to write:
GRANT DBA TO NewDBA;
Because this already makes the user a DB Administrator
I founded the problem:
Just insert the folder without the executable file.
so Instead of:
C:\Program Files (x86)\SumatraPDF\SumatraPDF.exe
you have to write this:
C:\Program Files (x86)\SumatraPDF\
Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.
It will start from -9,223,372,036,854,775,808
Long.MIN_VALUE.
Each numeric type has its own value. See TypeCode enum definition: https://docs.microsoft.com/en-us/dotnet/api/system.typecode?view=netframework-4.8 Based on this info, all your numeric type-values are in the range from 5 to 15. This means, you can write the condition-check like this:
$typeValue = $x.getTypeCode().value__
if ($typeValue -ge 5 -and $typeValue -le 15) {"x has a numeric type!"}
There may be one or multiple reasons if you are not able to connect to MAC OS X MySQL server with MySQL-workbench.
When you press 'test connection' you might see this error. This could be explained briefly if you go step by step through 'Configure server management..' On the basis of the red crosses you can filter out the real problem.
The most common problems are associated with the installation of MySQL-server. Few people either forget to install the server prior to installing MySQL-workbench. Some others would install a part of the product. Please check whether you have also installed all the 3 parts that comes with the MySQL-Server dmg(disk image) file which contains mysql-server package. Those 3 parts are: MySQL server, preference pane and startup item.
Note: If you haven't selected preference pane then you won't be able to start mysql server instance from the System preferences.
After you make sure that you have installed each item then you can check server instance of your native mysql-server. Open System preferences from dock and click MySQL. Then click Start MySQL Server to start the server instance. If the server instance is stopped, then MySQL-workbench won't be able to connect to the MySQL server.
If you are still facing issue, then you need to check the port of the connection which you are making. Default port is '3307' and NOT '3306'. You can check it with using the following command in mysql terminal:
SHOW GLOBAL VARIABLES LIKE 'PORT';
Please note that this process helps you to connect to the local instance. If you have to connect to a remote server, then you have to enter that specific IP and Port. Contact your server's administrator if you are facing the issue. As this question specifically states that the problem is related to connecting to the local instance, I am not writing checks that you may need to ensure.
One more thing to check is that you have spelled the named instance correctly!
This article is very helpful in troubleshooting connection problems: How to Troubleshoot Connecting to the SQL Server Database Engine
If you were dealing with, given two ranges [x1:x2]
and [y1:y2]
, natural / anti-natural order ranges at the same time where:
x1 <= x2 && y1 <= y2
or x1 >= x2 && y1 >= y2
then you may want to use this to check:
they are overlapped <=> (y2 - x1) * (x2 - y1) >= 0
where only four operations are involved:
Where is the Documents Directory for the iOS 8 Simulator
You may have noticed that the iPhone Simulator has changed with Xcode 6, and with it – of course – the path to your simulated apps’ Documents Directory. At times we may need to take a look at it.
Finding that path is not as easy as it was once, namely Library/Application Support/iPhone Simulator/7.1/Applications/ followed by a cryptic number representing your app.
As of Xcode 6 and iOS 8 you’ll find it here: Library/Developer/CoreSimulator/Devices/cryptic number/data/Containers/Data/Application/cryptic number
http://pinkstone.co.uk/where-is-the-documents-directory-for-the-ios-8-simulator/
For Latest Info About SSIS > https://docs.microsoft.com/en-us/sql/integration-services/sql-server-integration-services
From the above referenced site:
Microsoft Integration Services is a platform for building enterprise-level data integration and data transformations solutions. Use Integration Services to solve complex business problems by copying or downloading files, loading data warehouses, cleansing and mining data, and managing SQL Server objects and data.
Integration Services can extract and transform data from a wide variety of sources such as XML data files, flat files, and relational data sources, and then load the data into one or more destinations.
Integration Services includes a rich set of built-in tasks and transformations, graphical tools for building packages, and the Integration Services Catalog database, where you store, run, and manage packages.
You can use the graphical Integration Services tools to create solutions without writing a single line of code. You can also program the extensive Integration Services object model to create packages programmatically and code custom tasks and other package objects.
Getting Started with SSIS - http://msdn.microsoft.com/en-us/sqlserver/bb671393.aspx
If you are Integration Services Information Worker - http://msdn.microsoft.com/en-us/library/ms141667.aspx
If you are Integration Services Administrator - http://msdn.microsoft.com/en-us/library/ms137815.aspx
If you are Integration Services Developer - http://msdn.microsoft.com/en-us/library/ms137709.aspx
If you are Integration Services Architect - http://msdn.microsoft.com/en-us/library/ms142161.aspx
Overview of SSIS - http://msdn.microsoft.com/en-us/library/ms141263.aspx
Integration Services How-to Topics - http://msdn.microsoft.com/en-us/library/ms141767.aspx
There are two solutions:
Formatter
is more recent even though it takes over printf()
which is 40 years old...
Your placeholder as you currently define it is one MessageFormat
can use, but why use an antique technique? ;) Use Formatter
.
There is all the more reason to use Formatter
that you don't need to escape single quotes! MessageFormat
requires you to do so. Also, Formatter
has a shortcut via String.format()
to generate strings, and PrintWriter
s have .printf()
(that includes System.out
and System.err
which are both PrintWriter
s by default)
For right to left (entry animation) and left to right (exit animation):
styles.xml:
<style name="CustomDialog" parent="@android:style/Theme.Dialog">
<item name="android:windowAnimationStyle">@style/CustomDialogAnimation</item>
</style>
<style name="CustomDialogAnimation">
<item name="android:windowEnterAnimation">@anim/translate_left_side</item>
<item name="android:windowExitAnimation">@anim/translate_right_side</item>
</style>
Create two files in res/anim/:
translate_right_side.xml:
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0%" android:toXDelta="100%"
android:fromYDelta="0%" android:toYDelta="0%"
android:duration="600"/>
translate_left_side.xml:
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="600"
android:fromXDelta="100%"
android:toXDelta="0%"/>
In you Fragment/Activity:
Dialog dialog = new Dialog(getActivity(), R.style.CustomDialog);
Here's one way in XSLT 2
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="text()"> <xsl:value-of select="translate(.,'"','''')"/> </xsl:template> </xsl:stylesheet>
Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:variable name="apos">'</xsl:variable> <xsl:template match="text()"> <xsl:value-of select="translate(.,'"',$apos)"/> </xsl:template> </xsl:stylesheet>
Here's some info if someone comes upon this in 2019.
I think reduce vs map + filter might be somewhat dependent on what you need to loop through. Not sure on this but reduce does seem to be slower.
One thing is for sure - if you're looking for performance improvements the way you write the code is extremely important!
Here a JS perf test that shows the massive improvements when typing out the code fully rather than checking for "falsey" values (e.g. if (string) {...}
) or returning "falsey" values where a boolean is expected.
Hope this helps someone
When the DOM is finished loading you can add your code in the $(document).ready()
function.
Remove the onclick from here:
<input type="submit" name="submit" value="Submit" onClick="PopUp()" />
Try this:
$(document).ready(function(){
setTimeout(function(){
PopUp();
},5000); // 5000 to load it after 5 seconds from page load
});
You could set the width of the abbrev column to a fixed pixel width, then set the width of the description column to the width of the DataGridView, minus the sum of the widths of the other columns and some extra margin (if you want to prevent a horizontal scrollbar from appearing on the DataGridView):
dataGridView1.Columns[1].Width = 108; // or whatever width works well for abbrev
dataGridView1.Columns[2].Width =
dataGridView1.Width
- dataGridView1.Columns[0].Width
- dataGridView1.Columns[1].Width
- 72; // this is an extra "margin" number of pixels
If you wanted the description column to always take up the "remainder" of the width of the DataGridView, you could put something like the above code in a Resize
event handler of the DataGridView.
var testAwait = function () {
var promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Inside test await');
}, 1000);
});
return promise;
}
var asyncFunction = async function() {
await testAwait().then((data) => {
console.log(data);
})
return 'hello asyncFunction';
}
asyncFunction().then((data) => {
console.log(data);
});
//Inside test await
//hello asyncFunction
toEqual()
compares values if Primitive or contents if Objects.
toBe()
compares references.
Following code / suite should be self explanatory :
describe('Understanding toBe vs toEqual', () => {
let obj1, obj2, obj3;
beforeEach(() => {
obj1 = {
a: 1,
b: 'some string',
c: true
};
obj2 = {
a: 1,
b: 'some string',
c: true
};
obj3 = obj1;
});
afterEach(() => {
obj1 = null;
obj2 = null;
obj3 = null;
});
it('Obj1 === Obj2', () => {
expect(obj1).toEqual(obj2);
});
it('Obj1 === Obj3', () => {
expect(obj1).toEqual(obj3);
});
it('Obj1 !=> Obj2', () => {
expect(obj1).not.toBe(obj2);
});
it('Obj1 ==> Obj3', () => {
expect(obj1).toBe(obj3);
});
});
One way to approach the problem is to make a tuple of the dictionary's items:
hash(tuple(my_dict.items()))
I just tried the first answer from Brad Rem and came to this setting in the web.config under BasicHttpBinding:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding bypassProxyOnLocal="False" useDefaultWebProxy="false" proxyAddress="http://127.0.0.1:8888" ...
...
</basicHttpBinding>
</bindings>
...
<system.serviceModel>
Hope this helps someone.
The solution is simple, just use the CascadeType.MERGE
instead of CascadeType.PERSIST
or CascadeType.ALL
.
I have had the same problem and CascadeType.MERGE
has worked for me.
I hope you are sorted.
When you set keys (primary or foreign) you are setting constraints on how they can be used, which in turn limits what you can do with them. If you really want to alter the column, you could re-create the table without the constraints, although I'd recommend against it. Generally speaking, if you have a situation in which you want to do something, but it is blocked by a constraint, it's best resolved by changing what you want to do rather than the constraint.
A comment from Tomasz Madeyski is what fixed my problem... he tells that exists a bug on SetDefaultCredential, him says:
"The issue is that in UseDefaultCredentials setter there is this code: this.transport.Credentials = value ? (ICredentialsByHost) CredentialCache.DefaultNetworkCredentials : (ICredentialsByHost) null; which overrides credentials set by Credentials setter. For me it looks like SmtpClient's bug"
if you put smtpClient.UseDefaultCredentials = false
after set credentials... this line set to null those credentials...
I had to add thymeleaf dependency to pom.xml. Without this dependency Spring boot didn't find static resources.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Transparency can be coded in the color argument as well. It is just two more hex numbers coding a transparency between 0 (fully transparent) and 255 (fully visible). I once wrote this function to add transparency to a color vector, maybe it is usefull here?
addTrans <- function(color,trans)
{
# This function adds transparancy to a color.
# Define transparancy with an integer between 0 and 255
# 0 being fully transparant and 255 being fully visable
# Works with either color and trans a vector of equal length,
# or one of the two of length 1.
if (length(color)!=length(trans)&!any(c(length(color),length(trans))==1)) stop("Vector lengths not correct")
if (length(color)==1 & length(trans)>1) color <- rep(color,length(trans))
if (length(trans)==1 & length(color)>1) trans <- rep(trans,length(color))
num2hex <- function(x)
{
hex <- unlist(strsplit("0123456789ABCDEF",split=""))
return(paste(hex[(x-x%%16)/16+1],hex[x%%16+1],sep=""))
}
rgb <- rbind(col2rgb(color),trans)
res <- paste("#",apply(apply(rgb,2,num2hex),2,paste,collapse=""),sep="")
return(res)
}
Some examples:
cols <- sample(c("red","green","pink"),100,TRUE)
# Fully visable:
plot(rnorm(100),rnorm(100),col=cols,pch=16,cex=4)
# Somewhat transparant:
plot(rnorm(100),rnorm(100),col=addTrans(cols,200),pch=16,cex=4)
# Very transparant:
plot(rnorm(100),rnorm(100),col=addTrans(cols,100),pch=16,cex=4)
Use an array or vector of strings with matching values:
char *ErrorTypes[] =
{
"errorA",
"errorB",
"errorC"
};
cout << ErrorTypes[anError];
EDIT: The solution above is applicable when the enum is contiguous, i.e. starts from 0 and there are no assigned values. It will work perfectly with the enum in the question.
To further proof it for the case that enum doesn't start from 0, use:
cout << ErrorTypes[anError - ErrorA];
Do you mean like this?
var hello1 = document.getElementById('hello1');
hello1.id = btoa(hello1.id);
To further the example, say you wanted to get all elements with the class 'abc'. We can use querySelectorAll()
to accomplish this:
HTML
<div class="abc"></div>
<div class="abc"></div>
JS
var abcElements = document.querySelectorAll('.abc');
// Set their ids
for (var i = 0; i < abcElements.length; i++)
abcElements[i].id = 'abc-' + i;
This will assign the ID 'abc-<index number>'
to each element. So it would come out like this:
<div class="abc" id="abc-0"></div>
<div class="abc" id="abc-1"></div>
To create an element and assign an id
we can use document.createElement()
and then appendChild()
.
var div = document.createElement('div');
div.id = 'hello1';
var body = document.querySelector('body');
body.appendChild(div);
Update
You can set the id
on your element like this if your script is in your HTML file.
<input id="{{str(product["avt"]["fto"])}}" >
<span>New price :</span>
<span class="assign-me">
<script type="text/javascript">
var s = document.getElementsByClassName('assign-me')[0];
s.id = btoa({{str(produit["avt"]["fto"])}});
</script>
Your requirements still aren't 100% clear though.
mydata$sCode == "CA"
will return a boolean array, with a TRUE
value everywhere that the condition is met. To illustrate:
> mydata = data.frame(sCode = c("CA", "CA", "AC"))
> mydata$sCode == "CA"
[1] TRUE TRUE FALSE
There are a couple of ways to deal with this:
sum(mydata$sCode == "CA")
, as suggested in the comments; because
TRUE
is interpreted as 1 and FALSE
as 0, this should return the
numer of TRUE
values in your vector.
length(which(mydata$sCode == "CA"))
; the which()
function
returns a vector of the indices where the condition is met, the
length of which is the count of "CA"
.
Edit to expand upon what's happening in #2:
> which(mydata$sCode == "CA")
[1] 1 2
which()
returns a vector identify each column where the condition is met (in this case, columns 1 and 2 of the dataframe). The length()
of this vector is the number of occurences.
TypeError: Cannot read property 'then' of undefined when calling a Django service using AngularJS.
If you are calling a Python service, the code will look like below:
this.updateTalentSupplier=function(supplierObj){
var promise = $http({
method: 'POST',
url: bbConfig.BWS+'updateTalentSupplier/',
data:supplierObj,
withCredentials: false,
contentType:'application/json',
dataType:'json'
});
return promise; //Promise is returned
}
We are using MongoDB as the database(I know it doesn't matter. But if someone is searching with MongoDB + Python (Django) + AngularJS the result should come.