If Age and Palt are columns in the same Table, you can count(*) all tasks and sum only late ones like this:
select ks,
count(*) tasks,
sum(case when Age > Palt then 1 end) late
from Table
group by ks
This script worked for me:
DELETE t
FROM table t
INNER JOIN join_table jt ON t.fk_column = jt.id
WHERE jt.comdition_column…;
You can use jQuery's $.Deferred
var FunctionOne = function () {
// create a deferred object
var r = $.Deferred();
// do whatever you want (e.g. ajax/animations other asyc tasks)
setTimeout(function () {
// and call `resolve` on the deferred object, once you're done
r.resolve();
}, 2500);
// return the deferred object
return r;
};
// define FunctionTwo as needed
var FunctionTwo = function () {
console.log('FunctionTwo');
};
// call FunctionOne and use the `done` method
// with `FunctionTwo` as it's parameter
FunctionOne().done(FunctionTwo);
you could also pack multiple deferreds together:
var FunctionOne = function () {
var
a = $.Deferred(),
b = $.Deferred();
// some fake asyc task
setTimeout(function () {
console.log('a done');
a.resolve();
}, Math.random() * 4000);
// some other fake asyc task
setTimeout(function () {
console.log('b done');
b.resolve();
}, Math.random() * 4000);
return $.Deferred(function (def) {
$.when(a, b).done(function () {
def.resolve();
});
});
};
I had a same problem and this fixed it:
You should add:
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Lib\x64
for 64 bit system
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Lib
for 32 bit system
in Property Manager
>Linker
>General
>Additional Library Directories
You might try passing actual types instead of strings.
import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4']
dtypes = [datetime, datetime, str, float]
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)
But it's going to be really hard to diagnose this without any of your data to tinker with.
And really, you probably want pandas to parse the the dates into TimeStamps, so that might be:
pd.read_csv(file, sep='\t', header=None, names=headers, parse_dates=True)
Use /[^0-9.,]+/
if you want floats.
I have created a new tool to allow you to have true private methods on the prototype https://github.com/TremayneChrist/ProtectJS
Example:
var MyObject = (function () {
// Create the object
function MyObject() {}
// Add methods to the prototype
MyObject.prototype = {
// This is our public method
public: function () {
console.log('PUBLIC method has been called');
},
// This is our private method, using (_)
_private: function () {
console.log('PRIVATE method has been called');
}
}
return protect(MyObject);
})();
// Create an instance of the object
var mo = new MyObject();
// Call its methods
mo.public(); // Pass
mo._private(); // Fail
I actually like MY JavaScript files to be validated, but I definitely don't want to validate and deal with trivial warnings with third party libraries.
That's why I think that turning off validation all together is too drastic. Fortunately with Eclipse, you can selectively remove some JavaScript sources from validation.
Excluded
pattern.Exclusion patterns
box.Browse
button to mention the JavaScript source by name.The information about JavaScript source inclusion/exclusion is saved into .settings/.jsdtscope
file. Do not forget to add it to your SCM.
Here is how configuration looks with jQuery files removed from validation:
Right click on data which you want to store
\path-to-your-android-sdk-folder\platforms\android-xx\data\res
The file system is a tree structure that can be used as a hash map. Your hash table will be a temporary directory, your keys will be filenames, and your values will be file contents. The advantage is that it can handle huge hashmaps, and doesn't require a specific shell.
hashtable=$(mktemp -d)
echo $value > $hashtable/$key
value=$(< $hashtable/$key)
Of course, its slow, but not that slow. I tested it on my machine, with an SSD and btrfs, and it does around 3000 element read/write per second.
Below is a re-write of a previously posted function:
def addBinary(a, b): # Example: a = '11' + b =' 100' returns as '111'.
for ch in a: assert ch in {'0','1'}, 'bad digit: ' + ch
for ch in b: assert ch in {'0','1'}, 'bad digit: ' + ch
sumx = int(a, 2) + int(b, 2)
return bin(sumx)[2:]
The following code allows you to specify the row/column number and get the resulting cell value:
WebDriver driver = new ChromeDriver();
WebElement base = driver.findElement(By.className("Table"));
tableRows = base.findElements(By.tagName("tr"));
List<WebElement> tableCols = tableRows.get([ROW_NUM]).findElements(By.tagName("td"));
String cellValue = tableCols.get([COL_NUM]).getText();
Solution in Kotlin:
val nowInEpoch = Instant.now().epochSecond
Make sure your minimum SDK version is 26.
The solution is:
$(document).ready(function(){
$("#date_pretty").datepicker({
});
var myDate = new Date();
var month = myDate.getMonth() + 1;
var prettyDate = month + '/' + myDate.getDate() + '/' + myDate.getFullYear();
$("#date_pretty").val(prettyDate);
});
Thanks grayghost!
Firstly, Add this android:debuggable="false" in the application tag of the AndroidManifest.xml.
You don't need to harcode android:debuggable="false"
in your application tag. Infact for me studio complaints -
Avoid hardcoding the debug mode; leaving it out allows debug and release builds to automatically assign one less... (Ctrl+F1)
It's best to leave out the android:debuggable attribute from the manifest. If you do, then the tools will automatically insert android:debuggable=true when building an APK to debug on an emulator or device. And when you perform a release build, such as Exporting APK, it will automatically set it to false. If on the other hand you specify a specific value in the manifest file, then the tools will always use it. This can lead to accidentally publishing your app with debug information.
The accepted answer looks somewhat old. For me it asks me to select whether I want debug build or release build.
Go to Build->Generate Signed APK. Select your keystore, provide keystore password etc.
Now you should see a prompt to select release build or debug build
.
For production always select release build!
And you are done. Signed APK exported.
PS : Don't forget to increment your versionCode
in manifest file before uploading to playstore :)
In Xcode 8 - Swift 3:
button.setTitle( "entertext" , for: .normal )
This is because your string does not strictly contain the integers in string format. It has alphanumeric chars in it.
I wish #pragma once
(or something like it) had been in the standard. Include guards aren't a real big deal (but they do seem to be a little difficult to explain to people learning the language), but it seems like a minor annoyance that could have been avoided.
In fact, since 99.98% of the time, the #pragma once
behavior is the desired behavior, it would have been nice if preventing multiple inclusion of a header was automatically handled by the compiler, with a #pragma
or something to allow double including.
But we have what we have (except that you might not have #pragma once
).
I am using JPA (OpenJPA implementation from Apache which is based on the KODO JDO codebase which is 5+ years old and extremely fast/reliable). IMHO anyone who tells you to bypass the specs is giving you bad advice. I put the time in and was definitely rewarded. With either JDO or JPA you can change vendors with minimal changes (JPA has orm mapping so we are talking less than a day to possibly change vendors). If you have 100+ tables like I do this is huge. Plus you get built0in caching with cluster-wise cache evictions and its all good. SQL/Jdbc is fine for high performance queries but transparent persistence is far superior for writing your algorithms and data input routines. I only have about 16 SQL queries in my whole system (50k+ lines of code).
In
x ? "yes" : "no"
the ? declares an if sentence. Here: x represents the boolean condition; The part before the : is the then sentence and the part after is the else sentence.
In, for example,
int?
the ? declares a nullable type, and means that the type before it may have a null value.
The mySQL client by default attempts to connect through a local file called a socket instead of connecting to the loopback address (127.0.0.1) for localhost.
The default location of this socket file, at least on OSX, is /tmp/mysql.sock
.
QUICK, LESS ELEGANT SOLUTION
Create a symlink to fool the OS into finding the correct socket.
ln -s /Applications/MAMP/tmp/mysql/mysql.sock /tmp
PROPER SOLUTION
Change the socket path defined in the startMysql.sh
file in /Applications/MAMP/bin
.
For private schema 'xxx'
in postgresql :
SELECT table_name FROM information_schema.tables
WHERE table_schema = 'xxx' AND table_type = 'BASE TABLE'
Without table_type = 'BASE TABLE'
, you will list tables and views
I advise to not depend on ready made and built in code in .NET framework , try to bring up new solution ..this is what i do..
public bool isAlphaNumeric(string N)
{
bool YesNumeric = false;
bool YesAlpha = false;
bool BothStatus = false;
for (int i = 0; i < N.Length; i++)
{
if (char.IsLetter(N[i]) )
YesAlpha=true;
if (char.IsNumber(N[i]))
YesNumeric = true;
}
if (YesAlpha==true && YesNumeric==true)
{
BothStatus = true;
}
else
{
BothStatus = false;
}
return BothStatus;
}
You need to surround $file = readdir($handle)
with parentheses.
Here you go:
$log_directory = 'your_dir_name_here';
$results_array = array();
if (is_dir($log_directory))
{
if ($handle = opendir($log_directory))
{
//Notice the parentheses I added:
while(($file = readdir($handle)) !== FALSE)
{
$results_array[] = $file;
}
closedir($handle);
}
}
//Output findings
foreach($results_array as $value)
{
echo $value . '<br />';
}
In the v21 of the Support library there is now a solution to this: it's called RoundedBitmapDrawable.
It's basically just like a normal Drawable except you give it a corner radius for the clipping with:
setCornerRadius(float cornerRadius)
So, starting with Bitmap src
and a target ImageView
, it would look something like this:
RoundedBitmapDrawable dr = RoundedBitmapDrawableFactory.create(res, src);
dr.setCornerRadius(cornerRadius);
imageView.setImageDrawable(dr);
For this purpose and if i dont have boolean variable i use the following:
<li th:class="${#strings.contains(content.language,'CZ')} ? active : ''">
if your json format and variables are okay then check your database queries...even if data is saved in db correctly the actual problem might be in there...recheck your queries and try again.. Hope it helps
Take a look at example E of this tutorial -> https://www.postgresqltutorial.com/postgresql-group-by/
You need to call the function on your GROUP BY instead of calling the name of the virtual attribute you created on select.
I was doing what all the answers above recommended and I was getting a column 'year_month' does not exist
error.
What worked for me was:
SELECT
date_trunc('month', created_at), 'MM/YYYY' AS month
FROM
"orders"
GROUP BY
date_trunc('month', created_at)
As the original author of the work around on the connect bug report, there are TWO variants of this message (I've discovered later)
For one variant you use sn.exe (usually if you are doing strong naming) to import the key to the strong naming store.
The other variant for which you use certmgr to import is when you're codesigning for things like click-once deployment (note you can use the same cert for both purposes).
Hope this helps.
Subscript out of Range error occurs when you try to reference an Index for a collection that is invalid.
Most likely, the index in Windows does not actually include .xls. The index for the window should be the same as the name of the workbook displayed in the title bar of Excel.
As a guess, I would try using this:
Windows("Data Sheet - " & ComboBox_Month.Value & " " & TextBox_Year.Value).Activate
XAMPP only offers MySQL (Database Server) & Apache (Webserver) in one setup and you can manage them with the xampp starter.
After the successful installation navigate to your xampp folder and execute the xampp-control.exe
Press the start Button at the mysql row.
Now you've successfully started mysql. Now there are 2 different ways to administrate your mysql server and its databases.
But at first you have to set/change the MySQL Root password. Start the Apache server and type localhost
or 127.0.0.1
in your browser's address bar. If you haven't deleted anything from the htdocs folder the xampp status page appears. Navigate to security settings and change your mysql root password.
Now, you can browse to your phpmyadmin under http://localhost/phpmyadmin
or download a windows mysql client for example navicat lite or mysql workbench. Install it and log in to your mysql server with your new root password.
Let us say your jsfunctions.js file has a function "display" and this file is stored in C:/Scripts/Jsfunctions.js
jsfunctions.js
var display = function(name) {
print("Hello, I am a Javascript display function",name);
return "display function return"
}
Now, in your java code, I would recommend you to use Java8 Nashorn. In your java class,
import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
class Test {
public void runDisplay() {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
try {
engine.eval(new FileReader("C:/Scripts/Jsfunctions.js"));
Invocable invocable = (Invocable) engine;
Object result;
result = invocable.invokeFunction("display", helloWorld);
System.out.println(result);
System.out.println(result.getClass());
} catch (FileNotFoundException | NoSuchMethodException | ScriptException e) {
e.printStackTrace();
}
}
}
Note: Get the absolute path of your javascript file and replace in FileReader() and run the java code. It should work.
I just tried using header("Location: ");
(without any value) and it redirected to the current page.
There are a lot of answer above which will definitely help you but (after 2 days of afford and research on adb memory tools) I think i can help with my opinion too.
As Hackbod says : Thus if you were to take all of the physical RAM actually mapped in to each process, and add up all of the processes, you would probably end up with a number much greater than the actual total RAM. so there is no way you can get exact amount of memory per process.
But you can get close to it by some logic..and I will tell how..
There are some API like
android.os.Debug.MemoryInfo
andActivityManager.getMemoryInfo()
mentioned above which you already might have being read about and used but I will talk about other way
So firstly you need to be a root user to get it work. Get into console with root privilege by executing su
in process and get its output and input stream
. Then pass id\n
(enter) in ouputstream and write it to process output, If will get an inputstream containing uid=0
, you are root user.
Now here is the logic which you will use in above process
When you get ouputstream of process pass you command (procrank, dumpsys meminfo etc...) with \n
instead of id and get its inputstream
and read, store the stream in bytes[ ] ,char[ ] etc.. use raw data..and you are done!!!!!
permission :
<uses-permission android:name="android.permission.FACTORY_TEST"/>
Check if you are root user :
// su command to get root access
Process process = Runtime.getRuntime().exec("su");
DataOutputStream dataOutputStream =
new DataOutputStream(process.getOutputStream());
DataInputStream dataInputStream =
new DataInputStream(process.getInputStream());
if (dataInputStream != null && dataOutputStream != null) {
// write id to console with enter
dataOutputStream.writeBytes("id\n");
dataOutputStream.flush();
String Uid = dataInputStream.readLine();
// read output and check if uid is there
if (Uid.contains("uid=0")) {
// you are root user
}
}
Execute your command with su
Process process = Runtime.getRuntime().exec("su");
DataOutputStream dataOutputStream =
new DataOutputStream(process.getOutputStream());
if (dataOutputStream != null) {
// adb command
dataOutputStream.writeBytes("procrank\n");
dataOutputStream.flush();
BufferedInputStream bufferedInputStream =
new BufferedInputStream(process.getInputStream());
// this is important as it takes times to return to next line so wait
// else you with get empty bytes in buffered stream
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// read buffered stream into byte,char etc.
byte[] bff = new byte[bufferedInputStream.available()];
bufferedInputStream.read(bff);
bufferedInputStream.close();
}
}
You get a raw data in a single string from console instead of in some instance from any API,which is complex to store as you will need to separate it manually.
This is just a try, please suggest me if I missed something
I suggest Freewall
. It is a cross-browser and responsive jQuery plugin to help you create many types of grid layouts: flexible layouts, images layouts, nested grid layouts, metro style layouts, pinterest like layouts ... with nice CSS3 animation effects and call back events. Freewall is all-in-one solution for creating dynamic grid layouts for desktop, mobile, and tablet.
Home page and document: also found here
.
Try using this code for v3:
gMap = new google.maps.Map(document.getElementById('map'));
gMap.setZoom(13); // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);
Use : '
to open and '
to close.
For example:
: '
This is a
very neat comment
in bash
'
I answered a virtually identical question just the other day: Save CSV files into mysql database
MySQL has a feature LOAD DATA INFILE
, which allows it to import a CSV file directly in a single SQL query, without needing it to be processed in a loop via your PHP program at all.
Simple example:
<?php
$query = <<<eof
LOAD DATA INFILE '$fileName'
INTO TABLE tableName
FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
(field1,field2,field3,etc)
eof;
$db->query($query);
?>
It's as simple as that.
No loops, no fuss. And much much quicker than parsing it in PHP.
MySQL manual page here: http://dev.mysql.com/doc/refman/5.1/en/load-data.html
Hope that helps
Here is MySQL version which prints only one entry where there are duplicates MAX(datetime) in a group.
You could test here http://www.sqlfiddle.com/#!2/0a4ae/1
mysql> SELECT * from topten;
+------+------+---------------------+--------+----------+
| id | home | datetime | player | resource |
+------+------+---------------------+--------+----------+
| 1 | 10 | 2009-04-03 00:00:00 | john | 399 |
| 2 | 11 | 2009-04-03 00:00:00 | juliet | 244 |
| 3 | 10 | 2009-03-03 00:00:00 | john | 300 |
| 4 | 11 | 2009-03-03 00:00:00 | juliet | 200 |
| 5 | 12 | 2009-04-03 00:00:00 | borat | 555 |
| 6 | 12 | 2009-03-03 00:00:00 | borat | 500 |
| 7 | 13 | 2008-12-24 00:00:00 | borat | 600 |
| 8 | 13 | 2009-01-01 00:00:00 | borat | 700 |
| 9 | 10 | 2009-04-03 00:00:00 | borat | 700 |
| 10 | 11 | 2009-04-03 00:00:00 | borat | 700 |
| 12 | 12 | 2009-04-03 00:00:00 | borat | 700 |
+------+------+---------------------+--------+----------+
SELECT *
FROM (
SELECT ord.*,
IF (@prev_home = ord.home, 0, 1) AS is_first_appear,
@prev_home := ord.home
FROM (
SELECT t1.id, t1.home, t1.player, t1.resource
FROM topten t1
INNER JOIN (
SELECT home, MAX(datetime) AS mx_dt
FROM topten
GROUP BY home
) x ON t1.home = x.home AND t1.datetime = x.mx_dt
ORDER BY home
) ord, (SELECT @prev_home := 0, @seq := 0) init
) y
WHERE is_first_appear = 1;
+------+------+--------+----------+-----------------+------------------------+
| id | home | player | resource | is_first_appear | @prev_home := ord.home |
+------+------+--------+----------+-----------------+------------------------+
| 9 | 10 | borat | 700 | 1 | 10 |
| 10 | 11 | borat | 700 | 1 | 11 |
| 12 | 12 | borat | 700 | 1 | 12 |
| 8 | 13 | borat | 700 | 1 | 13 |
+------+------+--------+----------+-----------------+------------------------+
4 rows in set (0.00 sec)
SELECT tt.*
FROM topten tt
INNER JOIN
(
SELECT home, MAX(datetime) AS MaxDateTime
FROM topten
GROUP BY home
) groupedtt ON tt.home = groupedtt.home AND tt.datetime = groupedtt.MaxDateTime
+------+------+---------------------+--------+----------+
| id | home | datetime | player | resource |
+------+------+---------------------+--------+----------+
| 1 | 10 | 2009-04-03 00:00:00 | john | 399 |
| 2 | 11 | 2009-04-03 00:00:00 | juliet | 244 |
| 5 | 12 | 2009-04-03 00:00:00 | borat | 555 |
| 8 | 13 | 2009-01-01 00:00:00 | borat | 700 |
| 9 | 10 | 2009-04-03 00:00:00 | borat | 700 |
| 10 | 11 | 2009-04-03 00:00:00 | borat | 700 |
| 12 | 12 | 2009-04-03 00:00:00 | borat | 700 |
+------+------+---------------------+--------+----------+
7 rows in set (0.00 sec)
Try this :
select replace (colname, char(39)+char(39), '') AS colname FROM .[dbo].[Db Name];
I have achieved the desired result. Example : Input value --> Like '%Pat') '' OR
Want Output --> *Like '%Pat') OR*
using above query achieved the desired result.
We can't because it's expected/required by our customers.
You should be using the dirpath
which you call root
. The dirnames
are supplied so you can prune it if there are folders that you don't wish os.walk
to recurse into.
import os
result = [os.path.join(dp, f) for dp, dn, filenames in os.walk(PATH) for f in filenames if os.path.splitext(f)[1] == '.txt']
Edit:
After the latest downvote, it occurred to me that glob
is a better tool for selecting by extension.
import os
from glob import glob
result = [y for x in os.walk(PATH) for y in glob(os.path.join(x[0], '*.txt'))]
Also a generator version
from itertools import chain
result = (chain.from_iterable(glob(os.path.join(x[0], '*.txt')) for x in os.walk('.')))
Edit2 for Python 3.4+
from pathlib import Path
result = list(Path(".").rglob("*.[tT][xX][tT]"))
Aside from looking into root cause issues like file leaks, etc. in order to do a legitimate increase the "open files" limit and have that persist across reboots, consider editing
/etc/security/limits.conf
by adding something like this
jetty soft nofile 2048
jetty hard nofile 4096
where "jetty" is the username in this case. For more details on limits.conf, see http://linux.die.net/man/5/limits.conf
log off and then log in again and run
ulimit -n
to verify that the change has taken place. New processes by this user should now comply with this change. This link seems to describe how to apply the limit on already running processes but I have not tried it.
The default limit 1024 can be too low for large Java applications.
/Java Resources/resources/config.properties
for loading properties.
Properties prop = new Properties();
InputStream input = null;
try {
input = getClass().getClassLoader().getResourceAsStream("config.properties");
// load a properties file
prop.load(input);
// get the property value and print it out
System.out.println(prop.getProperty("database"));
System.out.println(prop.getProperty("dbuser"));
System.out.println(prop.getProperty("dbpassword"));
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
It depends what you want to do with each line. awk is a useful utility for this type of processing. Example:
ls -l | awk '{print $9, $5}'
.. on my system prints the name and size of each item in the directory.
import { ActivatedRoute } from '@angular/router';_x000D_
_x000D_
export class ClassName {_x000D_
_x000D_
private router = ActivatedRoute;_x000D_
_x000D_
constructor(r: ActivatedRoute) {_x000D_
this.router =r;_x000D_
}_x000D_
_x000D_
onSuccess() {_x000D_
this.router.navigate(['/user_invitation'],_x000D_
{queryParams: {email: loginEmail, code: userCode}});_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
Get this values:_x000D_
---------------_x000D_
_x000D_
ngOnInit() {_x000D_
this.route_x000D_
.queryParams_x000D_
.subscribe(params => {_x000D_
let code = params['code'];_x000D_
let userEmail = params['email'];_x000D_
});_x000D_
}
_x000D_
Ref: https://angular.io/docs/ts/latest/api/router/index/NavigationExtras-interface.html
You can use multiple way based on sitaution:
If you Variable is limited to specific Number or String, best way is using ngSwitch or ngIf:
<!-- foo = 3 -->
<div [ngSwitch]="foo">
<div *ngSwitchCase="1">First Number</div>
<div *ngSwitchCase="2">Second Number</div>
<div *ngSwitchCase="3">Third Number</div>
<div *ngSwitchDefault>Other Number</div>
</div>
<!-- foo = 3 -->
<ng-template [ngIf]="foo === 1">First Number</ng-template>
<ng-template [ngIf]="foo === 2">Second Number</ng-template>
<ng-template [ngIf]="foo === 3">Third Number</ng-template>
<!-- foo = 'David' -->
<div [ngSwitch]="foo">
<div *ngSwitchCase="'Daniel'">Daniel String</div>
<div *ngSwitchCase="'David'">David String</div>
<div *ngSwitchCase="'Alex'">Alex String</div>
<div *ngSwitchDefault>Other String</div>
</div>
<!-- foo = 'David' -->
<ng-template [ngIf]="foo === 'Alex'">Alex String</ng-template>
<ng-template [ngIf]="foo === 'David'">David String</ng-template>
<ng-template [ngIf]="foo === 'Daniel'">Daniel String</ng-template>
Above not suitable for if elseif else codes and dynamic codes, you can use below code:
<!-- foo = 5 -->
<ng-container *ngIf="foo >= 1 && foo <= 3; then t13"></ng-container>
<ng-container *ngIf="foo >= 4 && foo <= 6; then t46"></ng-container>
<ng-container *ngIf="foo >= 7; then t7"></ng-container>
<!-- If Statement -->
<ng-template #t13>
Template for foo between 1 and 3
</ng-template>
<!-- If Else Statement -->
<ng-template #t46>
Template for foo between 4 and 6
</ng-template>
<!-- Else Statement -->
<ng-template #t7>
Template for foo greater than 7
</ng-template>
Note: You can choose any format, but notice every code has own problems
Many modern browsers now support ES6 modules. As long as you import your scripts (including the entrypoint to your application) using <script type="module" src="...">
it will work.
Take a look at caniuse.com for more details: https://caniuse.com/#feat=es6-module
With C#6 there is a slightly shorter way for the case where planRec.approved_by is not a string:
this.approved_by = planRec.approved_by?.ToString() ?? "";
I had to do rake clean --force
. Then did gem install rake
and so forth.
Instead of using a regular expression, just check if string.length > 25
Use the PropertyConfigurator: PropertyConfigurator.configure(configFileUrl);
This answer is for a Material Design horizontal card layout with dynamic height and an image.
To prevent distortion of the image due to the dynamic height of the card, you could use a background placeholder image with blur to adjust for changes in height.
<div>
with class wrapper, which is a flexbox.<a>
, class link, is positioned
relative.<div>
class blur and an <img>
class pic which is the clear image.width: 100%
, but class pic has a higher stack order, i.e., z-index: 2
, which places it above the placeholder.
.wrapper {_x000D_
display: flex;_x000D_
width: 100%;_x000D_
border: 1px solid rgba(0, 0, 0, 0.16);_x000D_
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.16), 0 1px 1px rgba(0, 0, 0, 0.23);_x000D_
background-color: #fff;_x000D_
margin: 1rem auto;_x000D_
height: auto;_x000D_
}_x000D_
_x000D_
.wrapper:hover {_x000D_
box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23);_x000D_
}_x000D_
_x000D_
.link {_x000D_
display: block;_x000D_
width: 200px;_x000D_
height: auto;_x000D_
overflow: hidden;_x000D_
position: relative;_x000D_
border-right: 2px solid #ddd;_x000D_
}_x000D_
_x000D_
.blur {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
bottom: 0;_x000D_
margin: auto;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
filter: blur(5px);_x000D_
-webkit-filter: blur(5px);_x000D_
-moz-filter: blur(5px);_x000D_
-o-filter: blur(5px);_x000D_
-ms-filter: blur(5px);_x000D_
}_x000D_
_x000D_
.pic {_x000D_
width: calc(100% - 20px);_x000D_
max-width: 100%;_x000D_
height: auto;_x000D_
margin: auto;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
bottom: 0;_x000D_
z-index: 2;_x000D_
}_x000D_
_x000D_
.pic:hover {_x000D_
transition: all 0.2s ease-out;_x000D_
transform: scale(1.1);_x000D_
text-decoration: none;_x000D_
border: none;_x000D_
}_x000D_
_x000D_
.content {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
width: 100%;_x000D_
max-width: 100%;_x000D_
padding: 20px;_x000D_
overflow-x: hidden;_x000D_
}_x000D_
_x000D_
.text {_x000D_
margin: 0;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<a href="#" class="link">_x000D_
<div class="blur" style="background: url('http://www.planwallpaper.com/static/assets/img/header.jpg') 50% 50% / cover;"></div>_x000D_
<img src="http://www.planwallpaper.com/static/assets/img/header.jpg" alt="Title" class="pic" />_x000D_
</a>_x000D_
_x000D_
<div class="content">_x000D_
<p class="text">Agendum dicendo memores du gi ad. Perciperem occasionem ei ac im ac designabam. Ista rom sibi vul apud tam. Notaverim to extendere expendere concilium ab. Aliae cogor tales fas modus parum sap nullo. Voluntate ingressus infirmari ex mentemque ac manifeste_x000D_
eo. Ac gnum ei utor sive se. Nec curant contra seriem amisit res gaudet adsunt. </p>_x000D_
</div>_x000D_
</div>
_x000D_
Here is a rough explanation of the concepts.
[ACK]
is the acknowledgement that the previously sent data packet was received.
[FIN]
is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN
).
So, suppose
[FIN,ACK]
indicating that it received the sent packet and wants to close the session.[FIN,ACK]
indicating that it received the termination request (the ACK
part) and that it too will close the connection (the FIN
part).However, if host A wants to close the session after sending the packet, it would only send a [FIN]
packet (nothing to acknowledge) but host B would respond with [FIN,ACK]
(acknowledges the request and responds with FIN
).
Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST]
instead of the usual [FIN,ACK]
. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.
You can find a more detailed and comprehensive explanation here.
FileReaderJS can read the files for you. You get the file content inside onLoad(e)
event handler as e.target.result
.
Here's a quick Perl script to get what you need. It needs some whitespace chomping.
#!/bin/perl
$sample = <<END;
Subject:
Security ID: S-1-5-21-3368353891-1012177287-890106238-22451
Account Name: ChamaraKer
Account Domain: JIC
Logon ID: 0x1fffb
Object:
Object Server: Security
Object Type: File
Object Name: D:\\ApacheTomcat\\apache-tomcat-6.0.36\\logs\\localhost.2013- 07-01.log
Handle ID: 0x11dc
END
my @sample_lines = split /\n/, $sample;
my $path;
foreach my $line (@sample_lines) {
($path) = $line =~ m/Object Name:([^s]+)/g;
if($path) {
print $path . "\n";
}
}
Is there any reason for not using a submit button and then styling it with css to match your other a tags?
I think this would reduce your dependency on having javascript enabled and still get the desired result.
You have layout your_layout.xml
public void showCustomDialog(final Context context) {
Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.your_layout, null, false);
findByIds(view); /*HERE YOU CAN FIND YOU IDS AND SET TEXTS OR BUTTONS*/
((Activity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
dialog.setContentView(view);
final Window window = dialog.getWindow();
window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
window.setBackgroundDrawableResource(R.color.colorTransparent);
window.setGravity(Gravity.CENTER);
dialog.show();
}
Update : In angular 7, they are the same as 6
In angular 6
the complete answer found in live example
/** POST: add a new hero to the database */
addHero (hero: Hero): Observable<Hero> {
return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
.pipe(
catchError(this.handleError('addHero', hero))
);
}
/** GET heroes from the server */
getHeroes (): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
catchError(this.handleError('getHeroes', []))
);
}
it's because of pipeable/lettable operators
which now angular is able to use tree-shakable
and remove unused imports and optimize the app
some rxjs functions are changed
do -> tap
catch -> catchError
switch -> switchAll
finally -> finalize
more in MIGRATION
and Import paths
For JavaScript developers, the general rule is as follows:
rxjs: Creation methods, types, schedulers and utilities
import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent } from 'rxjs';
rxjs/operators: All pipeable operators:
import { map, filter, scan } from 'rxjs/operators';
rxjs/webSocket: The web socket subject implementation
import { webSocket } from 'rxjs/webSocket';
rxjs/ajax: The Rx ajax implementation
import { ajax } from 'rxjs/ajax';
rxjs/testing: The testing utilities
import { TestScheduler } from 'rxjs/testing';
and for backward compatability you can use rxjs-compat
You should check whether the distance from the center of the circle to the point is smaller than the radius
using Python
if (x-center_x)**2 + (y-center_y)**2 <= radius**2:
# inside circle
Add the following line in your .profile
file in your home directory (using vi ~/.profile
):
PATH=$PATH:/home/me/play
export PATH
Then, for the change to take effect, simply type in your terminal:
$ . ~/.profile
Appears to have moved again in the latest version of GH for windows to:
%USERPROFILE%\AppData\Local\GitHubDesktop\app-[gfw-version]\resources\app\git\cmd\git.exe
Given it now has the version in the folder structure i think it will move every time it auto-updates. This makes it impossible to put into path. I think the best option is to install git separately.
Just to add to what everyone else have said about setTimeout
:
If you want to call a function with a parameter in the future, you need to set up some anonymous function calls.
You need to pass the function as an argument for it to be called later. In effect this means without brackets behind the name. The following will call the alert at once, and it will display 'Hello world':
var a = "world";
setTimeout(alert("Hello " + a), 2000);
To fix this you can either put the name of a function (as Flubba has done) or you can use an anonymous function. If you need to pass a parameter, then you have to use an anonymous function.
var a = "world";
setTimeout(function(){alert("Hello " + a)}, 2000);
a = "Stack Overflow";
But if you run that code you will notice that after 2 seconds the popup will say 'Hello Stack Overflow'. This is because the value of the variable a has changed in those two seconds. To get it to say 'Hello world' after two seconds, you need to use the following code snippet:
function callback(a){
return function(){
alert("Hello " + a);
}
}
var a = "world";
setTimeout(callback(a), 2000);
a = "Stack Overflow";
It will wait 2 seconds and then popup 'Hello world'.
This answer is for visual studio 2017 and if you want to read from text file which location is relative to your compiled console application.
first put your textfile (test.txt in this case) into your solution folder. After compiling keep text file in same folder with applicationName.exe
C:\Users\"username"\source\repos\"solutionName"\"solutionName"
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inFile;
// open the file stream
inFile.open(".\\test.txt");
// check if opening a file failed
if (inFile.fail()) {
cerr << "Error opeing a file" << endl;
inFile.close();
exit(1);
}
string line;
while (getline(inFile, line))
{
cout << line << endl;
}
// close the file stream
inFile.close();
}
Read this my answer here
How do I export a project in the Android studio?
This will guide you step by step to generate signed APK and how to create keystore file from Android Studio.
From the link you can do it easily as I added the screenshot of it step by step.
If you have Key-store file then you can do same simply.
Go to Build then click on Generate Signed APK
sqrt=x**(1/2)
is doing integer division. 1/2 == 0
.
So you're computing x(1/2) in the first instance, x(0) in the second.
So it's not wrong, it's the right answer to a different question.
I had the same problem. It turns out that, compiling a project I got from someone else, I haven't set the correct StartUp project (right click on the desired startup project in the solution explorer and pick "set as StartUp Project"). Maybe this will help, cheers.
You need to add your files to your working copy, before you commit your changes to the repository:
svn add <file|folder>
Afterwards:
svn commit
See here for detailed information about svn add
.
TortoiseSVN
It works with TortoiseSVN, because it adds the file to your working copy automatically (commit dialog):
If you want to include an unversioned file, just check that file to add it to the commit.
Expanding on the accepted answer:
function mysql_query_or_die($query) {
$result = mysql_query($query);
if ($result)
return $result;
else {
$err = mysql_error();
die("<br>{$query}<br>*** {$err} ***<br>");
}
}
...
$query = "SELECT * FROM my_table";
$result = mysql_query_or_die($query);
echo("<table>");
$first_row = true;
while ($row = mysql_fetch_assoc($result)) {
if ($first_row) {
$first_row = false;
// Output header row from keys.
echo '<tr>';
foreach($row as $key => $field) {
echo '<th>' . htmlspecialchars($key) . '</th>';
}
echo '</tr>';
}
echo '<tr>';
foreach($row as $key => $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
}
echo("</table>");
Benefits:
Using mysql_fetch_assoc (instead of mysql_fetch_array with no 2nd parameter to specify type), we avoid getting each field twice, once for a numeric index (0, 1, 2, ..), and a second time for the associative key.
Shows field names as a header row of table.
Shows how to get both column name
($key) and value
($field) for each field, as iterate over the fields of a row.
Wrapped in <table>
so displays properly.
(OPTIONAL) dies with display of query string and mysql_error, if query fails.
Example Output:
Id Name
777 Aardvark
50 Lion
9999 Zebra
For the 3 vertical dot icon, these are the most popular names
For the remaining, here is the list.
In C++, your source files are usually parsed from top to bottom in a single pass, so any variable or function must be declared before they can be used. There are some exceptions to this, like when defining functions inline in a class definition, but that's not the case for your code.
Either move the definition of integrate
above the one for getSkewNormal
, or add a forward declaration above getSkewNormal
:
double integrate (double start, double stop, int numSteps, Evaluatable evalObj);
The same applies for sum
.
$("#txtfromdate").datepicker({
numberOfMonths: 2,
maxDate: 0,
dateFormat: 'dd-M-yy'
}).attr('readonly', 'readonly');
add the readonly attribute in the jquery.
Using onclick
instead will work. In theory it may not catch changes made via the keyboard but all browsers do seem to fire the event anyway when checking via keyboard.
You also need to pass the checkbox into the function:
function checkAddress(checkbox)
{
if (checkbox.checked)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onclick="checkAddress(this)" />
I wrote a reusable custom control, maybe it can help someone that need to implement multiple placeholder textboxes in his project.
here is the custom class with implementation example of an instance, you can test easily by pasting this code on a new winforms project using VS:
namespace reusebleplaceholdertextbox
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// implementation
CustomPlaceHolderTextbox myCustomTxt = new CustomPlaceHolderTextbox(
"Please Write Text Here...", Color.Gray, new Font("ARIAL", 11, FontStyle.Italic)
, Color.Black, new Font("ARIAL", 11, FontStyle.Regular)
);
myCustomTxt.Multiline = true;
myCustomTxt.Size = new Size(200, 50);
myCustomTxt.Location = new Point(10, 10);
this.Controls.Add(myCustomTxt);
}
}
class CustomPlaceHolderTextbox : System.Windows.Forms.TextBox
{
public string PlaceholderText { get; private set; }
public Color PlaceholderForeColor { get; private set; }
public Font PlaceholderFont { get; private set; }
public Color TextForeColor { get; private set; }
public Font TextFont { get; private set; }
public CustomPlaceHolderTextbox(string placeholdertext, Color placeholderforecolor,
Font placeholderfont, Color textforecolor, Font textfont)
{
this.PlaceholderText = placeholdertext;
this.PlaceholderFont = placeholderfont;
this.PlaceholderForeColor = placeholderforecolor;
this.PlaceholderFont = placeholderfont;
this.TextForeColor = textforecolor;
this.TextFont = textfont;
if (!string.IsNullOrEmpty(this.PlaceholderText))
{
SetPlaceHolder(true);
this.Update();
}
}
private void SetPlaceHolder(bool addEvents)
{
if (addEvents)
{
this.LostFocus += txt_lostfocus;
this.Click += txt_click;
}
this.Text = PlaceholderText;
this.ForeColor = PlaceholderForeColor;
this.Font = PlaceholderFont;
}
private void txt_click(object sender, EventArgs e)
{
// IsNotFirstClickOnThis:
// if there is no other control in the form
// we will have a problem after the first load
// because we dont other focusable control to move the focus to
// and we dont want to remove the place holder
// only on first time the place holder will be removed by click event
RemovePlaceHolder();
this.GotFocus += txt_focus;
// no need for this event listener now
this.Click -= txt_click;
}
private void RemovePlaceHolder()
{
this.Text = "";
this.ForeColor = TextForeColor;
this.Font = TextFont;
}
private void txt_lostfocus(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(this.Text))
{
// set placeholder again
SetPlaceHolder(false);
}
}
private void txt_focus(object sender, EventArgs e)
{
if (this.Text == PlaceholderText)
{
// IsNotFirstClickOnThis:
// if there is no other control in the form
// we will have a problem after the first load
// because we dont other focusable control to move the focus to
// and we dont want to remove the place holder
RemovePlaceHolder();
}
}
}
}
Font type always be set in code and nib/storyboard.
For the code,just like Hugues BR said,do it in catagory can solve the problem.
For the nib/storyboard,we can Method Swizzling awakeFromNib to change font type since UI element from nib/storyboard always call it before show in the screen.
I suppose you know Aspects.It's a library for AOP programing,based on Method Swizzling. We create catagory for UILabel,UIButton,UITextView to implement it.
UILabel:
#import "UILabel+OverrideBaseFont.h"
#import "Aspects.h"
@implementation UILabel (OverrideBaseFont)
+ (void)load {
[[self class]aspect_hookSelector:@selector(awakeFromNib) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo) {
UILabel* instance = [aspectInfo instance];
UIFont* font = [UIFont fontWithName:@"HelveticaNeue-light" size:instance.font.pointSize];
instance.font = font;
}error:nil];
}
@end
UIButton:
#import "UIButton+OverrideBaseFont.h"
#import "Aspects.h"
@implementation UIButton (OverrideBaseFont)
+ (void)load {
[[self class]aspect_hookSelector:@selector(awakeFromNib) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo) {
UIButton* instance = [aspectInfo instance];
UILabel* label = instance.titleLabel;
UIFont* font = [UIFont fontWithName:@"HelveticaNeue-light" size:label.font.pointSize];
instance.titleLabel.font = font;
}error:nil];
}
@end
UITextField:
#import "UITextField+OverrideBaseFont.h"
#import "Aspects.h"
@implementation UITextField (OverrideBaseFont)
+ (void)load {
[[self class]aspect_hookSelector:@selector(awakeFromNib) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo) {
UITextField* instance = [aspectInfo instance];
UIFont* font = [UIFont fontWithName:@"HelveticaNeue-light" size:instance.font.pointSize];
instance.font = font;
}error:nil];
}
@end
UITextView:
#import "UITextView+OverrideBaseFont.h"
#import "Aspects.h"
@implementation UITextView (OverrideBaseFont)
+ (void)load {
[[self class]aspect_hookSelector:@selector(awakeFromNib) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo) {
UITextView* instance = [aspectInfo instance];
UIFont* font = [UIFont fontWithName:@"HelveticaNeue-light" size:instance.font.pointSize];
instance.font = font;
}error:nil];
}
@end
That's all,you can change HelveticaNeue-light to a macro with your font name.
As of Gradle 4.9 Application plugin understands --args
option, so passing the arguments is as simple as:
build.gradle
plugins {
id 'application'
}
mainClassName = "my.App"
src/main/java/my/App.java
public class App {
public static void main(String[] args) {
System.out.println(args);
}
}
bash
./gradlew run --args='This string will be passed into my.App#main arguments'
or in Windows, use double quotes:
gradlew run --args="This string will be passed into my.App#main arguments"
If you're changing the layout of an existing ImageView, you should be able to simply get the current LayoutParams, change the width/height, and set it back:
android.view.ViewGroup.LayoutParams layoutParams = myImageView.getLayoutParams();
layoutParams.width = 30;
layoutParams.height = 30;
myImageView.setLayoutParams(layoutParams);
I don't know if that's your goal, but if it is, this is probably the easiest solution.
The recommended version by Günter Zöchbauer works fine, but I have an addition to make. In my case I had an unstyled html-element and I did not know how to style it. Therefore I designed a pipe to add styling to it.
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Pipe({
name: 'StyleClass'
})
export class StyleClassPipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) { }
transform(html: any, styleSelector: any, styleValue: any): SafeHtml {
const style = ` style = "${styleSelector}: ${styleValue};"`;
const indexPosition = html.indexOf('>');
const newHtml = [html.slice(0, indexPosition), style, html.slice(indexPosition)].join('');
return this.sanitizer.bypassSecurityTrustHtml(newHtml);
}
}
Then you can add style to any html-element like this:
<span [innerhtml]="Variable | StyleClass: 'margin': '0'"> </span>
With:
Variable = '<p> Test </p>'
The letters 100000000000 make up a literal integer constant, but the value is too large for the type int
. You need to use a suffix to change the type of the literal, i.e.
long long num3 = 100000000000LL;
The suffix LL
makes the literal into type long long
. C is not "smart" enough to conclude this from the type on the left, the type is a property of the literal itself, not the context in which it is being used.
Name: net/sf/jasperreports/engine/util/xml/JaxenXPathExecuterFactory.c lass SHA-256-Digest: q3B5wW+hLX/+lP2+L0/6wRVXRHq1mISBo1dkixT6Vxc=
You should consider have other php files included if you're going to derive a website from it. Instead of doing all the css/etc in that file, you can do
<head>
<?php include_once('C:\Users\George\Documents\HTML\style.css'); ?>
<title>Title</title>
</hea>
Then you can have a separate CSS file that is just being pulled into your php file. It provides some "neater" coding.
I just had this problem, and the cause seemed to be that a directory had been flagged as in conflict. To fix:
svn update
svn resolved <the directory in conflict>
svn commit
The answer by Maksym Kozlenko is nice and can be slightly modified to handle encoding a numeric value to any code format. For example:
CREATE FUNCTION [dbo].[IntToAlpha](@Value int)
RETURNS varchar(30)
AS
BEGIN
DECLARE @CodeChars varchar(100)
SET @CodeChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
DECLARE @CodeLength int = 26
DECLARE @Result varchar(30) = ''
DECLARE @Digit char(1)
SET @Result = SUBSTRING(@CodeChars, (@Value % @CodeLength) + 1, 1)
WHILE @Value > 0
BEGIN
SET @Digit = SUBSTRING(@CodeChars, ((@Value / @CodeLength) % @CodeLength) + 1, 1)
SET @Value = @Value / @CodeLength
IF @Value <> 0 SET @Result = @Digit + @Result
END
RETURN @Result
END
So, a big number like 150 million, becomes only 6 characters (150,000,000 = "MQGJMU")
You could also use different characters in different sequences as an encrypting device. Or pass in the code characters and length of characters and use as a salting method for encrypting.
And the reverse:
CREATE FUNCTION [dbo].[AlphaToInt](@Value varchar(7))
RETURNS int
AS
BEGIN
DECLARE @CodeChars varchar(100)
SET @CodeChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
DECLARE @CodeLength int = 26
DECLARE @Digit char(1)
DECLARE @Result int = 0
DECLARE @DigitValue int
DECLARE @Index int = 0
DECLARE @Reverse varchar(7)
SET @Reverse = REVERSE(@Value)
WHILE @Index < LEN(@Value)
BEGIN
SET @Digit = SUBSTRING(@Reverse, @Index + 1, 1)
SET @DigitValue = (CHARINDEX(@Digit, @CodeChars) - 1) * POWER(@CodeLength, @Index)
SET @Result = @Result + @DigitValue
SET @Index = @Index + 1
END
RETURN @Result
For the record:
"Data at the root level is invalid" means that you have attempted to parse something that is not an XML document. It doesn't even start to look like an XML document. It usually means just what you found: you're parsing something like the string "C:\inetpub\wwwroot\mysite\officelist.xml".
doAnswer
and thenReturn
do the same thing if:
Let's mock this BookService
public interface BookService {
String getAuthor();
void queryBookTitle(BookServiceCallback callback);
}
You can stub getAuthor() using doAnswer
and thenReturn
.
BookService service = mock(BookService.class);
when(service.getAuthor()).thenReturn("Joshua");
// or..
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return "Joshua";
}
}).when(service).getAuthor();
Note that when using doAnswer
, you can't pass a method on when
.
// Will throw UnfinishedStubbingException
doAnswer(invocation -> "Joshua").when(service.getAuthor());
So, when would you use doAnswer
instead of thenReturn
? I can think of two use cases:
Using doAnswer you can do some additionals actions upon method invocation. For example, trigger a callback on queryBookTitle.
BookServiceCallback callback = new BookServiceCallback() {
@Override
public void onSuccess(String bookTitle) {
assertEquals("Effective Java", bookTitle);
}
};
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
BookServiceCallback callback = (BookServiceCallback) invocation.getArguments()[0];
callback.onSuccess("Effective Java");
// return null because queryBookTitle is void
return null;
}
}).when(service).queryBookTitle(callback);
service.queryBookTitle(callback);
When using when-thenReturn on Spy Mockito will call real method and then stub your answer. This can cause a problem if you don't want to call real method, like in this sample:
List list = new LinkedList();
List spy = spy(list);
// Will throw java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
when(spy.get(0)).thenReturn("java");
assertEquals("java", spy.get(0));
Using doAnswer we can stub it safely.
List list = new LinkedList();
List spy = spy(list);
doAnswer(invocation -> "java").when(spy).get(0);
assertEquals("java", spy.get(0));
Actually, if you don't want to do additional actions upon method invocation, you can just use doReturn
.
List list = new LinkedList();
List spy = spy(list);
doReturn("java").when(spy).get(0);
assertEquals("java", spy.get(0));
If you don't use html helpers you may use simple ternary expression like this:
<input name="Field"
value="@Model.Field" tabindex="0"
@(Model.IsDisabledField ? "disabled=\"disabled\"" : "")>
First, you need to create your branch locally
git checkout -b your_branch
After that, you can work locally in your branch, when you are ready to share the branch, push it. The next command push the branch to the remote repository origin and tracks it
git push -u origin your_branch
Your Teammates/colleagues can push to your branch by doing commits and then push explicitly
... work ...
git commit
... work ...
git commit
git push origin HEAD:refs/heads/your_branch
=arrayformula(if(isblank(B2:B),iferror(1/0),mmult(sign(B2:B=TRANSPOSE(A2:A)),A2:A)))
I got this from a good tutorial - can't remember the title - probably about using MMult
You could just use REPLACE
:
UPDATE myTable SET emailCol = REPLACE(emailCol, '.com', '.org')`.
But take into account an email address such as [email protected]
will be updated to [email protected]
.
If you want to be on a safer side, you should check for the last 4 characters using RIGHT
, and append .org
to the SUBSTRING
manually instead. Notice the usage of UPPER
to make the search for the .com
ending case insensitive.
UPDATE myTable
SET emailCol = SUBSTRING(emailCol, 1, LEN(emailCol)-4) + '.org'
WHERE UPPER(RIGHT(emailCol,4)) = '.COM';
See it working in this SQLFiddle.
I wanted a way to simply and automatically report errors (since users often don't) from our applications. The easiest solution I could come up with was a public URL - a web page which could take input and store it to a database - that is sent data upon an application error. (The database could then be checked by a dev or a script to know if there are new errors.)
I wrote the web page in PHP and created a mysql database, user, and table to store the data. I decided on four user variables, an id, and a timestamp. The possible variables (either included in the URL or as POST data) are:
app
(application name)msg
(message - e.g. Exception occurred ...)dev
(developer - e.g. Pat)src
(source - this would come from a variable pertaining to the machine on which the app was running, e.g. Environment.MachineName
or some such)log
(a log file or verbose message)(All of the variables are optional, but nothing is reported if none of them are set - so if you just visit the website URL nothing is sent to the db.)
To send the data to the URL, I used NLog's WebService
target. (Note, I had a few problems with this target at first. It wasn't until I looked at the source that I figured out that my url
could not end with a /
.)
All in all, it's not a bad system for keeping tabs on external apps. (Of course, the polite thing to do is to inform your users that you will be reporting possibly sensitive data and to give them a way to opt in/out.)
(The db user has only INSERT
privileges on this one table in its own database.)
CREATE TABLE `reports` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`ts` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`applicationName` text,
`message` text,
`developer` text,
`source` text,
`logData` longtext,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='storage place for reports from external applications'
(PHP 5.3 or 5.2 with PDO enabled, file is index.php
in /report
folder)
<?php
$app = $_REQUEST['app'];
$msg = $_REQUEST['msg'];
$dev = $_REQUEST['dev'];
$src = $_REQUEST['src'];
$log = $_REQUEST['log'];
$dbData =
array( ':app' => $app,
':msg' => $msg,
':dev' => $dev,
':src' => $src,
':log' => $log
);
//print_r($dbData); // For debugging only! This could allow XSS attacks.
if(isEmpty($dbData)) die("No data provided");
try {
$db = new PDO("mysql:host=$host;dbname=reporting", "reporter", $pass, array(
PDO::ATTR_PERSISTENT => true
));
$s = $db->prepare("INSERT INTO reporting.reports
(
applicationName,
message,
developer,
source,
logData
)
VALUES
(
:app,
:msg,
:dev,
:src,
:log
);"
);
$s->execute($dbData);
print "Added report to database";
} catch (PDOException $e) {
// Sensitive information can be displayed if this exception isn't handled
//print "Error!: " . $e->getMessage() . "<br/>";
die("PDO error");
}
function isEmpty($array = array()) {
foreach ($array as $element) {
if (!empty($element)) {
return false;
}
}
return true;
}
?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
throwExceptions="true" internalLogToConsole="true" internalLogLevel="Warn" internalLogFile="nlog.log">
<variable name="appTitle" value="My External App"/>
<variable name="csvPath" value="${specialfolder:folder=Desktop:file=${appTitle} log.csv}"/>
<variable name="developer" value="Pat"/>
<targets async="true">
<!--The following will keep the default number of log messages in a buffer and write out certain levels if there is an error and other levels if there is not. Messages that appeared before the error (in code) will be included, since they are buffered.-->
<wrapper-target xsi:type="BufferingWrapper" name="smartLog">
<wrapper-target xsi:type="PostFilteringWrapper">
<target xsi:type="File" fileName="${csvPath}"
archiveAboveSize="4194304" concurrentWrites="false" maxArchiveFiles="1" archiveNumbering="Sequence"
>
<layout xsi:type="CsvLayout" delimiter="Comma" withHeader="false">
<column name="time" layout="${longdate}" />
<column name="level" layout="${level:upperCase=true}"/>
<column name="message" layout="${message}" />
<column name="callsite" layout="${callsite:includeSourcePath=true}" />
<column name="stacktrace" layout="${stacktrace:topFrames=10}" />
<column name="exception" layout="${exception:format=ToString}"/>
<!--<column name="logger" layout="${logger}"/>-->
</layout>
</target>
<!--during normal execution only log certain messages-->
<defaultFilter>level >= LogLevel.Warn</defaultFilter>
<!--if there is at least one error, log everything from trace level-->
<when exists="level >= LogLevel.Error" filter="level >= LogLevel.Trace" />
</wrapper-target>
</wrapper-target>
<target xsi:type="WebService" name="web"
url="http://example.com/report"
methodName=""
namespace=""
protocol="HttpPost"
>
<parameter name="app" layout="${appTitle}"/>
<parameter name="msg" layout="${message}"/>
<parameter name="dev" layout="${developer}"/>
<parameter name="src" layout="${environment:variable=UserName} (${windows-identity}) on ${machinename} running os ${environment:variable=OSVersion} with CLR v${environment:variable=Version}"/>
<parameter name="log" layout="${file-contents:fileName=${csvPath}}"/>
</target>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="smartLog"/>
<logger name="*" minlevel="Error" writeTo="web"/>
</rules>
</nlog>
Note: there may be some issues with the size of the log file, but I haven't figured out a simple way to truncate it (e.g. a la *nix's tail
command).
An alternative, I think for your purpose, is to use the round() function:
select round((10 * 1.5),2) // prints 15.00
You can try it here:
Iterating through elements of two lists simultaneously is known as zipping, and python provides a built in function for it, which is documented here.
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zipped)
>>> x == list(x2) and y == list(y2)
True
[Example is taken from pydocs]
In your case, it will be simply:
for (lat, lon) in zip(latitudes, longitudes):
... process lat and lon
According to the documentation there are several ways to do the inlining.
The right way you must choose based on the situation.
1) Simply put the variable from server to javascript :
<script th:inline="javascript">
/*<![CDATA[*/
var message = [[${message}]];
alert(message);
/*]]>*/
</script>
2) Combine javascript variables with server side variables, e.g. you need to create link for requesting inside the javascript:
<script th:inline="javascript">
/*<![CDATA[*/
function sampleGetByJquery(v) {
/*[+
var url = [[@{/my/get/url(var1=${#httpServletRequest.getParameter('var1')})}]]
+ "&var2="+v;
+]*/
$("#myPanel").load(url, function() {});
}
/*]]>*/
</script>
The one situation I can't resolve - then I need to pass javascript variable inside the Java method calling inside the template (it's impossible I guess).
To fix your specific error you need to run that command as sudo, ie:
sudo gem install rails --pre
Just try to send a session variable when you press log in. And on the welcome page, first check whether that session is empty like this in the page load or in the Init Event:
if(Session["UserID"] == null || Session["UserID"] == "")
{
Response.Redirect("Login.aspx");
}
You said :
Maybe my data.frame is not in a good format?
Yes this is true. Your data is in the wide format You need to put it in the long format. Generally speaking, long format is better for variables comparison.
Using reshape2
for example , you do this using melt
:
dat.m <- melt(dat,id.vars = "Rank") ## just melt(dat) should work
Then you get your barplot:
ggplot(dat.m, aes(x = Rank, y = value,fill=variable)) +
geom_bar(stat='identity')
But using lattice
and barchart
smart formula notation , you don't need to reshape your data , just do this:
barchart(F1+F2+F3~Rank,data=dat)
If you want to ignore the insertion of existing value, there must be a Key field in your Table. Just create a table With Primary Key Field Like:
CREATE TABLE IF NOT EXISTS TblUsers (UserId INTEGER PRIMARY KEY, UserName varchar(100), ContactName varchar(100),Password varchar(100));
And Then Insert Or Replace / Insert Or Ignore Query on the Table Like:
INSERT OR REPLACE INTO TblUsers (UserId, UserName, ContactName ,Password) VALUES('1','UserName','ContactName','Password');
It Will Not Let it Re-Enter The Existing Primary key Value... This Is how you can Check Whether a Value exists in the table or not.
Browsers and OS's determine the style of the select boxes in most cases, and it's next to impossible to alter them with CSS alone. You'll have to look into replacement methods. The main trick is to apply appearance: none
which lets you override some of the styling.
My favourite method is this one:
http://cssdeck.com/item/265/styling-select-box-with-css3
It doesn't replace the OS select menu UI element so all the problems related to doing that are non-existant (not being able to break out of the browser window with a long list being the main one).
Good luck :)
you can use pixels or percent.
<div id="container">
<img id="image" src="...">
</div>
css
#image
{
width:100%;
height:
}
If you add text-align: center
to the declarations for .columns-container
then they align centrally:
.columns-container {
display: table-cell;
height: 100%;
width:600px;
text-align: center;
}
/*************************_x000D_
* Sticky footer hack_x000D_
* Source: http://pixelsvsbytes.com/blog/2011/09/sticky-css-footers-the-flexible-way/_x000D_
************************/_x000D_
_x000D_
/* Stretching all container's parents to full height */_x000D_
_x000D_
html,_x000D_
body {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
/* Setting the container to be a table with maximum width and height */_x000D_
_x000D_
#container {_x000D_
display: table;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
}_x000D_
/* All sections (container's children) should be table rows with minimal height */_x000D_
_x000D_
.section {_x000D_
display: table-row;_x000D_
height: 1px;_x000D_
}_x000D_
/* The last-but-one section should be stretched to automatic height */_x000D_
_x000D_
.section.expand {_x000D_
height: auto;_x000D_
}_x000D_
/*************************_x000D_
* Full height columns_x000D_
************************/_x000D_
_x000D_
/* We need one extra container, setting it to full width */_x000D_
_x000D_
.columns-container {_x000D_
display: table-cell;_x000D_
height: 100%;_x000D_
width:600px;_x000D_
text-align: center;_x000D_
}_x000D_
/* Creating columns */_x000D_
_x000D_
.column {_x000D_
/* The float:left won't work for Chrome for some reason, so inline-block */_x000D_
display: inline-block;_x000D_
/* for this to work, the .column elements should have NO SPACE BETWEEN THEM */_x000D_
vertical-align: top;_x000D_
height: 100%;_x000D_
width: 100px;_x000D_
}_x000D_
/****************************************************************_x000D_
* Just some coloring so that we're able to see height of columns_x000D_
****************************************************************/_x000D_
_x000D_
header {_x000D_
background-color: yellow;_x000D_
}_x000D_
#a {_x000D_
background-color: pink;_x000D_
}_x000D_
#b {_x000D_
background-color: lightgreen;_x000D_
}_x000D_
#c {_x000D_
background-color: lightblue;_x000D_
}_x000D_
footer {_x000D_
background-color: purple;_x000D_
}
_x000D_
<div id="container">_x000D_
<header class="section">_x000D_
foo_x000D_
</header>_x000D_
_x000D_
<div class="section expand">_x000D_
<div class="columns-container">_x000D_
<div class="column" id="a">_x000D_
<p>Contents A</p>_x000D_
</div>_x000D_
<div class="column" id="b">_x000D_
<p>Contents B</p>_x000D_
</div>_x000D_
<div class="column" id="c">_x000D_
<p>Contents C</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<footer class="section">_x000D_
bar_x000D_
</footer>_x000D_
</div>
_x000D_
This does, though, require that you reset the .column
elements to text-align: left
(assuming you want them left-aligned, obviously (JS Fiddle demo).
You sure can. Create an HTML page with the form in it that will contain the necessary components from the login.aspx page (i.e. username, etc), and make sure they have the same IDs. For you action, make sure it's a post.
You might have to do some code on the login.aspx page in the Page_Load function to read the form (in the Request.Form object) and call the appropriate functions to log the user in, but other than that, you should have access to the form, and can do what you want with it.
Here is the minimal code to have a nice looking graph with just 3 lines of code :
from sklearn import tree
import pydotplus
dot_data=tree.export_graphviz(dt,filled=True,rounded=True)
graph=pydotplus.graph_from_dot_data(dot_data)
graph.write_png('tree.png')
plt.imshow(plt.imread('tree.png'))
I have added the plt.imgshow
to view the graph it Jupyter Notebook. You can ignore it if you are only interested in saving the png file.
I installed the following dependencies:
pip3 install graphviz
pip3 install pydotplus
For MacOs the pip version of Graphviz did not work. Following Graphviz's official documentation I installed it with brew and everything worked fine.
brew install graphviz
The problem you have is related to TCP streaming nature.
The fact that you sent 100 Bytes (for example) from the server doesn't mean you will read 100 Bytes in the client the first time you read. Maybe the bytes sent from the server arrive in several TCP segments to the client.
You need to implement a loop in which you read until the whole message was received.
Let me provide an example with DataInputStream
instead of BufferedinputStream
. Something very simple to give you just an example.
Let's suppose you know beforehand the server is to send 100 Bytes of data.
In client you need to write:
byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";
try
{
DataInputStream in = new DataInputStream(clientSocket.getInputStream());
while(!end)
{
int bytesRead = in.read(messageByte);
dataString += new String(messageByte, 0, bytesRead);
if (dataString.length == 100)
{
end = true;
}
}
System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
e.printStackTrace();
}
Now, typically the data size sent by one node (the server here) is not known beforehand. Then you need to define your own small protocol for the communication between server and client (or any two nodes) communicating with TCP.
The most common and simple is to define TLV: Type, Length, Value. So you define that every message sent form server to client comes with:
So you know you have to receive a minimum of 2 Bytes and with the second Byte you know how many following Bytes you need to read.
This is just a suggestion of a possible protocol. You could also get rid of "Type".
So it would be something like:
byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";
try
{
DataInputStream in = new DataInputStream(clientSocket.getInputStream());
int bytesRead = 0;
messageByte[0] = in.readByte();
messageByte[1] = in.readByte();
int bytesToRead = messageByte[1];
while(!end)
{
bytesRead = in.read(messageByte);
dataString += new String(messageByte, 0, bytesRead);
if (dataString.length == bytesToRead )
{
end = true;
}
}
System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
e.printStackTrace();
}
The following code compiles and looks better. It assumes the first two bytes providing the length arrive in binary format, in network endianship (big endian). No focus on different encoding types for the rest of the message.
import java.nio.ByteBuffer;
import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;
class Test
{
public static void main(String[] args)
{
byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";
try
{
Socket clientSocket;
ServerSocket server;
server = new ServerSocket(30501, 100);
clientSocket = server.accept();
DataInputStream in = new DataInputStream(clientSocket.getInputStream());
int bytesRead = 0;
messageByte[0] = in.readByte();
messageByte[1] = in.readByte();
ByteBuffer byteBuffer = ByteBuffer.wrap(messageByte, 0, 2);
int bytesToRead = byteBuffer.getShort();
System.out.println("About to read " + bytesToRead + " octets");
//The following code shows in detail how to read from a TCP socket
while(!end)
{
bytesRead = in.read(messageByte);
dataString += new String(messageByte, 0, bytesRead);
if (dataString.length() == bytesToRead )
{
end = true;
}
}
//All the code in the loop can be replaced by these two lines
//in.readFully(messageByte, 0, bytesToRead);
//dataString = new String(messageByte, 0, bytesToRead);
System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
See this Fiddle
<input type="radio" id="radio-2-1" name="radio-2-set" class="regular-radio" /><label for="radio-2-1"></label>
<input type="radio" id="radio-2-2" name="radio-2-set" class="regular-radio" /><label for="radio-2-2"></label>
<input type="radio" id="radio-2-3" name="radio-2-set" class="regular-radio" /><label for="radio-2-3"></label>
.regular-radio {
display: none;
}
.regular-radio + label {
-webkit-appearance: none;
background-color: #e1e1e1;
border: 4px solid #e1e1e1;
border-radius: 10px;
width: 100%;
display: inline-block;
position: relative;
width: 10px;
height: 10px;
}
.regular-radio:checked + label {
background: grey;
border: 4px solid #e1e1e1;
}
You have to define void swapCase before the main definition.
CSS
select{
color:red;
}
HTML
<select id="sel" onclick="document.getElementById('sel').style.color='green';">
<option>Select Your Option</option>
<option value="">INDIA</option>
<option value="">USA</option>
</select>
The above code will change the colour of text on click of the select box.
and if you want every option different colour, give separate class or id to all options.
The time zone should be something like "GMT+00:00" or 0000 in order to be properly parsed by the SimpleDateFormat - you can replace Z with this construction.
I would like to add my answer to the table and here it is :
//connect to db ...etc
$result_product = /*your mysql query here*/
$array_product = array();
$i = 0;
foreach ($result_product as $row_product)
{
$array_product [$i]["id"]= $row_product->id;
$array_product [$i]["name"]= $row_product->name;
$i++;
}
//you can encode the array to json if you want to send it to an ajax call
$json_product = json_encode($array_product);
echo($json_product);
hope that this will help somebody
Aquamacs:
(set-face-attribute 'default nil :font "Monaco-16" )
From the Emacs Wiki Globally Change the Default Font, it says you can use either of these:
(set-face-attribute 'default nil :font FONT )
(set-frame-font FONT nil t)
Where FONT
is something like "Monaco-16"
, e.g.:
(set-face-attribute 'default nil :font "Monaco-16" )
There was an extra closing parenthesis in the first suggestion on the wiki, which caused an error on startup. I finally noticed the extra closing parenthesis, and I subsequently corrected the suggestion on the wiki. Then both of the suggestions worked for me.
Here is an expanded solution based on DrewT's answer above that uses cookies if localStorage is not available. It uses Mozilla's docCookies library:
function localStorageGet( pKey ) {
if( localStorageSupported() ) {
return localStorage[pKey];
} else {
return docCookies.getItem( 'localstorage.'+pKey );
}
}
function localStorageSet( pKey, pValue ) {
if( localStorageSupported() ) {
localStorage[pKey] = pValue;
} else {
docCookies.setItem( 'localstorage.'+pKey, pValue );
}
}
// global to cache value
var gStorageSupported = undefined;
function localStorageSupported() {
var testKey = 'test', storage = window.sessionStorage;
if( gStorageSupported === undefined ) {
try {
storage.setItem(testKey, '1');
storage.removeItem(testKey);
gStorageSupported = true;
} catch (error) {
gStorageSupported = false;
}
}
return gStorageSupported;
}
In your source, just use:
localStorageSet( 'foobar', 'yes' );
...
var foo = localStorageGet( 'foobar' );
...
I've been using
quit -n terminal
at the end of my scripts. You have to have the terminal set to never prompt in preferences
So Terminal > Preferences > Settings > Shell When the shell exits Close the window Prompt before closing Never
Here's one simple deadlock in Java. We need two resources for demonstrating deadlock. In below example, one resource is class lock(via sync method) and the other one is an integer 'i'
public class DeadLock {
static int i;
static int k;
public static synchronized void m1(){
System.out.println(Thread.currentThread().getName()+" executing m1. Value of i="+i);
if(k>0){i++;}
while(i==0){
System.out.println(Thread.currentThread().getName()+" waiting in m1 for i to be > 0. Value of i="+i);
try { Thread.sleep(10000);} catch (InterruptedException e) { e.printStackTrace(); }
}
}
public static void main(String[] args) {
Thread t1 = new Thread("t1") {
public void run() {
m1();
}
};
Thread t2 = new Thread("t2") {
public void run() {
try { Thread.sleep(100);} catch (InterruptedException e) { e.printStackTrace(); }
k++;
m1();
}
};
t1.start();
t2.start();
}
}
Remember that by default the return value from the input will be a string and not an integer. You cannot compare strings with booleans like <, >, =>, <= (unless you are comparing the length). Therefore your code should look like this:
number = 23
guess = int(input('Enter a number: ')) # The var guess will be an integer
if guess == number:
print('Congratulations! You guessed it.')
elif guess != number:
print('Wrong Number')
well, just a quick and dirty suggestion for simple 1-level directory structure without spaces, [edit] and for directories containing only ONE type of files that I found useful (at some point from http://www.pcreview.co.uk/forums/can-check-if-folder-empty-bat-file-t1468868.html):
for /f %a in ('dir /ad/b') do if not exist %a\*.xml echo %a Empty
/ad : shows only directory entries
/b : use bare format (just names)
[edit] using plain asterisk to check for ANY file (%a\* above) won't work, thanks for correction
therefore, deleting would be:
for /f %a in ('dir /ad/b') do if not exist %a\*.xml rmdir %a
another solution disown the job
$ nohup node server.js &
[1] 1711
$ disown -h %1
I write python script with IDLE3.8(python 3.8.0)
I have solved this question:
if the path is
shelve.open('C:\\database.dat')
it will be
PermissionError: [Errno 13] Permission denied: 'C:\\database.dat.dat'
.
But when I test to set the path as
shelve.open('E:\\database.dat')
That is OK!!!
Then I test all the drive(such as C,D,F...) on my computer,Only when the Path set in Disk
C:\\
will get the permission denied error. So I think this is a protect path in windows to avoid python script to change or read files in system Disk(Disk C)
If the first cell returned is a null
, the result in .NET will be DBNull.Value
If no cells are returned, the result in .NET will be null
; you cannot call ToString()
on a null
. You can of course capture what ExecuteScalar
returns and process the null
/ DBNull
/ other cases separately.
Since you are grouping etc, you presumably could potentially have more than one group. Frankly I'm not sure ExecuteScalar
is your best option here...
Additional: the sql in the question is bad in many ways:
I strongly suggest you parameterize; perhaps with something like "dapper" to make it easy:
int count = conn.Query<int>(
@"select COUNT(idemp_atd) absentDayNo from td_atd
where absentdate_atd between @sdate and @edate
and idemp_atd=@idemp group by idemp_atd",
new {sdate, edate, idemp}).FirstOrDefault();
all problems solved, including the "no rows" scenario. The dates are passed as dates (not strings); the injection hole is closed by use of a parameter. You get query-plan re-use as an added bonus, too. The group by
here is redundant, BTW - if there is only one group (via the equality condition) you might as well just select COUNT(1)
.
Just notepad ~/.bashrc
from the git bash shell and save your file.That should be all.
NOTE: Please ensure that you need to restart your terminal for changes to be reflected.
Try to use the <font>
tag
?<table>
<thead>
<tr>
<th><font color="#FFF">Header 1</font></th>
<th><font color="#FFF">Header 1</font></th>
<th><font color="#FFF">Header 1</font></th>
</tr>
</thead>
<tbody>
<tr>
<td>blah blah</td>
<td>blah blah</td>
<td>blah blah</td>
</tr>
</tbody>
</table>
But I think this should work, too:
?<table>
<thead>
<tr>
<th color="#FFF">Header 1</th>
<th color="#FFF">Header 1</th>
<th color="#FFF">Header 1</th>
</tr>
</thead>
<tbody>
<tr>
<td>blah blah</td>
<td>blah blah</td>
<td>blah blah</td>
</tr>
</tbody>
</table>
EDIT:
Crossbrowser solution:
use capitals in HEX-color.
<th bgcolor="#5D7B9D" color="#FFFFFF"><font color="#FFFFFF">Header 1</font></th>
https://github.com/alexanderdickson/waitForImages
$('selector').waitForImages({
finished: function() {
// ...
},
each: function() {
// ...
},
waitForAll: true
});
Python itself comes with an editor that you can access from the IDLE File > New File menu option.
Write the code in that file, save it as [filename].py and then (in that same file editor window) press F5 to execute the code you created in the IDLE Shell window.
Note: it's just been the easiest and most straightforward way for me so far.
If they're actually managed assemblies, you can use ILMerge. For native DLLs, you'll have a bit more work to do.
See also: How can a C++ windows dll be merged into a C# application exe?
Here is setting headers from github sample:
StringRequest myReq = new StringRequest(Method.POST,
"http://ave.bolyartech.com/params.php",
createMyReqSuccessListener(),
createMyReqErrorListener()) {
protected Map<String, String> getParams() throws
com.android.volley.AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("param1", num1);
params.put("param2", num2);
return params;
};
};
queue.add(myReq);
Ok, try this:
Get the image with the transparent circle - http://i39.tinypic.com/15s97vd.png Put that image in a html element and change that element's background color via css. This way you get the logo with the circle in the color defined in the stylesheet.
The html
<div class="badassColorChangingLogo">
<img src="http://i39.tinypic.com/15s97vd.png" />
Or download the image and change the path to the downloaded image in your machine
</div>
The css
div.badassColorChangingLogo{
background-color:white;
}
div.badassColorChangingLogo:hover{
background-color:blue;
}
Keep in mind that this wont work on non-alpha capable browsers like ie6, and ie7. for ie you can use a js fix. Google ddbelated png fix and you can get the script.
The best cross-browser solution is
background: #fff;
background: -moz-linear-gradient(#fff, #000);
background: -webkit-linear-gradient(#fff, #000);
background: -o-linear-gradient(#fff, #000);
background: -ms-linear-gradient(#fff, #000);/*For IE10*/
background: linear-gradient(#fff, #000);
filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#ffffff', endColorstr='#000000');/*For IE7-8-9*/
height: 1%;/*For IE7*/
First, Jonathan's point about vectorizing is correct. If your getWellID() function is vectorized, then you can skip the loop and just use cat or write.csv:
write.csv(data.frame(wellid=getWellID(well$name, well$plate),
value1=well$value1, value2=well$value2), file=outputFile)
If getWellID() isn't vectorized, then Jonathan's recommendation of using by
or knguyen's suggestion of apply
should work.
Otherwise, if you really want to use for
, you can do something like this:
for(i in 1:nrow(dataFrame)) {
row <- dataFrame[i,]
# do stuff with row
}
You can also try to use the foreach
package, although it requires you to become familiar with that syntax. Here's a simple example:
library(foreach)
d <- data.frame(x=1:10, y=rnorm(10))
s <- foreach(d=iter(d, by='row'), .combine=rbind) %dopar% d
A final option is to use a function out of the plyr
package, in which case the convention will be very similar to the apply function.
library(plyr)
ddply(dataFrame, .(x), function(x) { # do stuff })
You must not have made jQuery available to your script.
Add this to the top of your file:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
This issue is related to the jQuery/JavaScript file not added to the PHP/JSP/ASP file properly. This goes out and gets the jQuery code from the source. You could download that and reference it locally on the server which would be faster.
Or either one can directly link it to jQuery or GoogleCDN or MicrosoftCDN.
Icon with default bootstrap Style
<div class="input-group">
<input type="text" class="form-control" placeholder="From" aria-label="from" aria-describedby="from">
<div class="input-group-append">
<span class="input-group-text"><i class="fas fa-map-marker-alt"></i></span>
</div>
</div>
Icon Inside Input with default bootstrap class
<div class="input-group">
<input type="text" class="form-control border-right-0" placeholder="From" aria-label="from" aria-describedby="from">
<div class="input-group-append">
<span class="input-group-text bg-transparent"><i class="fas fa-map-marker-alt"></i></span>
</div>
</div>
Icon Inside Input with small custom css
<div class="input-group">
<input type="text" class="form-control rounded-right" placeholder="From" aria-label="from" aria-describedby="from">
<span class="icon-inside"><i class="fas fa-map-marker-alt"></i></span>
</div>
Custom Css
.icon-inside {
position: absolute;
right: 10px;
top: calc(50% - 12px);
pointer-events: none;
font-size: 16px;
font-size: 1.125rem;
color: #c4c3c3;
z-index:3;
}
.icon-inside {_x000D_
position: absolute;_x000D_
right: 10px;_x000D_
top: calc(50% - 12px);_x000D_
pointer-events: none;_x000D_
font-size: 16px;_x000D_
font-size: 1.125rem;_x000D_
color: #c4c3c3;_x000D_
z-index:3;_x000D_
}
_x000D_
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" />_x000D_
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">_x000D_
_x000D_
<div class="container">_x000D_
<h5 class="mt-3">Icon <small>with default bootstrap Style</small><h5>_x000D_
<div class="input-group">_x000D_
<input type="text" class="form-control" placeholder="From" aria-label="from" aria-describedby="from">_x000D_
<div class="input-group-append">_x000D_
<span class="input-group-text"><i class="fas fa-map-marker-alt"></i></span>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<h5 class="mt-3">Icon Inside Input <small>with default bootstrap class</small><h5>_x000D_
<div class="input-group">_x000D_
<input type="text" class="form-control border-right-0" placeholder="From" aria-label="from" aria-describedby="from">_x000D_
<div class="input-group-append">_x000D_
<span class="input-group-text bg-transparent"><i class="fas fa-map-marker-alt"></i></span>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<h5 class="mt-3">Icon Inside Input<small> with small custom css</small><h5>_x000D_
<div class="input-group">_x000D_
<input type="text" class="form-control rounded-right" placeholder="From" aria-label="from" aria-describedby="from">_x000D_
<span class="icon-inside"><i class="fas fa-map-marker-alt"></i></span>_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
You can increase client_max_body_size and upload_max_filesize + post_max_size all day long. Without adjusting HTTP timeout it will never work.
//You need to adjust this, and probably on PHP side also. client_body_timeout 2min // 1GB fileupload
re.match attempts to match a pattern at the beginning of the string. re.search attempts to match the pattern throughout the string until it finds a match.
For jQuery 1.6+ :
.attr() is deprecated for properties; use the new .prop() function instead as:
$('#myCheckbox').prop('checked', true); // Checks it
$('#myCheckbox').prop('checked', false); // Unchecks it
For jQuery < 1.6:
To check/uncheck a checkbox, use the attribute checked
and alter that. With jQuery you can do:
$('#myCheckbox').attr('checked', true); // Checks it
$('#myCheckbox').attr('checked', false); // Unchecks it
Cause you know, in HTML, it would look something like:
<input type="checkbox" id="myCheckbox" checked="checked" /> <!-- Checked -->
<input type="checkbox" id="myCheckbox" /> <!-- Unchecked -->
However, you cannot trust the .attr() method to get the value of the checkbox (if you need to). You will have to rely in the .prop() method.
You can subtract 7 from the current date with this:
WHERE datex BETWEEN DATEADD(day, -7, GETDATE()) AND GETDATE()
I just convert liquidki's answer into Ubuntu commands. On an Ubuntu based system it works!:
sudo apt -y install python-pip
pip install -U pip
sudo pip install -U setuptools
Answered provided by Tom Saleeba is very helpful. Today I also struggled with the same error
Apr 28, 2015 7:53:27 PM org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart
I followed the suggestion and added the logging.properties file. And below was my reason of failure:
java.lang.IllegalStateException: Cannot set web app root system property when WAR file is not expanded
The root cause of the issue was a listener (Log4jConfigListener) that I added into the web.xml. And as per the link SEVERE: Exception org.springframework.web.util.Log4jConfigListener , this listener cannot be added within a WAR that is not expanded.
It may be helpful for someone to know that this was happening on OpenShift JBoss gear.
Use the correct version of MSBuild. Set Environment Variable to:
C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin
This will also work for VS 2019 projects
Previously we were setting it to C:\Windows\Microsoft.NET\Framework\v4.0.30319
I have installed python 3.7.4. First, I tried python in my command prompt. It was saying that 'Python is not recognized command......'. Then I tried 'py' command and it works.
My sample command is:
py hacker.py
for oracle you could do something like below
alter table mytable add (myfield integer);
update mytable set myfield = rownum;
Use a NavigableMap
implementation, like TreeMap
.
/* Setup */
NavigableMap<Integer, Optional<String>> messages = new TreeMap<>();
messages.put(Integer.MIN_VALUE, Optional.empty());
messages.put(1, Optional.of("testing case 1 to 5"));
messages.put(6, Optional.of("testing case 6 to 10"));
messages.put(11, Optional.empty());
/* Use */
messages.floorEntry(3).getValue().ifPresent(System.out::println);
Where a
is the slice, and i
is the index of the element you want to delete:
a = append(a[:i], a[i+1:]...)
...
is syntax for variadic arguments in Go.
Basically, when defining a function it puts all the arguments that you pass into one slice of that type. By doing that, you can pass as many arguments as you want (for example, fmt.Println
can take as many arguments as you want).
Now, when calling a function, ...
does the opposite: it unpacks a slice and passes them as separate arguments to a variadic function.
So what this line does:
a = append(a[:0], a[1:]...)
is essentially:
a = append(a[:0], a[1], a[2])
Now, you may be wondering, why not just do
a = append(a[1:]...)
Well, the function definition of append
is
func append(slice []Type, elems ...Type) []Type
So the first argument has to be a slice of the correct type, the second argument is the variadic, so we pass in an empty slice, and then unpack the rest of the slice to fill in the arguments.
Crash Null Point Exception Fix: I had a case where the keyboard might not open when the user clicks the button. You have to write an if statement to check that getCurrentFocus() isn't a null:
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if(getCurrentFocus() != null) {
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
trying to access the /s2/profile/photo url works for most users but not all.
The only full proof method is to use the Google+ API. You don't need user authentication to request public profile data so it's a rather simple method:
Get a Google+ API key on https://cloud.google.com/console
Make a simple GET request to: https://www.googleapis.com/plus/v1/people/+< username >?key=
Note the + before the username. If you use user ids instead (the long string of digits), you don't need the +
It’s easy; just do the following:
rvm implode
or
rm -rf ~/.rvm
And don’t forget to remove the script calls in the following files:
~/.bashrc
~/.bash_profile
~/.profile
And maybe others depending on whatever shell you’re using.
If you have two lists that have the predicted and actual values; as it appears you do, you can pass them to a function that will calculate TP, FP, TN, FN with something like this:
def perf_measure(y_actual, y_hat):
TP = 0
FP = 0
TN = 0
FN = 0
for i in range(len(y_hat)):
if y_actual[i]==y_hat[i]==1:
TP += 1
if y_hat[i]==1 and y_actual[i]!=y_hat[i]:
FP += 1
if y_actual[i]==y_hat[i]==0:
TN += 1
if y_hat[i]==0 and y_actual[i]!=y_hat[i]:
FN += 1
return(TP, FP, TN, FN)
From here I think you will be able to calculate rates of interest to you, and other performance measure like specificity and sensitivity.
As already mentioned the correct way to have a space in an XML file is by using \u0020
which is the unicode character for a space.
Example:
<string name="spelatonertext3">-4,\u00205,\u0020-5,\u00206,\u0020-6</string>
Other suggestions have said to use  
or  
but there is two downsides to this. The first downside is that these are ASCII characters so you are relying on something like a TextView to parse them. The second downside is that  
can sometimes cause strange wrapping in TextViews.
I create the tag like this and then I push it to GitHub:
git tag -a v1.1 -m "Version 1.1 is waiting for review"
git push --tags
Counting objects: 1, done.
Writing objects: 100% (1/1), 180 bytes, done.
Total 1 (delta 0), reused 0 (delta 0)
To [email protected]:neoneye/triangle_draw.git
* [new tag] v1.1 -> v1.1
All "normal" triggers in SQL Server are "AFTER ..." triggers. There are no "BEFORE ..." triggers.
To do something before an update, check out INSTEAD OF UPDATE Triggers.
if it is a RSA key
openssl rsa -pubout -in my_rsa_key.pem
if you need it in a format for openssh , please see Use RSA private key to generate public key?
Note that public key is generated from the private key and ssh uses the identity file (private key file) to generate and send public key to server and un-encrypt the encrypted token from the server via the private key in identity file.
I had the same problem. I wanted to create a view to show information of the most recent year, from a table with records from 2009 to 2011. Here's the original query:
SELECT a.*
FROM a
JOIN (
SELECT a.alias, MAX(a.year) as max_year
FROM a
GROUP BY a.alias
) b
ON a.alias=b.alias and a.year=b.max_year
Outline of solution:
Here's the solution query:
CREATE VIEW v_max_year AS
SELECT alias, MAX(year) as max_year
FROM a
GROUP BY a.alias;
CREATE VIEW v_latest_info AS
SELECT a.*
FROM a
JOIN v_max_year b
ON a.alias=b.alias and a.year=b.max_year;
It works fine on mysql 5.0.45, without much of a speed penalty (compared to executing the original sub-query select without any views).
try using form collection
<input id="responsable" value="True" name="checkResp" type="checkbox" />
[HttpPost]
public ActionResult Index(FormCollection collection)
{
if(!string.IsNullOrEmpty(collection["checkResp"])
{
string checkResp=collection["checkResp"];
bool checkRespB=Convert.ToBoolean(checkResp);
}
}
You can do this very simply using LINQ.
Make sure this using is at the top of your C# file:
using System.Linq;
Then use the ToList
extension method.
Example:
IEnumerable<int> enumerable = Enumerable.Range(1, 300);
List<int> asList = enumerable.ToList();
STEP 1 Install Git.
STEP 2 Add the path of your git to the environment variables like this C:\Program Files (x86)\Git\bin.
STEP 3 Open new terminal session and try ssh-keygen. It will work.
NOTE New Terminal Window is must!
(This is for the benefit of others who may refer)
You can simply use cin and a char array. The cin input is delimited by the first whitespace it encounters.
#include<iostream>
using namespace std;
main()
{
char word[50];
cin>>word;
while(word){
//Do stuff with word[]
cin>>word;
}
}
A simple solution:
Encode the image as a jpeg and look for a substantial change in filesize.
I've implemented something similar with video thumbnails, and had a lot of success and scalability.
Underscore js solution
let samplLst = [{id:1,title:Lorem},{id:2,title:Ipsum}]
let sampleKey = _.findLastIndex(samplLst,{_id:2});
//result would be 1
console.log(samplLst[sampleKey])
//output - {id:2,title:Ipsum}
To be precise and crisp
LAMP is L(Linux) A(Apache) M(Mysql) P(PHP5) is a combined package intended for web-application development.
The easiest way to install Lamp is as follows
1) Using tasksel
Below are the list of commands
sudo apt-get update sudo apt-get install tasksel sudo tasksel ( will give you a prompt check the LAMP server and select Ok)
Thats it LAMP is ready to glow your knowledge.
One liner code:
Note: Use System
and System.Text
directives.
Encode:
string encodedStr = Convert.ToBase64String(Encoding.UTF8.GetBytes("inputStr"));
Decode:
string inputStr = Encoding.UTF8.GetString(Convert.FromBase64String(encodedStr));
Best solution for me so far
Select Database -> Right Click -> Tasks -> Generate Scripts - will open wizard for generating scripts. After choosing objects in set Scripting option click Advanced Button. Under "Script DROP and CREATE" select Script DROP.
Run script.
If you install Node using the windows installer, there is nothing you have to do. It adds path to node and npm.
You can also use Windows setx command for changing system environment variables. No reboot is required. Just logout/login. Or just open a new cmd window, if you want to see the changing there.
setx PATH "%PATH%;C:\Program Files\nodejs"
private static final String hostExtractorRegexString = "(?:https?://)?(?:www\\.)?(.+\\.)(com|au\\.uk|co\\.in|be|in|uk|org\\.in|org|net|edu|gov|mil)";
private static final Pattern hostExtractorRegexPattern = Pattern.compile(hostExtractorRegexString);
public static String getDomainName(String url){
if (url == null) return null;
url = url.trim();
Matcher m = hostExtractorRegexPattern.matcher(url);
if(m.find() && m.groupCount() == 2) {
return m.group(1) + m.group(2);
}
return null;
}
Explanation : The regex has 4 groups. The first two are non-matching groups and the next two are matching groups.
The first non-matching group is "http" or "https" or ""
The second non-matching group is "www." or ""
The second matching group is the top level domain
The first matching group is anything after the non-matching groups and anything before the top level domain
The concatenation of the two matching groups will give us the domain/host name.
PS : Note that you can add any number of supported domains to the regex.
@override
Widget build(BuildContext context) {
return Theme(
data: ThemeData(brightness: Brightness.dark),
child: Scaffold()
....
)
}
very simple answer
Here is a property I use in one of my applications
public List<string> OperationModes
{
get
{
return Enum.GetNames(typeof(SomeENUM)).ToList();
}
}
AMD
CommonJS:
Example
upper.js file
exports.uppercase = str => str.toUpperCase()
main.js file
const uppercaseModule = require('uppercase.js')
uppercaseModule.uppercase('test')
Summary
Resources:
Using .format
from Python 2.6 and higher:
>>> print '{}{}{}{}'.format(*[7,7,7,7])
7777
>>> data = [7, 7, 7, 7] * 3
>>> print ('{}'*len(data)).format(*data)
777777777777777777777777
For Python 3:
>>> print(('{}'*len(data)).format(*data))
777777777777777777777777
The block approach avoids running the lookup algorithm for every key:
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL* stop) {
NSLog(@"%@ => %@", key, value);
}];
Even though NSDictionary
is implemented as a hashtable (which means that the cost of looking up an element is O(1)
), lookups still slow down your iteration by a constant factor.
My measurements show that for a dictionary d
of numbers ...
NSMutableDictionary* dict = [NSMutableDictionary dictionary];
for (int i = 0; i < 5000000; ++i) {
NSNumber* value = @(i);
dict[value.stringValue] = value;
}
... summing up the numbers with the block approach ...
__block int sum = 0;
[dict enumerateKeysAndObjectsUsingBlock:^(NSString* key, NSNumber* value, BOOL* stop) {
sum += value.intValue;
}];
... rather than the loop approach ...
int sum = 0;
for (NSString* key in dict)
sum += [dict[key] intValue];
... is about 40% faster.
EDIT: The new SDK (6.1+) appears to optimise loop iteration, so the loop approach is now about 20% faster than the block approach, at least for the simple case above.
// Following is angular 2.0 directive for window re size that adjust scroll bar for give element as per your tag
---- angular 2.0 window resize directive.
import { Directive, ElementRef} from 'angular2/core';
@Directive({
selector: '[resize]',
host: { '(window:resize)': 'onResize()' } // Window resize listener
})
export class AutoResize {
element: ElementRef; // Element that associated to attribute.
$window: any;
constructor(_element: ElementRef) {
this.element = _element;
// Get instance of DOM window.
this.$window = angular.element(window);
this.onResize();
}
// Adjust height of element.
onResize() {
$(this.element.nativeElement).css('height', (this.$window.height() - 163) + 'px');
}
}
I had modified my answer tons of times and realized i don't have to say anything, python had explained itself already.
a = 'string'
a.replace('t', '_')
print(a)
>>> 'string'
a = a.replace('t', '_')
print(a)
>>> 's_ring'
b = 100
b + 1
print(b)
>>> 100
b = b + 1
print(b)
>>> 101
def test_id(arg):
c = id(arg)
arg = 123
d = id(arg)
return
a = 'test ids'
b = id(a)
test_id(a)
e = id(a)
# b = c = e != d
# this function do change original value
del change_like_mutable(arg):
arg.append(1)
arg.insert(0, 9)
arg.remove(2)
return
test_1 = [1, 2, 3]
change_like_mutable(test_1)
# this function doesn't
def wont_change_like_str(arg):
arg = [1, 2, 3]
return
test_2 = [1, 1, 1]
wont_change_like_str(test_2)
print("Doesn't change like a imutable", test_2)
This devil is not the reference / value / mutable or not / instance, name space or variable / list or str, IT IS THE SYNTAX, EQUAL SIGN.
If this is a simple Java project, You essentially create a new project and give the location of the existing code. The project wizard will tell you that it will use existing sources.
Also, Eclipse 3.3.2 is ancient history, you guys should really upgrade. This is like using Visual Studio 5.
I will just add a blank ("") to the end of the variable and do the comparison. Something like below should work even when that variable is null. You can also trim the variable just in case of spaces.
If provider & "" <> "" Then
url = url & "&provider=" & provider
End if
Here's another suggestion:
public interface Service<T> {
T execute();
}
using this simple interface you can pass arguments via constructor in the concrete service classes:
public class FooService implements Service<String> {
private final String input1;
private final int input2;
public FooService(String input1, int input2) {
this.input1 = input1;
this.input2 = input2;
}
@Override
public String execute() {
return String.format("'%s%d'", input1, input2);
}
}
If you don't use innodb_file_per_table, reclaiming disk space is possible, but quite tedious, and requires a significant amount of downtime.
The How To is pretty in-depth - but I pasted the relevant part below.
Be sure to also retain a copy of your schema in your dump.
Currently, you cannot remove a data file from the system tablespace. To decrease the system tablespace size, use this procedure:
Use mysqldump to dump all your InnoDB tables.
Stop the server.
Remove all the existing tablespace files, including the ibdata and ib_log files. If you want to keep a backup copy of the information, then copy all the ib* files to another location before the removing the files in your MySQL installation.
Remove any .frm files for InnoDB tables.
Configure a new tablespace.
Restart the server.
Import the dump files.
>>> import datetime
>>> now = datetime.datetime.now()
>>> print unicode(now.replace(microsecond=0))
2011-11-03 11:19:07
This:
<div class="details @(Model.Details.Count > 0 ? "show" : "hide")">
will render this:
<div class="details hide">
and is the mark-up I want.
Restart your Android device. Things started to work for me after I restarted the device.
Check your error log file and then use the tail command as:
tail -200f /var/log/redis_6379.log
or
tail -200f /var/log/redis.log
According to your error file name..
You can use DateValue
to convert your string to a date in this instance
Dim c As Range
For Each c In ActiveSheet.UsedRange.columns("A").Cells
c.Value = DateValue(c.Value)
Next c
It can convert yyyy-mm-dd
format string directly into a native Excel date value.
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementsByClassName('featured-heading')[0].setAttribute('style', 'background-color: green')");
I could add an attribute using the above code in java
In this case you use -1.
You will want to use the String class' Split() method and pass in a regular expression of "\D+" which will match at least one non-number.
myString.split("\\D+");
I think the fix is relative easy without disabling this feature.
def kos_root():
"""Return the pathname of the KOS root directory."""
global _kos_root
if _kos_root: return _kos_root
All you need to do is add the triple double quotes string in every function.
for Microsoft SQL Server Management Studio 2012,2008.. First Copy your database file .mdf and log file .ldf & Paste in your sql server install file in Programs Files->Microsoft SQL Server->MSSQL10.SQLEXPRESS->MSSQL->DATA. Then open Microsoft Sql Server . Right Click on Databases -> Select Attach...option.
class stack
{ private int top;
private int[] element;
stack()
{element=new int[10];
top=-1;
}
void push(int item)
{top++;
if(top==9)
System.out.println("Overflow");
else
{
top++;
element[top]=item;
}
void pop()
{if(top==-1)
System.out.println("Underflow");
else
top--;
}
void display()
{
System.out.println("\nTop="+top+"\nElement="+element[top]);
}
public static void main(String args[])
{
stack s1=new stack();
s1.push(10);
s1.display();
s1.push(20);
s1.display();
s1.push(30);
s1.display();
s1.pop();
s1.display();
}
}
Output
Top=0
Element=10
Top=1
Element=20
Top=2
Element=30
Top=1
Element=20
For multiple elements, you should give it a class rather than id eg:
<input type="text" class="task" name="task[]" />
Now you can get those using jquery something like this:
$('.task').each(function(){
alert($(this).val());
});
If you want to get a constraint by the column or table names, or you want to get all the constraints in the database, look to other answers. However, if you're just looking for exactly what the question asks, namely, to "test if a given default constraint exists ... by the name of the constraint", then there's a much easier way.
Here's a future-proof answer that doesn't use the sysobjects
or other sys
tables at all:
IF object_id('DF_CONSTRAINT_NAME', 'D') IS NOT NULL BEGIN
-- constraint exists, work with it.
END
The answers above are great, but I needed a simple example to alleviate some concerns that I have had in the past. I wanted to make sure it was indeed treating each column separately. I am now reassured and can't find what example had caused me concern. All columns ARE scaled separately as described by those above.
import pandas as pd
import scipy.stats as ss
from sklearn.preprocessing import StandardScaler
data= [[1, 1, 1, 1, 1],[2, 5, 10, 50, 100],[3, 10, 20, 150, 200],[4, 15, 40, 200, 300]]
df = pd.DataFrame(data, columns=['N0', 'N1', 'N2', 'N3', 'N4']).astype('float64')
sc_X = StandardScaler()
df = sc_X.fit_transform(df)
num_cols = len(df[0,:])
for i in range(num_cols):
col = df[:,i]
col_stats = ss.describe(col)
print(col_stats)
DescribeResult(nobs=4, minmax=(-1.3416407864998738, 1.3416407864998738), mean=0.0, variance=1.3333333333333333, skewness=0.0, kurtosis=-1.3599999999999999)
DescribeResult(nobs=4, minmax=(-1.2828087129930659, 1.3778315806221817), mean=-5.551115123125783e-17, variance=1.3333333333333337, skewness=0.11003776770595125, kurtosis=-1.394993095506219)
DescribeResult(nobs=4, minmax=(-1.155344148338584, 1.53471088361394), mean=0.0, variance=1.3333333333333333, skewness=0.48089217736510326, kurtosis=-1.1471008824318165)
DescribeResult(nobs=4, minmax=(-1.2604572012883055, 1.2668071116222517), mean=-5.551115123125783e-17, variance=1.3333333333333333, skewness=0.0056842140599118185, kurtosis=-1.6438177182479734)
DescribeResult(nobs=4, minmax=(-1.338945389819976, 1.3434309690153527), mean=5.551115123125783e-17, variance=1.3333333333333333, skewness=0.005374558840039456, kurtosis=-1.3619131970819205)
The scipy.stats module is correctly reporting the "sample" variance, which uses (n - 1) in the denominator. The "population" variance would use n in the denominator for the calculation of variance. To understand better, please see the code below that uses scaled data from the first column of the data set above:
import scipy.stats as ss
sc_Data = [[-1.34164079], [-0.4472136], [0.4472136], [1.34164079]]
col_stats = ss.describe([-1.34164079, -0.4472136, 0.4472136, 1.34164079])
print(col_stats)
print()
mean_by_hand = 0
for row in sc_Data:
for element in row:
mean_by_hand += element
mean_by_hand /= 4
variance_by_hand = 0
for row in sc_Data:
for element in row:
variance_by_hand += (mean_by_hand - element)**2
sample_variance_by_hand = variance_by_hand / 3
sample_std_dev_by_hand = sample_variance_by_hand ** 0.5
pop_variance_by_hand = variance_by_hand / 4
pop_std_dev_by_hand = pop_variance_by_hand ** 0.5
print("Sample of Population Calcs:")
print(mean_by_hand, sample_variance_by_hand, sample_std_dev_by_hand, '\n')
print("Population Calcs:")
print(mean_by_hand, pop_variance_by_hand, pop_std_dev_by_hand)
DescribeResult(nobs=4, minmax=(-1.34164079, 1.34164079), mean=0.0, variance=1.3333333422778562, skewness=0.0, kurtosis=-1.36000000429325)
Sample of Population Calcs:
0.0 1.3333333422778562 1.1547005422523435
Population Calcs:
0.0 1.000000006708392 1.000000003354196
If some item(s) exist in both lists you may use
var all = list1.Concat(list2).Concat(list3) ... Concat(listN).Distinct().ToList();
So yes, you should prefer the shadowPath property for performance, but also: From the header file of CALayer.shadowPath
Specifying the path explicitly using this property will usually * improve rendering performance, as will sharing the same path * reference across multiple layers
A lesser known trick is sharing the same reference across multiple layers. Of course they have to use the same shape, but this is common with table/collection view cells.
I don't know why it gets faster if you share instances, i'm guessing it caches the rendering of the shadow and can reuse it for other instances in the view. I wonder if this is even faster with
override
is a C++11 keyword which means that a method is an "override" from a method from a base class. Consider this example:
class Foo
{
public:
virtual void func1();
}
class Bar : public Foo
{
public:
void func1() override;
}
If B::func1()
signature doesn't equal A::func1()
signature a compilation error will be generated because B::func1()
does not override A::func1()
, it will define a new method called func1()
instead.
date -j -f "%Y-%m-%d %H:%M:%S" "2020-04-07 00:00:00" "+%s"
It will print the dynamic seconds when without %H:%M:%S
and 00:00:00
.
To determine which branch you are now on, look at the side bar, under BRANCHES, you are in the branch that is in BOLD LETTERS.
Meanwhile I have found the (for me) perfect solution: nexe, which creates a single executable from a Node.js application including all of its modules.
It's the next best thing to an ideal solution.
Based on the error you showed ('footballforum' is missing required Java project: 'ApiDemos'), I would check your build path. Right-click the footballforum project and choose Build Path > Configure Build Path. Make sure ApiDemos is on the projects tab of the build path options.
How about suppressing errors on each line specific to each error?
Something like this: https://pylint.readthedocs.io/en/latest/user_guide/message-control.html
Error: [pylint] Class 'class_name' has no 'member_name' member It can be suppressed on that line by:
# pylint: disable=no-member
I'm confused. The example I found avoids the static property entirely and uses the UI thread:
public class example extends Activity {
final int HANDLE_FIX_SCREEN = 1000;
public Handler DBthreadHandler = new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message msg) {
int imsg;
imsg = msg.what;
if (imsg == HANDLE_FIX_SCREEN) {
doSomething();
}
}
};
}
The thing I like about this solution is there is no problem trying to mix class and method variables.
Jupyter has its own PATH variable, JUPYTER_PATH.
Adding this line to the .bashrc
file worked for me:
export JUPYTER_PATH=<directory_for_your_module>:$JUPYTER_PATH
You have to use GetThumbnailImage
method in the Image
class:
https://msdn.microsoft.com/en-us/library/8t23aykb%28v=vs.110%29.aspx
Here's a rough example that takes an image file and makes a thumbnail image from it, then saves it back to disk.
Image image = Image.FromFile(fileName);
Image thumb = image.GetThumbnailImage(120, 120, ()=>false, IntPtr.Zero);
thumb.Save(Path.ChangeExtension(fileName, "thumb"));
It is in the System.Drawing namespace (in System.Drawing.dll).
Behavior:
If the Image contains an embedded thumbnail image, this method retrieves the embedded thumbnail and scales it to the requested size. If the Image does not contain an embedded thumbnail image, this method creates a thumbnail image by scaling the main image.
Important: the remarks section of the Microsoft link above warns of certain potential problems:
The
GetThumbnailImage
method works well when the requested thumbnail image has a size of about 120 x 120 pixels. If you request a large thumbnail image (for example, 300 x 300) from an Image that has an embedded thumbnail, there could be a noticeable loss of quality in the thumbnail image.It might be better to scale the main image (instead of scaling the embedded thumbnail) by calling the
DrawImage
method.
A shot in the dark, but From the looks of your error message, it seems that either the sqlserver instance is not running on port 1433 or something is blocking the requests to that port
I prefer using the ggfortify
library. It is a ggplot2
wrapper that recognizes the type of object inside the autoplot function and chooses the best ggplot methods to plot. At least I don't have to remember the syntax of ggplot2.
library(ggfortify)
ts1 <- 1:100
ts2 <- 1:100*0.8
autoplot(ts( cbind(ts1, ts2) , start = c(2010,5), frequency = 12 ),
facets = FALSE)
As Matt Ball's answer explains, or
is "and/or". But or
doesn't work with in
the way you use it above. You have to say if "a" in someList or "á" in someList or...
. Or better yet,
if any(c in someList for c in ("a", "á", "à", "ã", "â")):
...
That's the answer to your question as asked.
However, there are a few more things to say about the example code you've posted. First, the chain of someList.remove... or someList remove...
statements here is unnecessary, and may result in unexpected behavior. It's also hard to read! Better to break it into individual lines:
someList.remove("a")
someList.remove("á")
...
Even that's not enough, however. As you observed, if the item isn't in the list, then an error is thrown. On top of that, using remove
is very slow, because every time you call it, Python has to look at every item in the list. So if you want to remove 10 different characters, and you have a list that has 100 characters, you have to perform 1000 tests.
Instead, I would suggest a very different approach. Filter the list using a set
, like so:
chars_to_remove = set(("a", "á", "à", "ã", "â"))
someList = [c for c in someList if c not in chars_to_remove]
Or, change the list in-place without creating a copy:
someList[:] = (c for c in someList if c not in chars_to_remove)
These both use list comprehension syntax to create a new list. They look at every character in someList
, check to see of the character is in chars_to_remove
, and if it is not, they include the character in the new list.
This is the most efficient version of this code. It has two speed advantages:
someList
once. Instead of performing 1000 tests, in the above scenario, it performs only 100. chars_to_remove
is a set
. If it chars_to_remove
were a list
or tuple
, then each test would really be 10 tests in the above scenario -- because each character in the list would need to be checked individually.Since Dave asked for me to repeat my answer to Omitting all xsi and xsd namespaces when serializing an object in .NET, I have updated this post and repeated my answer here from the afore-mentioned link. The example used in this answer is the same example used for the other question. What follows is copied, verbatim.
After reading Microsoft's documentation and several solutions online, I have discovered the solution to this problem. It works with both the built-in XmlSerializer
and custom XML serialization via IXmlSerialiazble
.
To whit, I'll use the same MyTypeWithNamespaces
XML sample that's been used in the answers to this question so far.
[XmlRoot("MyTypeWithNamespaces", Namespace="urn:Abracadabra", IsNullable=false)]
public class MyTypeWithNamespaces
{
// As noted below, per Microsoft's documentation, if the class exposes a public
// member of type XmlSerializerNamespaces decorated with the
// XmlNamespacesDeclarationAttribute, then the XmlSerializer will utilize those
// namespaces during serialization.
public MyTypeWithNamespaces( )
{
this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
// Don't do this!! Microsoft's documentation explicitly says it's not supported.
// It doesn't throw any exceptions, but in my testing, it didn't always work.
// new XmlQualifiedName(string.Empty, string.Empty), // And don't do this:
// new XmlQualifiedName("", "")
// DO THIS:
new XmlQualifiedName(string.Empty, "urn:Abracadabra") // Default Namespace
// Add any other namespaces, with prefixes, here.
});
}
// If you have other constructors, make sure to call the default constructor.
public MyTypeWithNamespaces(string label, int epoch) : this( )
{
this._label = label;
this._epoch = epoch;
}
// An element with a declared namespace different than the namespace
// of the enclosing type.
[XmlElement(Namespace="urn:Whoohoo")]
public string Label
{
get { return this._label; }
set { this._label = value; }
}
private string _label;
// An element whose tag will be the same name as the property name.
// Also, this element will inherit the namespace of the enclosing type.
public int Epoch
{
get { return this._epoch; }
set { this._epoch = value; }
}
private int _epoch;
// Per Microsoft's documentation, you can add some public member that
// returns a XmlSerializerNamespaces object. They use a public field,
// but that's sloppy. So I'll use a private backed-field with a public
// getter property. Also, per the documentation, for this to work with
// the XmlSerializer, decorate it with the XmlNamespaceDeclarations
// attribute.
[XmlNamespaceDeclarations]
public XmlSerializerNamespaces Namespaces
{
get { return this._namespaces; }
}
private XmlSerializerNamespaces _namespaces;
}
That's all to this class. Now, some objected to having an XmlSerializerNamespaces
object somewhere within their classes; but as you can see, I neatly tucked it away in the default constructor and exposed a public property to return the namespaces.
Now, when it comes time to serialize the class, you would use the following code:
MyTypeWithNamespaces myType = new MyTypeWithNamespaces("myLabel", 42);
/******
OK, I just figured I could do this to make the code shorter, so I commented out the
below and replaced it with what follows:
// You have to use this constructor in order for the root element to have the right namespaces.
// If you need to do custom serialization of inner objects, you can use a shortened constructor.
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces), new XmlAttributeOverrides(),
new Type[]{}, new XmlRootAttribute("MyTypeWithNamespaces"), "urn:Abracadabra");
******/
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces),
new XmlRootAttribute("MyTypeWithNamespaces") { Namespace="urn:Abracadabra" });
// I'll use a MemoryStream as my backing store.
MemoryStream ms = new MemoryStream();
// This is extra! If you want to change the settings for the XmlSerializer, you have to create
// a separate XmlWriterSettings object and use the XmlTextWriter.Create(...) factory method.
// So, in this case, I want to omit the XML declaration.
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.Encoding = Encoding.UTF8; // This is probably the default
// You could use the XmlWriterSetting to set indenting and new line options, but the
// XmlTextWriter class has a much easier method to accomplish that.
// The factory method returns a XmlWriter, not a XmlTextWriter, so cast it.
XmlTextWriter xtw = (XmlTextWriter)XmlTextWriter.Create(ms, xws);
// Then we can set our indenting options (this is, of course, optional).
xtw.Formatting = Formatting.Indented;
// Now serialize our object.
xs.Serialize(xtw, myType, myType.Namespaces);
Once you have done this, you should get the following output:
<MyTypeWithNamespaces>
<Label xmlns="urn:Whoohoo">myLabel</Label>
<Epoch>42</Epoch>
</MyTypeWithNamespaces>
I have successfully used this method in a recent project with a deep hierachy of classes that are serialized to XML for web service calls. Microsoft's documentation is not very clear about what to do with the publicly accesible XmlSerializerNamespaces
member once you've created it, and so many think it's useless. But by following their documentation and using it in the manner shown above, you can customize how the XmlSerializer generates XML for your classes without resorting to unsupported behavior or "rolling your own" serialization by implementing IXmlSerializable
.
It is my hope that this answer will put to rest, once and for all, how to get rid of the standard xsi
and xsd
namespaces generated by the XmlSerializer
.
UPDATE: I just want to make sure I answered the OP's question about removing all namespaces. My code above will work for this; let me show you how. Now, in the example above, you really can't get rid of all namespaces (because there are two namespaces in use). Somewhere in your XML document, you're going to need to have something like xmlns="urn:Abracadabra" xmlns:w="urn:Whoohoo
. If the class in the example is part of a larger document, then somewhere above a namespace must be declared for either one of (or both) Abracadbra
and Whoohoo
. If not, then the element in one or both of the namespaces must be decorated with a prefix of some sort (you can't have two default namespaces, right?). So, for this example, Abracadabra
is the default namespace. I could inside my MyTypeWithNamespaces
class add a namespace prefix for the Whoohoo
namespace like so:
public MyTypeWithNamespaces
{
this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
new XmlQualifiedName(string.Empty, "urn:Abracadabra"), // Default Namespace
new XmlQualifiedName("w", "urn:Whoohoo")
});
}
Now, in my class definition, I indicated that the <Label/>
element is in the namespace "urn:Whoohoo"
, so I don't need to do anything further. When I now serialize the class using my above serialization code unchanged, this is the output:
<MyTypeWithNamespaces xmlns:w="urn:Whoohoo">
<w:Label>myLabel</w:Label>
<Epoch>42</Epoch>
</MyTypeWithNamespaces>
Because <Label>
is in a different namespace from the rest of the document, it must, in someway, be "decorated" with a namespace. Notice that there are still no xsi
and xsd
namespaces.
This ends my answer to the other question. But I wanted to make sure I answered the OP's question about using no namespaces, as I feel I didn't really address it yet. Assume that <Label>
is part of the same namespace as the rest of the document, in this case urn:Abracadabra
:
<MyTypeWithNamespaces>
<Label>myLabel<Label>
<Epoch>42</Epoch>
</MyTypeWithNamespaces>
Your constructor would look as it would in my very first code example, along with the public property to retrieve the default namespace:
// As noted below, per Microsoft's documentation, if the class exposes a public
// member of type XmlSerializerNamespaces decorated with the
// XmlNamespacesDeclarationAttribute, then the XmlSerializer will utilize those
// namespaces during serialization.
public MyTypeWithNamespaces( )
{
this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
new XmlQualifiedName(string.Empty, "urn:Abracadabra") // Default Namespace
});
}
[XmlNamespaceDeclarations]
public XmlSerializerNamespaces Namespaces
{
get { return this._namespaces; }
}
private XmlSerializerNamespaces _namespaces;
Then, later, in your code that uses the MyTypeWithNamespaces
object to serialize it, you would call it as I did above:
MyTypeWithNamespaces myType = new MyTypeWithNamespaces("myLabel", 42);
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces),
new XmlRootAttribute("MyTypeWithNamespaces") { Namespace="urn:Abracadabra" });
...
// Above, you'd setup your XmlTextWriter.
// Now serialize our object.
xs.Serialize(xtw, myType, myType.Namespaces);
And the XmlSerializer
would spit back out the same XML as shown immediately above with no additional namespaces in the output:
<MyTypeWithNamespaces>
<Label>myLabel<Label>
<Epoch>42</Epoch>
</MyTypeWithNamespaces>