I tried all above solution and fail, it just added a null file to the DB.
However, I was able to get it done by moving the image(fileName.jpg
) file first in to below folder(in my case) C:\ProgramData\MySQL\MySQL Server 5.7\Uploads
and then I executed below command and it works for me,
INSERT INTO xx_BLOB(ID,IMAGE) VALUES(1,LOAD_FILE('C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/fileName.jpg'));
Hope this helps.
All: Evidently this is working as designed. Please see new ref man dated 2019-7-23, Section 6.1.6, Security Issues with LOAD DATA LOCAL.
For those who have the following error:
Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement
You can simply run this command to see which folder can load files from:
SHOW VARIABLES LIKE "secure_file_priv";
After that, you have to copy the files in that folder and run the query with LOAD DATA LOCAL INFILE
instead of LOAD DATA INFILE
.
First you should use print_r($_FILES)
to debug, and see what it contains. :
your uploads.php
would look like:
//This is the directory where images will be saved
$target = "pics/";
$target = $target . basename( $_FILES['Filename']['name']);
//This gets all the other information from the form
$Filename=basename( $_FILES['Filename']['name']);
$Description=$_POST['Description'];
//Writes the Filename to the server
if(move_uploaded_file($_FILES['Filename']['tmp_name'], $target)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['Filename']['name']). " has been uploaded, and your information has been added to the directory";
// Connects to your Database
mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("altabotanikk") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO picture (Filename,Description)
VALUES ('$Filename', '$Description')") ;
} else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
EDIT: Since this is old post, currently it is strongly recommended to use either mysqli or pdo instead mysql_ functions in php
If you are running LOAD DATA LOCAL INFILE
from the windows shell, and you need to use OPTIONALLY ENCLOSED BY '"'
, you will have to do something like this in order to escape characters properly:
"C:\Program Files\MySQL\MySQL Server 5.6\bin\mysql" -u root --password=%password% -e "LOAD DATA LOCAL INFILE '!file!' INTO TABLE !table! FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"^""' LINES TERMINATED BY '\n' IGNORE 1 LINES" --verbose --show-warnings > mysql_!fname!.out
Since ID is auto increment, you can also specify ID=NULL as,
LOAD XML LOCAL INFILE '/pathtofile/file.xml' INTO TABLE my_tablename SET ID=NULL;
Just want to summarize the answers and comments. There are a number of ways doing a pagination.
Prior to oracle 12c there were no OFFSET/FETCH functionality, so take a look at whitepaper as the @jasonk suggested. It's the most complete article I found about different methods with detailed explanation of advantages and disadvantages. It would take a significant amount of time to copy-paste them here, so I won't do it.
There is also a good article from jooq creators explaining some common caveats with oracle and other databases pagination. jooq's blogpost
Good news, since oracle 12c we have a new OFFSET/FETCH functionality. OracleMagazine 12c new features. Please refer to "Top-N Queries and Pagination"
You may check your oracle version by issuing the following statement
SELECT * FROM V$VERSION
Swift 3 version
import UIKit
protocol PhoneCalling {
func call(phoneNumber: String)
}
extension PhoneCalling {
func call(phoneNumber: String) {
let cleanNumber = phoneNumber.replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "-", with: "")
guard let number = URL(string: "telprompt://" + cleanNumber) else { return }
UIApplication.shared.open(number, options: [:], completionHandler: nil)
}
}
You may have to replace getActivity() with MainActivity.this for those that are having issues with this.
The first option is simply to hide an error with disabling it by configuring errorOnUnhandledRejections
in $qProvider configuration as suggested Cengkuru Michael
BUT this will only switch off logging. The error itself will remain
The better solution in this case will be - handling a rejection with .catch(fn)
method:
resource.get().$promise
.then(function (response) {})
.catch(function (err) {});
LINKS:
Put this code in your viewDidLoad()
:
textField.delegate = self
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: self.textField.frame.height))
textField.leftView = paddingView
textField.leftViewMode = UITextFieldViewMode.always
It works for me :)
If you want to use AngularJs Directive with dynamic template, you can use those answers,But here is more professional and legal syntax of it.You can use templateUrl not only with single value.You can use it as a function,which returns a value as url.That function has some arguments,which you can use.
There is another method for calculate age is
See below table
FirstName LastName DOB
sai krishnan 1991-11-04
Harish S A 1998-10-11
For finding age,you can calculate through month
Select datediff(MONTH,DOB,getdate())/12 as dates from [Organization].[Employee]
Result will be
firstname dates
sai 27
Harish 20
This is better to remove NodeJS and its modules manually because installation leaves a lot of files, links and modules behind and later it create problems while we reconfigure another version of NodeJS and its modules. Run the following commands.
sudo rm -rf /usr/local/bin/npm /usr/local/share/man/man1/node* /usr/local/lib/dtrace/node.d ~/.npm ~/.node-gyp /opt/local/bin/node opt/local/include/node /opt/local/lib/node_modules
sudo rm -rf /usr/local/lib/node*
sudo rm -rf /usr/local/include/node*
sudo rm -rf /usr/local/bin/node*
and this done.
A step by step guide with commands is at http://amcositsupport.blogspot.in/2016/07/to-completely-uninstall-node-js-from.html
This helped me resolve my problem.
If the string is empty, comboBox.getSelectedItem().toString()
will give a NullPointerException
. So better to typecast by (String)
.
The Address property of a cell can get this for you:
MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)
returns A1
.
The other way around can be done with the Row
and Column
property of Range
:
MsgBox Range("A1").Row & ", " & Range("A1").Column
returns 1,1
.
Original definitive documentation
0
, 1
and 2
only track how many of the necessary methods to make a request you've called so far.
3
tells you that the server's response has started to come in. But when you're using the XMLHttpRequest
object from a web page there's almost nothing(*) you can do with that information, since you don't have access to the extended properties that allow you to read the partial data.
readyState 4
is the only one that holds any meaning.
(*: about the only conceivable use I can think of for checking for readyState 3
is that it signals some form of life at the server end, so you could possibly increase the amount of time you wait for a full response when you receive it.)
Below code runs correctly.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double num1 = 3.12345678;
cout << fixed << showpoint;
cout << setprecision(2);
cout << num1 << endl;
}
There is another way of doing "random" ordered numbers with LFSR, take a look at:
http://en.wikipedia.org/wiki/Linear_feedback_shift_register
with this technique you can achieve the ordered random number by index and making sure the values are not duplicated.
But these are not TRUE random numbers because the random generation is deterministic.
But depending your case you can use this technique reducing the amount of processing on random number generation when using shuffling.
Here a LFSR algorithm in java, (I took it somewhere I don't remeber):
public final class LFSR {
private static final int M = 15;
// hard-coded for 15-bits
private static final int[] TAPS = {14, 15};
private final boolean[] bits = new boolean[M + 1];
public LFSR() {
this((int)System.currentTimeMillis());
}
public LFSR(int seed) {
for(int i = 0; i < M; i++) {
bits[i] = (((1 << i) & seed) >>> i) == 1;
}
}
/* generate a random int uniformly on the interval [-2^31 + 1, 2^31 - 1] */
public short nextShort() {
//printBits();
// calculate the integer value from the registers
short next = 0;
for(int i = 0; i < M; i++) {
next |= (bits[i] ? 1 : 0) << i;
}
// allow for zero without allowing for -2^31
if (next < 0) next++;
// calculate the last register from all the preceding
bits[M] = false;
for(int i = 0; i < TAPS.length; i++) {
bits[M] ^= bits[M - TAPS[i]];
}
// shift all the registers
for(int i = 0; i < M; i++) {
bits[i] = bits[i + 1];
}
return next;
}
/** returns random double uniformly over [0, 1) */
public double nextDouble() {
return ((nextShort() / (Integer.MAX_VALUE + 1.0)) + 1.0) / 2.0;
}
/** returns random boolean */
public boolean nextBoolean() {
return nextShort() >= 0;
}
public void printBits() {
System.out.print(bits[M] ? 1 : 0);
System.out.print(" -> ");
for(int i = M - 1; i >= 0; i--) {
System.out.print(bits[i] ? 1 : 0);
}
System.out.println();
}
public static void main(String[] args) {
LFSR rng = new LFSR();
Vector<Short> vec = new Vector<Short>();
for(int i = 0; i <= 32766; i++) {
short next = rng.nextShort();
// just testing/asserting to make
// sure the number doesn't repeat on a given list
if (vec.contains(next))
throw new RuntimeException("Index repeat: " + i);
vec.add(next);
System.out.println(next);
}
}
}
go to gradle and then to app.buildgradle then set compileSDKVersion to 21 and then if necessary the android studio will download some files
You can also get it with PInvoke on Kernel32.dll
The following code is coming more or less from SystemInfo.cs
from System.Web source located here:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct SYSTEM_INFO
{
public ushort wProcessorArchitecture;
public ushort wReserved;
public uint dwPageSize;
public IntPtr lpMinimumApplicationAddress;
public IntPtr lpMaximumApplicationAddress;
public IntPtr dwActiveProcessorMask;
public uint dwNumberOfProcessors;
public uint dwProcessorType;
public uint dwAllocationGranularity;
public ushort wProcessorLevel;
public ushort wProcessorRevision;
}
internal static class SystemInfo
{
static int _trueNumberOfProcessors;
internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal static extern void GetSystemInfo(out SYSTEM_INFO si);
[DllImport("kernel32.dll")]
internal static extern int GetProcessAffinityMask(IntPtr handle, out IntPtr processAffinityMask, out IntPtr systemAffinityMask);
internal static int GetNumProcessCPUs()
{
if (SystemInfo._trueNumberOfProcessors == 0)
{
SYSTEM_INFO si;
GetSystemInfo(out si);
if ((int) si.dwNumberOfProcessors == 1)
{
SystemInfo._trueNumberOfProcessors = 1;
}
else
{
IntPtr processAffinityMask;
IntPtr systemAffinityMask;
if (GetProcessAffinityMask(INVALID_HANDLE_VALUE, out processAffinityMask, out systemAffinityMask) == 0)
{
SystemInfo._trueNumberOfProcessors = 1;
}
else
{
int num1 = 0;
if (IntPtr.Size == 4)
{
uint num2 = (uint) (int) processAffinityMask;
while ((int) num2 != 0)
{
if (((int) num2 & 1) == 1)
++num1;
num2 >>= 1;
}
}
else
{
ulong num2 = (ulong) (long) processAffinityMask;
while ((long) num2 != 0L)
{
if (((long) num2 & 1L) == 1L)
++num1;
num2 >>= 1;
}
}
SystemInfo._trueNumberOfProcessors = num1;
}
}
}
return SystemInfo._trueNumberOfProcessors;
}
}
Make sure that both projects have same target framework version here: right click on project -> properties -> application (tab) -> target framework
Also, make sure that the project "logger" (which you want to include in the main project) has the output type "Class Library" in: right click on project -> properties -> application (tab) -> output type
Finally, Rebuild the solution.
My issue was resolved by updating the metadata part of the connection string. Apparently it was pointing at the wrong .csdl / .ssdl / .msl reference.
You can skip the ORM, builders, etc. and simplify your DB/SQL management using sqler
and sqler-mdb
.
-- create this file at: db/mdb/read.table.rows.sql
SELECT TST.ID AS "id", TST.NAME AS "name", NULL AS "report",
TST.CREATED_AT AS "created", TST.UPDATED_AT AS "updated"
FROM TEST TST
WHERE UPPER(TST.NAME) LIKE CONCAT(CONCAT('%', UPPER(:name)), '%')
const conf = {
"univ": {
"db": {
"mdb": {
"host": "localhost",
"username":"admin",
"password": "mysqlpassword"
}
}
},
"db": {
"dialects": {
"mdb": "sqler-mdb"
},
"connections": [
{
"id": "mdb",
"name": "mdb",
"dir": "db/mdb",
"service": "MySQL",
"dialect": "mdb",
"pool": {},
"driverOptions": {
"connection": {
"multipleStatements": true
}
}
}
]
}
};
// create/initialize manager
const manager = new Manager(conf);
await manager.init();
// .sql file path is path to db function
const result = await manager.db.mdb.read.table.rows({
binds: {
name: 'Some Name'
}
});
console.log('Result:', result);
// after we're done using the manager we should close it
process.on('SIGINT', async function sigintDB() {
await manager.close();
console.log('Manager has been closed');
});
For multibranch pipeline projects, do this in the script console:
def project = Jenkins.instance.getItemByFullName("YourMultibranchPipelineProjectName")
project.getAllJobs().each{ item ->
if(item.name == 'jobName'){ // master, develop, feature/......
item.updateNextBuildNumber(#Number);
item.saveNextBuildNumber();
println('new build: ' + item.getNextBuildNumber())
}
}
You can get the second method to achieve the same effect by:
var mySecondDiv = $('<div></div>');
$(mySecondDiv).find('div').attr('id', 'mySecondDiv');
$('#myDiv').append(mySecondDiv);
Luca mentioned that html()
just inserts hte HTML which results in faster performance.
In some occassions though, you would opt for the second option, consider:
// Clumsy string concat, error prone
$('#myDiv').html("<div style='width:'" + myWidth + "'px'>Lorem ipsum</div>");
// Isn't this a lot cleaner? (though longer)
var newDiv = $('<div></div>');
$(newDiv).find('div').css('width', myWidth);
$('#myDiv').append(newDiv);
The package hash is now available: https://cran.r-project.org/web/packages/hash/hash.pdf
Examples
h <- hash( keys=letters, values=1:26 )
h <- hash( letters, 1:26 )
h$a
# [1] 1
h$foo <- "bar"
h[ "foo" ]
# <hash> containing 1 key-value pair(s).
# foo : bar
h[[ "foo" ]]
# [1] "bar"
There are two steps to fix this.
First edit phpMyAdmin/libraries/DatabaseInterface.class.php
Change:
if (PMA_MYSQL_INT_VERSION > 50503) {
$default_charset = 'utf8mb4';
$default_collation = 'utf8mb4_general_ci';
} else {
$default_charset = 'utf8';
$default_collation = 'utf8_general_ci';
}
To:
//if (PMA_MYSQL_INT_VERSION > 50503) {
// $default_charset = 'utf8mb4';
// $default_collation = 'utf8mb4_general_ci';
//} else {
$default_charset = 'utf8';
$default_collation = 'utf8_general_ci';
//}
Then delete this cookie from your browser "pma_collation_connection".
Or delete all Cookies.
Then restart your phpMyAdmin.
(It would be nice if phpMyAdmin allowed you to set the charset and collation per server in the config.inc.php)
do like this-paste your html code inside your separate html file using GET method.
$mail->IsHTML(true);
$mail->WordWrap = 70;
$mail->addAttachment= $_GET['addattachment']; $mail->AltBody
=$_GET['AltBody']; $mail->Subject = $_GET['subject']; $mail->Body = $_GET['body'];
another way to get exactly the output mentioned in the question:
envtext= "printenv".execute().text
envtext.split('\n').each
{ envvar=it.split("=")
println envvar[0]+" is "+envvar[1]
}
This can easily be extended to build a map with a subset of env vars matching a criteria:
envdict=[:]
envtext= "printenv".execute().text
envtext.split('\n').each
{ envvar=it.split("=")
if (envvar[0].startsWith("GERRIT_"))
envdict.put(envvar[0],envvar[1])
}
envdict.each{println it.key+" is "+it.value}
Found this on github...
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import pandas
Dispatching a block to the main queue is usually done from a background queue to signal that some background processing has finished e.g.
- (void)doCalculation
{
//you can use any string instead "com.mycompany.myqueue"
dispatch_queue_t backgroundQueue = dispatch_queue_create("com.mycompany.myqueue", 0);
dispatch_async(backgroundQueue, ^{
int result = <some really long calculation that takes seconds to complete>;
dispatch_async(dispatch_get_main_queue(), ^{
[self updateMyUIWithResult:result];
});
});
}
In this case, we are doing a lengthy calculation on a background queue and need to update our UI when the calculation is complete. Updating UI normally has to be done from the main queue so we 'signal' back to the main queue using a second nested dispatch_async.
There are probably other examples where you might want to dispatch back to the main queue but it is generally done in this way i.e. nested from within a block dispatched to a background queue.
As to why you might want to dispatch to the main queue from the main queue... Well, you generally wouldn't although conceivably you might do it to schedule some work to do the next time around the run loop.
Be wary, too, of inheriting workspace settings in your projects for Java Compiler/Compliance settings. I had a project that was imported into Eclipse. Eclipse generated the project with a J2SE 1.4 JRE, compiler, and compliance settings.
When I went in and manually updated these settings and un-checked the "Enable project specific settings" box, I was still receiving build errors relating to 1.5 level compliance (even though the workspace settings were clearly 1.6). It wasn't until I re-checked the "Enable project specific settings" box and manually set the compiler/compliance levels to 1.6 did the errors go away.
My solution using File Provider
private void viewGallery(File file) {
Uri mImageCaptureUri = FileProvider.getUriForFile(
mContext,
mContext.getApplicationContext()
.getPackageName() + ".provider", file);
Intent view = new Intent();
view.setAction(Intent.ACTION_VIEW);
view.setData(mImageCaptureUri);
List < ResolveInfo > resInfoList =
mContext.getPackageManager()
.queryIntentActivities(view, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo: resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
mContext.grantUriPermission(packageName, mImageCaptureUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
view.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(mImageCaptureUri, "image/*");
mContext.startActivity(intent);
}
I couldn't get Microsoft's logic behind this ugly implementation, but you have to have two functions:
void setEnableLoginButton()
{
if (InvokeRequired)
{
// btn_login can be any conroller, (label, button textbox ..etc.)
btn_login.Invoke(new MethodInvoker(setEnable));
// OR
//Invoke(new MethodInvoker(setEnable));
}
else {
setEnable();
}
}
void setEnable()
{
btn_login.Enabled = isLoginBtnEnabled;
}
These snippets work for me, so I can do something on another thread, and then I update the GUI:
Task.Factory.StartNew(()=>
{
// THIS IS NOT GUI
Thread.Sleep(5000);
// HERE IS INVOKING GUI
btn_login.Invoke(new Action(() => DoSomethingOnGUI()));
});
private void DoSomethingOnGUI()
{
// GUI
MessageBox.Show("message", "title", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
Even simpler:
btn_login.Invoke(new Action(()=>{ /* HERE YOU ARE ON GUI */ }));
ALTER DATABASE name OWNER TO new_owner;
See the Postgresql manual's entry on this for more details.
I found the existing answers confusing, and took a long time to work out where the problem is. Here's a compilation of everything I found.
When I run my app, I get an error Failed to execute script foo
(if foo.py
is the main file). To troubleshoot this, don't run PyInstaller with --noconsole
(or edit main.spec
to change console=False
=> console=True
). With this, run the executable from a command-line, and you'll see the failure.
The first thing to check is that it's packaging up your extra files correctly. You should add tuples like ('x', 'x')
if you want the folder x
to be included.
After it crashes, don't click OK. If you're on Windows, you can use Search Everything. Look for one of your files (eg. sword.png
). You should find the temporary path where it unpacked the files (eg. C:\Users\ashes999\AppData\Local\Temp\_MEI157682\images\sword.png
). You can browse this directory and make sure it included everything. If you can't find it this way, look for something like main.exe.manifest
(Windows) or python35.dll
(if you're using Python 3.5).
If the installer includes everything, the next likely problem is file I/O: your Python code is looking in the executable's directory, instead of the temp directory, for files.
To fix that, any of the answers on this question work. Personally, I found a mixture of them all to work: change directory conditionally first thing in your main entry-point file, and everything else works as-is:
if hasattr(sys, '_MEIPASS'):
os.chdir(sys._MEIPASS)
No offence, but none of the other answers (so far) has it quite right.
break
is used to immediately terminate a for
loop, a while
loop or a switch
statement. You can not break
from an if
block.
return
is used the terminate a method (and possibly return a value).
A return
within any loop or block will of course also immediately terminate that loop/block.
Following Steps are much enough to back button:
Step 1: This code should be in Manifest.xml
<activity android:name=".activity.ChildActivity"
android:parentActivityName=".activity.ParentActivity"
android:screenOrientation="portrait">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".activity.ParentActivity" /></activity>
Step 2: You won't give
finish();
in your Parent Activity while starting Child Activity.
Step 3: If you need to come back to Parent Activity from Child Activity, Then you just give this code for Child Activity.
startActivity(new Intent(ParentActivity.this, ChildActivity.class));
You should not use your domain models
in your views. ViewModels
are the correct way to do it.
You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.
If you never heard of viewmodels, take a look at this.
You have a few options, all varying in "correctness" and ease of use. As always, the right design depends on your needs.
You could simply create two columns in Ticket, OwnedByUserId and OwnedByGroupId, and have nullable Foreign Keys to each table.
You could create M:M reference tables enabling both ticket:user and ticket:group relationships. Perhaps in future you will want to allow a single ticket to be owned by multiple users or groups? This design does not enforce that a ticket must be owned by a single entity only.
You could create a default group for every user and have tickets simply owned by either a true Group or a User's default Group.
Or (my choice) model an entity that acts as a base for both Users and Groups, and have tickets owned by that entity.
Heres a rough example using your posted schema:
create table dbo.PartyType
(
PartyTypeId tinyint primary key,
PartyTypeName varchar(10)
)
insert into dbo.PartyType
values(1, 'User'), (2, 'Group');
create table dbo.Party
(
PartyId int identity(1,1) primary key,
PartyTypeId tinyint references dbo.PartyType(PartyTypeId),
unique (PartyId, PartyTypeId)
)
CREATE TABLE dbo.[Group]
(
ID int primary key,
Name varchar(50) NOT NULL,
PartyTypeId as cast(2 as tinyint) persisted,
foreign key (ID, PartyTypeId) references Party(PartyId, PartyTypeID)
)
CREATE TABLE dbo.[User]
(
ID int primary key,
Name varchar(50) NOT NULL,
PartyTypeId as cast(1 as tinyint) persisted,
foreign key (ID, PartyTypeId) references Party(PartyID, PartyTypeID)
)
CREATE TABLE dbo.Ticket
(
ID int primary key,
[Owner] int NOT NULL references dbo.Party(PartyId),
[Subject] varchar(50) NULL
)
All the answers above assume the user has access to a privileged/root account to install the required libraries. To install it locally you will need to do the following steps. Only showed the overview since the steps can get a little involved depending on the dependencies that you might be missing
1.Download and Compile libxml2-2.9.1 & libxslt-1.1.28(versions might change)
2.Configure each install path for both libxml and libxslt to be some local directory using configure. Ex. ./configure --prefix=/home_dir/dependencies/libxslt_path
3.Run make
then make install
4.Download and compile lxml from source
its really simple just
var total = (1 * yourFirstVariablehere) + (1 * yourSecondVariablehere)
this forces javascript to multiply because there is no confusion for * sign in javascript.
Open Task Manager (press Ctrl+Alt+Del Select the 'Processes Tab' Search for 'Node.js: Server-side JavaScript' Select it and click on 'End task' button
Here is how you can add an icon while creating an exe file from a Python file
open command prompt at the place where Python file exist
type:
pyinstaller --onefile -i"path of icon" path of python file
Example-
pyinstaller --onefile -i"C:\icon\Robot.ico" C:\Users\Jarvis.py
This is the easiest way to add an icon.
You can also use the var_export PHP function.
The above answers are fine but I would add to be sure the div is defined in the designer.cs file. This doesn't always happen when adding a div to the .aspx file. Not sure why but there are threads concerning this issue in this forum. Eg:
protected global::System.Web.UI.HtmlControls.HtmlGenericControl theDiv;
You can use setdefault
:
d = dict()
a = ['1', '2']
for i in a:
for j in range(int(i), int(i) + 2):
d.setdefault(j, []).append(i)
print d # prints {1: ['1'], 2: ['1', '2'], 3: ['2']}
The rather oddly-named setdefault
function says "Get the value with this key, or if that key isn't there, add this value and then return it."
As others have rightly pointed out, defaultdict
is a better and more modern choice. setdefault
is still useful in older versions of Python (prior to 2.5).
I recently ran into this issue and none of the solutions proposed fixed it. The issue turned out to be an excessive use of datasets stored in the session. There was a flaw in the code that results in the session size to increase 10x.
There is an article on the msdn blog that also talks about this. http://blogs.msdn.com/b/johan/archive/2006/11/20/sessionstate-performance.aspx
I used a function to write custom trace messages to measure the size of the session data on the live site.
Use Java 8's removeIf(),
To remove safely,
letters.removeIf(x -> !x.equals("A"));
Make resource controller with Model.
php artisan make:controller PostController --model=Post
8 years later, for a one-liner
const search = Object.fromEntries(new URLSearchParams(location.search));
Down-side, it does NOT work with IE11
To explain
// For https://caniuse.com/?search=fromEntries
> Object.fromEntries(new URLSearchParams(location.search))
> {search: "fromEntries"}
The break
keyword does exactly that. Here is a contrived example:
public static void main(String[] args) {
int i = 0;
while (i++ < 10) {
if (i == 5) break;
}
System.out.println(i); //prints 5
}
If you were actually using nested loops, you would be able to use labels.
function removeParam(parameter)
{
var url=document.location.href;
var urlparts= url.split('?');
if (urlparts.length>=2)
{
var urlBase=urlparts.shift();
var queryString=urlparts.join("?");
var prefix = encodeURIComponent(parameter)+'=';
var pars = queryString.split(/[&;]/g);
for (var i= pars.length; i-->0;)
if (pars[i].lastIndexOf(prefix, 0)!==-1)
pars.splice(i, 1);
url = urlBase+'?'+pars.join('&');
window.history.pushState('',document.title,url); // added this line to push the new url directly to url bar .
}
return url;
}
This will resolve your problem
http://robert.ocallahan.org/2011/11/latency-of-html5-sounds.html
http://people.mozilla.org/~roc/audio-latency-repeating.html
Works OK in Firefox and Chrome for me.
To stop a sound that you started, do var sound = document.getElementById("shot").cloneNode(true); sound.play(); and later sound.pause();
str
is text representation in bytes, unicode
is text representation in characters.
You decode text from bytes to unicode and encode a unicode into bytes with some encoding.
That is:
>>> 'abc'.decode('utf-8') # str to unicode
u'abc'
>>> u'abc'.encode('utf-8') # unicode to str
'abc'
UPD Sep 2020: The answer was written when Python 2 was mostly used. In Python 3, str
was renamed to bytes
, and unicode
was renamed to str
.
>>> b'abc'.decode('utf-8') # bytes to str
'abc'
>>> 'abc'.encode('utf-8'). # str to bytes
b'abc'
Forwarding the example by @ritiek, I'm a beginner in ML too, maybe this kind of formatting will help see the name instead of just class number.
images = np.vstack([x, y])
prediction = model.predict(images)
print(prediction)
i = 1
for things in prediction:
if(things == 0):
print('%d.It is cancer'%(i))
else:
print('%d.Not cancer'%(i))
i = i + 1
The ON UPDATE
and ON DELETE
specify which action will execute when a row in the parent table is updated and deleted. The following are permitted actions : NO ACTION
, CASCADE
, SET NULL
, and SET DEFAULT
.
If you delete one or more rows in the parent table, you can set one of the following actions:
ON DELETE NO ACTION
: SQL Server raises an error and rolls back the delete action on the row in the parent table.ON DELETE CASCADE
: SQL Server deletes the rows in the child table that is corresponding to the row deleted from the parent table.ON DELETE SET NULL
: SQL Server sets the rows in the child table to NULL if the corresponding rows in the parent table are deleted. To execute this action, the foreign key columns must be nullable.ON DELETE SET DEFAULT
: SQL Server sets the rows in the child table to their default values if the corresponding rows in the parent table are deleted. To execute this action, the foreign key columns must have default definitions. Note that a nullable column has a default value of NULL if no default value specified.
By default, SQL Server appliesON DELETE NO ACTION if you don’t explicitly specify any action.If you update one or more rows in the parent table, you can set one of the following actions:
ON UPDATE NO ACTION
: SQL Server raises an error and rolls back the update action on the row in the parent table.ON UPDATE CASCADE
: SQL Server updates the corresponding rows in the child table when the rows in the parent table are updated.ON UPDATE SET NULL
: SQL Server sets the rows in the child table to NULL when the corresponding row in the parent table is updated. Note that the foreign key columns must be nullable for this action to execute.ON UPDATE SET DEFAULT
: SQL Server sets the default values for the rows in the child table that have the corresponding rows in the parent table updated.FOREIGN KEY (foreign_key_columns)
REFERENCES parent_table(parent_key_columns)
ON UPDATE <action>
ON DELETE <action>;
If this batch file is something you want to run as scheduled or always; you can use windows schedule tool and it doesn't opens up in a window when it starts the batch file.
To open Task Scheduler
:
'cmd'
taskschd.msc
-> enterFrom the right side, click Create Basic Task
and follow the menus.
Hope this helps.
What the browser does when you've got
<a onclick="alert('Hi');" ... >
is to set the actual value of "onclick" to something effectively like:
new Function("event", "alert('Hi');");
That is, it creates a function that expects an "event" parameter. (Well, IE doesn't; it's more like a plain simple anonymous function.)
String source = "24/10/17";
String[] sourceSplit= source.split("/");
int anno= Integer.parseInt(sourceSplit[2]);
int mese= Integer.parseInt(sourceSplit[1]);
int giorno= Integer.parseInt(sourceSplit[0]);
GregorianCalendar calendar = new GregorianCalendar();
calendar.set(anno,mese-1,giorno);
Date data1= calendar.getTime();
SimpleDateFormat myFormat = new SimpleDateFormat("20yy-MM-dd");
String dayFormatted= myFormat.format(data1);
System.out.println("data formattata,-->"+dayFormatted);
Take a look to this link that shows how works the mapping of EF 6 with Stored Procedures to make an Insert, Update and Delete: http://msdn.microsoft.com/en-us/data/dn468673
Addition
Here is a great example to call a stored procedure from Code First:
Lets say you have to execute an Stored Procedure with a single parameter, and that Stored Procedure returns a set of data that match with the Entity States, so we will have this:
var countryIso = "AR"; //Argentina
var statesFromArgentina = context.Countries.SqlQuery(
"dbo.GetStatesFromCountry @p0", countryIso
);
Now lets say that we whant to execute another stored procedure with two parameters:
var countryIso = "AR"; //Argentina
var stateIso = "RN"; //Río Negro
var citiesFromRioNegro = context.States.SqlQuery(
"dbo.GetCitiesFromState @p0, @p1", countryIso, stateIso
);
Notice that we are using index-based naming for parameters. This is because Entity Framework will wrap these parameters up as DbParameter objects fro you to avoid any SQL injection issues.
Hope this example helps!
try this in eclipse: Window - Preferences - Android
- SDK Location and setup SDK path
It is possible to reference an intellij 'Path Variable' in an intellij 'Run Configuration'.
In 'Path Variables' create a variable for example ANALYTICS_VERSION
.
In a 'Run Configuration' under 'Environment Variables' add for example the following:
ANALYTICS_LOAD_LOCATION=$MAVEN_REPOSITORY$\com\my\company\analytics\$ANALYTICS_VERSION$\bin
To answer the original question you would need to add an APP_HOME
environment variable to your run configuration which references the path variable:
APP_HOME=$APP_HOME$
Check that Apache has execute rights for /root
, /root/site
and /root/site/about
.
Run:
chmod o+x /root /root/site /root/site/about
Here is an example to create a new object with renamed keys.
let x = { id: "checkout", name: "git checkout", description: "checkout repository" };
let renamed = Object.entries(x).reduce((u, [n, v]) => {
u[`__${n}`] = v;
return u;
}, {});
In your invoke web request just use the parameter -UseBasicParsing
e.g. in your script (line 2) you should use:
$rss = Invoke-WebRequest -Uri $url -UseBasicParsing
According to the documentation, this parameter is necessary on systems where IE isn't installed or configured:
Uses the response object for HTML content without Document Object Model (DOM) parsing. This parameter is required when Internet Explorer is not installed on the computers, such as on a Server Core installation of a Windows Server operating system.
return 42 ;
statement. This is for me extreme inlining. It happens rarely in real life, it makes compilation time longer, will not bloat your code, and will make your code faster. But like the grail, don't try to apply it everywhere because most processing cannot be resolved this way... Still, this is cool anyway...It is strange how much beauty varies for different people. I find the list comprehension much clearer than filter
+lambda
, but use whichever you find easier.
There are two things that may slow down your use of filter
.
The first is the function call overhead: as soon as you use a Python function (whether created by def
or lambda
) it is likely that filter will be slower than the list comprehension. It almost certainly is not enough to matter, and you shouldn't think much about performance until you've timed your code and found it to be a bottleneck, but the difference will be there.
The other overhead that might apply is that the lambda is being forced to access a scoped variable (value
). That is slower than accessing a local variable and in Python 2.x the list comprehension only accesses local variables. If you are using Python 3.x the list comprehension runs in a separate function so it will also be accessing value
through a closure and this difference won't apply.
The other option to consider is to use a generator instead of a list comprehension:
def filterbyvalue(seq, value):
for el in seq:
if el.attribute==value: yield el
Then in your main code (which is where readability really matters) you've replaced both list comprehension and filter with a hopefully meaningful function name.
Use the wait
built-in:
process1 &
process2 &
process3 &
process4 &
wait
process5 &
process6 &
process7 &
process8 &
wait
For the above example, 4 processes process1
... process4
would be started in the background, and the shell would wait until those are completed before starting the next set.
From the GNU manual:
wait [jobspec or pid ...]
Wait until the child process specified by each process ID pid or job specification jobspec exits and return the exit status of the last command waited for. If a job spec is given, all processes in the job are waited for. If no arguments are given, all currently active child processes are waited for, and the return status is zero. If neither jobspec nor pid specifies an active child process of the shell, the return status is 127.
In maven the dependencies got included for me when I removed the dependencyManagement xml section and just had dependencies directly under project section
UPDATE: Using Java 8 Syntax
List<DataPoint> myList = new ArrayList<>();
//Fill up myList with your Data Points
List<DataPoint> dataPointsCalledJohn =
myList
.stream()
.filter(p-> p.getName().equals(("john")))
.collect(Collectors.toList());
If you don't mind using an external libaray - you can use Predicates from the Google Guava library as follows:
class DataPoint {
String name;
String getName() { return name; }
}
Predicate<DataPoint> nameEqualsTo(final String name) {
return new Predicate<DataPoint>() {
public boolean apply(DataPoint dataPoint) {
return dataPoint.getName().equals(name);
}
};
}
public void main(String[] args) throws Exception {
List<DataPoint> myList = new ArrayList<DataPoint>();
//Fill up myList with your Data Points
Collection<DataPoint> dataPointsCalledJohn =
Collections2.filter(myList, nameEqualsTo("john"));
}
If you are targeting ASP.NET Core that does not support RijndaelManaged
yet, you can use IDataProtectionProvider
.
First, configure your application to use data protection:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddDataProtection();
}
// ...
}
Then you'll be able to inject IDataProtectionProvider
instance and use it to encrypt/decrypt data:
public class MyService : IService
{
private const string Purpose = "my protection purpose";
private readonly IDataProtectionProvider _provider;
public MyService(IDataProtectionProvider provider)
{
_provider = provider;
}
public string Encrypt(string plainText)
{
var protector = _provider.CreateProtector(Purpose);
return protector.Protect(plainText);
}
public string Decrypt(string cipherText)
{
var protector = _provider.CreateProtector(Purpose);
return protector.Unprotect(cipherText);
}
}
See this article for more details.
Take a look at the line-height
property. Trying to style the <br>
tag is not the answer.
Example:
<p id="single-spaced">
This<br>
text<br>
is<br>
single-spaced.
</p>
<p id="double-spaced" style="line-height: 200%;">
This<br>
text<br>
is<br>
double-spaced.
</p>
Bind a handler to the FormClosing
event, then set e.Cancel = true
, and set the form this.WindowState = FormWindowState.Minimized
.
If you want to ever actually close the form, make a class-wide boolean _close
and, in your handler, set e.Cancel
to !_close
, so that whenever the user clicks the X
on the window, it doesn't close, but you can still close it (without just killing it) with close = true; this.Close();
(And just to make my answer complete) set MaximizeBox
and MinimizeBox
form properties to False
.
Another Java 8 Stream solution to delete all the content of a folder, sub directories included, but not the folder itself.
Usage:
Path folder = Paths.get("/tmp/folder");
CleanFolder.clean(folder);
and the code:
public interface CleanFolder {
static void clean(Path folder) throws IOException {
Function<Path, Stream<Path>> walk = p -> {
try { return Files.walk(p);
} catch (IOException e) {
return Stream.empty();
}};
Consumer<Path> delete = p -> {
try {
Files.delete(p);
} catch (IOException e) {
}
};
Files.list(folder)
.flatMap(walk)
.sorted(Comparator.reverseOrder())
.forEach(delete);
}
}
The problem with every stream solution involving Files.walk or Files.delete is that these methods throws IOException which are a pain to handle in streams.
I tried to create a solution which is more concise as possible.
Environment.getExternalStorageDirectory().getAbsolutePath()
Gives you the full path the SDCard. You can then do normal File I/O operations using standard Java.
Here's a simple example for writing a file:
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.txt";
// Not sure if the / is on the path or not
File f = new File(baseDir + File.separator + fileName);
f.write(...);
f.flush();
f.close();
Edit:
Oops - you wanted an example for reading ...
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.txt";
// Not sure if the / is on the path or not
File f = new File(baseDir + File.Separator + fileName);
FileInputStream fiStream = new FileInputStream(f);
byte[] bytes;
// You might not get the whole file, lookup File I/O examples for Java
fiStream.read(bytes);
fiStream.close();
Another feature:
instead of of server.xml, you can add "Resource" tag in
your_application/META-INF/Context.xml
(according to tomcat docs)
like this:
<Context>
<Resource name="jdbc/DatabaseName" auth="Container" type="javax.sql.DataSource"
username="dbUsername" password="dbPasswd"
url="jdbc:postgresql://localhost/dbname"
driverClassName="org.postgresql.Driver"
initialSize="5" maxWait="5000"
maxActive="120" maxIdle="5"
validationQuery="select 1"
poolPreparedStatements="true"/>
</Context>
If the column expanded only by contiguously added dates as in my case - I used just MAX function to get last date.
The final formula will be:
=DAYS360(A2; MAX(A2:A))
Strings in PHP are always BLOBs. So you can use a string to hold the value for your database BLOB. All of this stuff base-converting and so on has to do with presenting that BLOB.
If you want a nice human-readable representation of your BLOB then it makes sense to show the bytes it contains, and probably to use hex rather than decimal. Hence, the string "41 42 43" is a good way to present the byte array that in C# would be
var bytes = new byte[] { 0x41, 0x42, 0x43 };
but it is obviously not a good way to represent those bytes! The string "ABC" is an efficient representation, because it is in fact the same BLOB (only it's not so Large in this case).
In practice you will typically get your BLOBs from functions that return string - such as that hashing function, or other built-in functions like fread.
In the rare cases (but not so rare when just trying things out/prototyping) that you need to just construct a string from some hard-coded bytes I don't know of anything more efficient than converting a "hex string" to what is often called a "binary string" in PHP:
$myBytes = "414243";
$data = pack('H*', $myBytes);
If you var_dump($data);
it'll show you string(3) "ABC"
. That's because 0x41 = 65 decimal = 'A' (in basically all encodings).
Since looking at binary data by interpreting it as a string is not exactly intuitive, you may want to make a basic wrapper to make debugging easier. One possible such wrapper is
class blob
{
function __construct($hexStr = '')
{
$this->appendHex($hexStr);
}
public $value;
public function appendHex($hexStr)
{
$this->value .= pack('H*', $hexStr);
}
public function getByte($index)
{
return unpack('C', $this->value{$index})[1];
}
public function setByte($index, $value)
{
$this->value{$index} = pack('C', $value);
}
public function toArray()
{
return unpack('C*', $this->value);
}
}
This is something I cooked up on the fly, and probably just a starting point for your own wrapper. But the idea is to use a string for storage since this is the most efficient structure available in PHP, while providing methods like toArray() for use in debugger watches/evaluations when you want to examine the contents.
Of course you may use a perfectly straightforward PHP array instead and pack it to a string when interfacing with something that uses strings for binary data. Depending on the degree to which you are actually going to modify the blob this may prove easier, and although it isn't space efficient I think you'd get acceptable performance for many tasks.
An example to illustrate the functionality:
// Construct a blob with 3 bytes: 0x41 0x42 0x43.
$b = new blob("414243");
// Append 3 more bytes: 0x44 0x45 0x46.
$b->appendHex("444546");
// Change the second byte to 0x41 (so we now have 0x41 0x41 0x43 0x44 0x45 0x46).
$b->setByte(1, 0x41); // or, equivalently, setByte(1, 65)
// Dump the first byte.
var_dump($b->getByte(0));
// Verify the result. The string "AACDEF", because it's only ASCII characters, will have the same binary representation in basically any encoding.
$ok = $b->value == "AACDEF";
This issue can occur if the Azure Active Directory Module for Windows PowerShell isn't loaded correctly.
To resolve this issue, follow these steps.
1.Install the Azure Active Directory Module for Windows PowerShell on the computer (if it isn't already installed). To install the Azure Active Directory Module for Windows PowerShell, go to the following Microsoft website:
Manage Azure AD using Windows PowerShell
2.If the MSOnline module isn't present, use Windows PowerShell to import the MSOnline module.
Import-Module MSOnline
After it complete, we can use this command to check it.
PS C:\Users> Get-Module -ListAvailable -Name MSOnline*
Directory: C:\windows\system32\WindowsPowerShell\v1.0\Modules
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Manifest 1.1.166.0 MSOnline {Get-MsolDevice, Remove-MsolDevice, Enable-MsolDevice, Disable-MsolDevice...}
Manifest 1.1.166.0 MSOnlineExtended {Get-MsolDevice, Remove-MsolDevice, Enable-MsolDevice, Disable-MsolDevice...}
More information about this issue, please refer to it.
Update:
We should import azure AD powershell to VS 2015, we can add tool and select Azure AD powershell.
IF "%1"=="" will fail, all versions of this will fail under certain poison character conditions. Only IF DEFINED or IF NOT DEFINED are safe
The simple and best solution is to use tables for layouts. You're doing it right. There are a number of reasons tables are better.
This will return a given string with ellipsis based on WORD count instead of characters:
<?php
/**
* Return an elipsis given a string and a number of words
*/
function elipsis ($text, $words = 30) {
// Check if string has more than X words
if (str_word_count($text) > $words) {
// Extract first X words from string
preg_match("/(?:[^\s,\.;\?\!]+(?:[\s,\.;\?\!]+|$)){0,$words}/", $text, $matches);
$text = trim($matches[0]);
// Let's check if it ends in a comma or a dot.
if (substr($text, -1) == ',') {
// If it's a comma, let's remove it and add a ellipsis
$text = rtrim($text, ',');
$text .= '...';
} else if (substr($text, -1) == '.') {
// If it's a dot, let's remove it and add a ellipsis (optional)
$text = rtrim($text, '.');
$text .= '...';
} else {
// Doesn't end in dot or comma, just adding ellipsis here
$text .= '...';
}
}
// Returns "ellipsed" text, or just the string, if it's less than X words wide.
return $text;
}
$description = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quibusdam ut placeat consequuntur pariatur iure eum ducimus quasi perferendis, laborum obcaecati iusto ullam expedita excepturi debitis nisi deserunt fugiat velit assumenda. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt, blanditiis nostrum. Nostrum cumque non rerum ducimus voluptas officia tempore modi, nulla nisi illum, voluptates dolor sapiente ut iusto earum. Esse? Lorem ipsum dolor sit amet, consectetur adipisicing elit. A eligendi perspiciatis natus autem. Necessitatibus eligendi doloribus corporis quia, quas laboriosam. Beatae repellat dolor alias. Perferendis, distinctio, laudantium? Dolorum, veniam, amet!';
echo elipsis($description, 30);
?>
To expand on @Grgur's answer, if you look in your inspector, you'll find that using Link
components gives them the preset color value color: -webkit-link
. You'll need to override this along with the textDecoration
if you don't want it to look like a default hyperlink.
You can make a cookie never end by setting it to whatever date plus one more than the current year like this :
var d = new Date();
document.cookie = "username=John Doe; expires=Thu, 18 Dec " + (d.getFullYear() + 1) + " 12:00:00 UTC";
Your tuples are basically key-value pairs--a python dict
--so:
l = [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]
val = dict(l)[53]
Edit -- aha, you say you want the index value of (53, "xuxa"). If this is really what you want, you'll have to iterate through the original list, or perhaps make a more complicated dictionary:
d = dict((n,i) for (i,n) in enumerate(e[0] for e in l))
idx = d[53]
As Adrian said, the plugins are going to work the same way. There are three basic parts you're going to need:
1: Event handler for 'contextmenu'
event:
$(document).bind("contextmenu", function(event) {
event.preventDefault();
$("<div class='custom-menu'>Custom menu</div>")
.appendTo("body")
.css({top: event.pageY + "px", left: event.pageX + "px"});
});
Here, you could bind the event handler to any selector that you want to show a menu for. I've chosen the entire document.
2: Event handler for 'click'
event (to close the custom menu):
$(document).bind("click", function(event) {
$("div.custom-menu").hide();
});
3: CSS to control the position of the menu:
.custom-menu {
z-index:1000;
position: absolute;
background-color:#C0C0C0;
border: 1px solid black;
padding: 2px;
}
The important thing with the CSS is to include the z-index
and position: absolute
It wouldn't be too tough to wrap all of this in a slick jQuery plugin.
You can see a simple demo here: http://jsfiddle.net/andrewwhitaker/fELma/
Number((6.688689).toFixed(1)); // 6.7
var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;
Use toFixed()
function.
(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"
If you don't want it to add it to a link, you can just enclose it within a span and that would work.
<span id='clickableAwesomeFont'><i class="fa fa-behance-square fa-4x"></span>
in your css, then you can:
#clickableAwesomeFont {
cursor: pointer
}
Then in java script, you can just add a click handler.
In cases where it's actually not a link, I think this is much cleaner and using a link would be changing its semantics and abusing its meaning.
I think I got there in the end.
The task is like this:
- name: Populate genders
set_fact:
genders: "{{ genders|default({}) | combine( {item.item.name: item.stdout} ) }}"
with_items: "{{ people.results }}"
It loops through each of the dicts (item
) in the people.results
array, each time creating a new dict like {Bob: "male"}
, and combine()
s that new dict in the genders
array, which ends up like:
{
"Bob": "male",
"Thelma": "female"
}
It assumes the keys (the name
in this case) will be unique.
I then realised I actually wanted a list of dictionaries, as it seems much easier to loop through using with_items
:
- name: Populate genders
set_fact:
genders: "{{ genders|default([]) + [ {'name': item.item.name, 'gender': item.stdout} ] }}"
with_items: "{{ people.results }}"
This keeps combining the existing list with a list containing a single dict. We end up with a genders
array like this:
[
{'name': 'Bob', 'gender': 'male'},
{'name': 'Thelma', 'gender': 'female'}
]
Here is my recursive approach:
function visit(object) {
if (isIterable(object)) {
forEachIn(object, function (accessor, child) {
visit(child);
});
}
else {
var value = object;
console.log(value);
}
}
function forEachIn(iterable, functionRef) {
for (var accessor in iterable) {
functionRef(accessor, iterable[accessor]);
}
}
function isIterable(element) {
return isArray(element) || isObject(element);
}
function isArray(element) {
return element.constructor == Array;
}
function isObject(element) {
return element.constructor == Object;
}
The error indicates that the DLL is either not a COM DLL or it's corrupt. If it's not a COM DLL and not being used as a COM DLL by an application then there is no need to register it.
From what you say in your question (the service is not registered)
it seems that we are talking about a service not correctly installed. I will try to reinstall the application.
A var
cannot be set to null
since it needs to be statically typed.
var foo = null;
// compiler goes: "Huh, what's that type of foo?"
However, you can use this construct to work around the issue:
var foo = (string)null;
// compiler goes: "Ah, it's a string. Nice."
I don't know for sure, but from what I heard you can also use dynamic
instead of var
. This does not require static typing.
dynamic foo = null;
foo = "hi";
Also, since it was not clear to me from the question if you meant the var
keyword or variables in general: Only references (to classes) and nullable types can be set to null. For instance, you can do this:
string s = null; // reference
SomeClass c = null; // reference
int? i = null; // nullable
But you cannot do this:
int i = null; // integers cannot contain null
I have a slightly different way of doing this than the accepted answer. This way you can avoid using GROUP_CONCAT which has a limit of 1024 characters and will not work if you have a lot of fields.
SET @sql = '';
SELECT
@sql := CONCAT(@sql,if(@sql='','',', '),temp.output)
FROM
(
SELECT
DISTINCT
CONCAT(
'MAX(IF(pa.fieldname = ''',
fieldname,
''', pa.fieldvalue, NULL)) AS ',
fieldname
) as output
FROM
product_additional
) as temp;
SET @sql = CONCAT('SELECT p.id
, p.name
, p.description, ', @sql, '
FROM product p
LEFT JOIN product_additional AS pa
ON p.id = pa.id
GROUP BY p.id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
The default collation for stored procedure parameters is utf8_general_ci
and you can't mix collations, so you have four options:
Option 1: add COLLATE
to your input variable:
SET @rUsername = ‘aname’ COLLATE utf8_unicode_ci; -- COLLATE added
CALL updateProductUsers(@rUsername, @rProductID, @rPerm);
Option 2: add COLLATE
to the WHERE
clause:
CREATE PROCEDURE updateProductUsers(
IN rUsername VARCHAR(24),
IN rProductID INT UNSIGNED,
IN rPerm VARCHAR(16))
BEGIN
UPDATE productUsers
INNER JOIN users
ON productUsers.userID = users.userID
SET productUsers.permission = rPerm
WHERE users.username = rUsername COLLATE utf8_unicode_ci -- COLLATE added
AND productUsers.productID = rProductID;
END
Option 3: add it to the IN
parameter definition:
CREATE PROCEDURE updateProductUsers(
IN rUsername VARCHAR(24) COLLATE utf8_unicode_ci, -- COLLATE added
IN rProductID INT UNSIGNED,
IN rPerm VARCHAR(16))
BEGIN
UPDATE productUsers
INNER JOIN users
ON productUsers.userID = users.userID
SET productUsers.permission = rPerm
WHERE users.username = rUsername
AND productUsers.productID = rProductID;
END
Option 4: alter the field itself:
ALTER TABLE users CHARACTER SET utf8 COLLATE utf8_general_ci;
Unless you need to sort data in Unicode order, I would suggest altering all your tables to use utf8_general_ci
collation, as it requires no code changes, and will speed sorts up slightly.
UPDATE: utf8mb4/utf8mb4_unicode_ci is now the preferred character set/collation method. utf8_general_ci is advised against, as the performance improvement is negligible. See https://stackoverflow.com/a/766996/1432614
TLDR:First determine where in the pipeline you're getting the error from (scroll looking for screenshots of something that resembles your error), make changes to get something new, repeat.
If you are seeing the file located here...
%SystemDrive%\inetpub\custerr\\500.htm
...which generally looks like this:
...then you know you are seeing the currently configured error page in **IIS ** and you do NOT need to change the ASP.net customErrors setting, asp error detail setting, or "show friendly http errors" browser setting.
You may want to look at the above referenced path instead of trusting my screenshot just in case somebody changed it.
In this case, you are seeing the setting of <httpErrors> or in IIS Manager it's Error Pages --> Edit Feature Settings. The default for this is errorMode=DetailedLocalOnly at the server node level (as opposed to the site level) which means that while you will see this configured error page while remote, you should be able to log on locally to the server and see the full error which should look something like this:
You should have everything that you need at that point to fix the current error.
That leaves a couple of possibilities.
Change your site's httpErrors to "Detailed" so you can see it remotely. But if it doesn't work your error might already be a config error, see #3 immediately above. So you might be stuck with #4 or #5 and you're going to need somebody from your server team.
...and you expect to see something like this...
...then you need to change "Send errors to browser" to true in IIS Manager, under Site --> IIS --> ASP --> Debugging Properties
or this...
...you need to disable friendly errors in your browser or use fiddler's webview to look at the actual response vs what your browser chooses to show you.
If you see this...
...then custom errors is working but you don't have a custom error page (of course at this point were talking about .net and not classic asp). You need to change your customErrors tag in your web.config to RemoteOnly to view on the server, or Off to view remotely.
If you see something that is styled like your site, then custom errors is likely On or RemoteOnly and it's displaying the custom page (Views->Shared->Error.cshtml in MVC for example). That said, it is unlikely but possible that somebody changed the pages in IIS for httpErrors so see the first section on that.
I'd use a 'where not exists' -- exactly as you suggest in your title:
SELECT `voter`.`ID`, `voter`.`Last_Name`, `voter`.`First_Name`,
`voter`.`Middle_Name`, `voter`.`Age`, `voter`.`Sex`,
`voter`.`Party`, `voter`.`Demo`, `voter`.`PV`,
`household`.`Address`, `household`.`City`, `household`.`Zip`
FROM (`voter`)
JOIN `household` ON `voter`.`House_ID`=`household`.`id`
WHERE `CT` = '5'
AND `Precnum` = 'CTY3'
AND `Last_Name` LIKE '%Cumbee%'
AND `First_Name` LIKE '%John%'
AND NOT EXISTS (
SELECT * FROM `elimination`
WHERE `elimination`.`voter_id` = `voter`.`ID`
)
ORDER BY `Last_Name` ASC
LIMIT 30
That may be marginally faster than doing a left join (of course, depending on your indexes, cardinality of your tables, etc), and is almost certainly much faster than using IN.
Oddly it looks like the other two answers don't spell it out, and it's definitely worth saying:
i++
means 'tell me the value of i
, then increment'
++i
means 'increment i
, then tell me the value'
They are Pre-increment, post-increment operators. In both cases the variable is incremented, but if you were to take the value of both expressions in exactly the same cases, the result will differ.
For those with Spring Boot you have to add the module to your context and it will be added to your configuration like this.
@Bean
public Module jodaTimeModule() {
return new JodaModule();
}
And if you want to use the new java8 time module jsr-310.
@Bean
public Module jodaTimeModule() {
return new JavaTimeModule();
}
you can try:
shift + right click
then, click on Open command prompt here
Here is a Swift 3 adaptation of Paul Hegarty's solution from rdprado's answer, with some checking for optionals added to it (returning 0.0 if any part of the process fails):
var wageFloat:Float = 0.0
if let wageText = wage.text {
if let wageNumber = NumberFormatter().number(from: wageText) {
wageFloat = wageNumber.floatValue
}
}
By the way, I took Stanford's CS193p class using iTunes University when it was still teaching Objective-C.
I found Paul Hegarty to be a FANTASTIC instructor, and I would highly recommend the class to anyone starting out as an iOS developer in Swift!!!
I am not sure if you are trying to create a remote branch from a local branch or vice versa, so I've outlined both scenarios as well as provided information on merging the remote and local branches.
Creating a remote called "github":
git remote add github git://github.com/jdoe/coolapp.git
git fetch github
List all remote branches:
git branch -r
github/gh-pages
github/master
github/next
github/pu
Create a new local branch (test) from a github's remote branch (pu):
git branch test github/pu
git checkout test
Merge changes from github's remote branch (pu) with local branch (test):
git fetch github
git checkout test
git merge github/pu
Update github's remote branch (pu) from a local branch (test):
git push github test:pu
Creating a new branch on a remote uses the same syntax as updating a remote branch. For example, create new remote branch (beta) on github from local branch (test):
git push github test:beta
Delete remote branch (pu) from github:
git push github :pu
One option is to give the <a>
a display of inline-block
and then apply text-align: center;
on the containing block (remove the float as well):
div {
background: red;
overflow: hidden;
text-align: center;
}
span a {
background: #222;
color: #fff;
display: inline-block;
/* float:left; remove */
margin: 10px 10px 0 0;
padding: 5px 10px
}
If you need functionality that isn't there, just extend the class with whatever you want:
from collections import OrderedDict
class OrderedDictWithPrepend(OrderedDict):
def prepend(self, other):
ins = []
if hasattr(other, 'viewitems'):
other = other.viewitems()
for key, val in other:
if key in self:
self[key] = val
else:
ins.append((key, val))
if ins:
items = self.items()
self.clear()
self.update(ins)
self.update(items)
Not terribly efficient, but works:
o = OrderedDictWithPrepend()
o['a'] = 1
o['b'] = 2
print o
# OrderedDictWithPrepend([('a', 1), ('b', 2)])
o.prepend({'c': 3})
print o
# OrderedDictWithPrepend([('c', 3), ('a', 1), ('b', 2)])
o.prepend([('a',11),('d',55),('e',66)])
print o
# OrderedDictWithPrepend([('d', 55), ('e', 66), ('c', 3), ('a', 11), ('b', 2)])
10.0.2.2
to access your actual machine.As you've learned, when you use the emulator, localhost
(127.0.0.1
) refers to the device's own loopback service, not the one on your machine as you may expect.
You can use 10.0.2.2 to access your actual machine, it is an alias set up to help in development.
Add the Controller Section
ViewBag.Orders= new SelectList(db.Orders, "Id", "business", paramid);
Add the Html Section
@Html.DropDownList("Orders", null)
A simple method
After hours of searching and looking for answer, finally I made it!!!!! Code is below :))))
HTML:
<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
<label>File to stash:</label>
<input type="file" name="file" required />
</form>
<input type="button" value="Stash the file!"></input>
<div id="output"></div>
jQuery:
$(function(){
$('#uploadBTN').on('click', function(){
var fd = new FormData($("#fileinfo"));
//fd.append("CustomField", "This is some extra data");
$.ajax({
url: 'upload.php',
type: 'POST',
data: fd,
success:function(data){
$('#output').html(data);
},
cache: false,
contentType: false,
processData: false
});
});
});
In the upload.php
file you can access the data passed with $_FILES['file']
.
Thanks everyone for trying to help:)
I took the answer from here (with some changes) MDN
set android:dividerHeight="1dp"
<ListView
android:id="@+id/myphnview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@drawable/dividerheight"
android:background="#E9EAEC"
android:clickable="true"
android:divider="@color/white"
android:dividerHeight="1dp"
android:headerDividersEnabled="true" >
</ListView>
based on the some of above replies i improvised it a bit
create this method and call it by passing your resource
Reusable Method
public String getURLForResource (int resourceId) {
//use BuildConfig.APPLICATION_ID instead of R.class.getPackage().getName() if both are not same
return Uri.parse("android.resource://"+R.class.getPackage().getName()+"/" +resourceId).toString();
}
Sample call
getURLForResource(R.drawable.personIcon)
complete example of loading image
String imageUrl = getURLForResource(R.drawable.personIcon);
// Load image
Glide.with(patientProfileImageView.getContext())
.load(imageUrl)
.into(patientProfileImageView);
you can move the function getURLForResource to a Util file and make it static so it can be reused
You don't need floats. In fact, they're useless because floats are ignored in flexbox.
You also don't need CSS positioning.
There are several flex methods available. auto
margins have been mentioned in another answer.
Here are two other options:
justify-content: space-between
and the order
property.justify-content: space-between
and reverse the order of the divs..parent {_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
}_x000D_
_x000D_
.parent:first-of-type > div:last-child { order: -1; }_x000D_
_x000D_
p { background-color: #ddd;}
_x000D_
<p>Method 1: Use <code>justify-content: space-between</code> and <code>order-1</code></p>_x000D_
_x000D_
<div class="parent">_x000D_
<div class="child" style="float:right"> Ignore parent? </div>_x000D_
<div>another child </div>_x000D_
</div>_x000D_
_x000D_
<hr>_x000D_
_x000D_
<p>Method 2: Use <code>justify-content: space-between</code> and reverse the order of _x000D_
divs in the mark-up</p>_x000D_
_x000D_
<div class="parent">_x000D_
<div>another child </div>_x000D_
<div class="child" style="float:right"> Ignore parent? </div>_x000D_
</div>
_x000D_
When you use a web service you have a client and a server:
When you use a message queue like RabbitMQ, Beanstalkd, ActiveMQ, IBM MQ Series, Tuxedo you expect different and more fault tolerant results:
Message Queues has a lot more features but this is some rule of thumb to decide if you want to handle error conditions yourself or leave them to the message queue.
In my case only after I added gcm.jar
to lib folder, it started to work.
It was here: C:\adt-bundle-windows-x86_64-20131030\sdk\extras\google\gcm\gcm-client\dist
So the google-play-services.jar
didn't work...
You can also use an oracle defined collection
DECLARE
arrayvalues sys.odcivarchar2list;
BEGIN
arrayvalues := sys.odcivarchar2list('Matt','Joanne','Robert');
FOR x IN ( SELECT m.column_value m_value
FROM table(arrayvalues) m )
LOOP
dbms_output.put_line (x.m_value||' is a good pal');
END LOOP;
END;
I would use in-memory array. But with the .COUNT
improvement suggested by uziberia:
DECLARE
TYPE t_people IS TABLE OF varchar2(10) INDEX BY PLS_INTEGER;
arrayvalues t_people;
BEGIN
SELECT *
BULK COLLECT INTO arrayvalues
FROM (select 'Matt' m_value from dual union all
select 'Joanne' from dual union all
select 'Robert' from dual
)
;
--
FOR i IN 1 .. arrayvalues.COUNT
LOOP
dbms_output.put_line(arrayvalues(i)||' is my friend');
END LOOP;
END;
Another solution would be to use a Hashmap like @Jchomel did here.
NB:
With Oracle 12c you can even query arrays directly now!
I think you need str.contains
, if you need rows where values of column date
contains string 07311954
:
print df[df['date'].astype(str).str.contains('07311954')]
Or if type
of date
column is string
:
print df[df['date'].str.contains('07311954')]
If you want check last 4 digits for string
1954
in column date
:
print df[df['date'].astype(str).str[-4:].str.contains('1954')]
Sample:
print df['date']
0 8152007
1 9262007
2 7311954
3 2252011
4 2012011
5 2012011
6 2222011
7 2282011
Name: date, dtype: int64
print df['date'].astype(str).str[-4:].str.contains('1954')
0 False
1 False
2 True
3 False
4 False
5 False
6 False
7 False
Name: date, dtype: bool
print df[df['date'].astype(str).str[-4:].str.contains('1954')]
cmte_id trans_typ entity_typ state employer occupation date \
2 C00119040 24K CCM MD NaN NaN 7311954
amount fec_id cand_id
2 1000 C00140715 H2MD05155
I ended up doing something similar to what mark dibe did, but I needed to figure out the spacing for a slightly different manner.
The col-x
classes in bootstrap can be an absolute lifesaver. I ended up doing something similar to this:
<div class="row col-12">
<div class="col-3">Title</div>
</div>
<div class="row col-12">
<div class="col-3">Bootstrap Switch</div>
<div>
This allowed me to align titles and input switches in a nicely spaced manner. The same idea can be applied to the buttons and allow you to stop the buttons from touching.
(Side note: I wanted this to be a comment on the above link, but my reputation is not high enough)
The simplest way to get the visitor’s/client’s IP address is using the $_SERVER['REMOTE_ADDR']
or $_SERVER['REMOTE_HOST']
variables.
However, sometimes this does not return the correct IP address of the visitor, so we can use some other server variables to get the IP address.
The below both functions are equivalent with the difference only in how and from where the values are retrieved.
getenv() is used to get the value of an environment variable in PHP.
// Function to get the client IP address
function get_client_ip() {
$ipaddress = '';
if (getenv('HTTP_CLIENT_IP'))
$ipaddress = getenv('HTTP_CLIENT_IP');
else if(getenv('HTTP_X_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
else if(getenv('HTTP_X_FORWARDED'))
$ipaddress = getenv('HTTP_X_FORWARDED');
else if(getenv('HTTP_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_FORWARDED_FOR');
else if(getenv('HTTP_FORWARDED'))
$ipaddress = getenv('HTTP_FORWARDED');
else if(getenv('REMOTE_ADDR'))
$ipaddress = getenv('REMOTE_ADDR');
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
$_SERVER is an array that contains server variables created by the web server.
// Function to get the client IP address
function get_client_ip() {
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP']))
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']))
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
you can | for set union and & for set intersection.
for example:
set1={1,2,3}
set2={3,4,5}
print(set1&set2)
output=3
set1={1,2,3}
set2={3,4,5}
print(set1|set2)
output=1,2,3,4,5
curly braces in the answer.
The right place to download the JDK for Java 7 is Java SE Downloads.
All the other links provided above, as far as I can tell, either provide the JRE or Java 6 downloads (incidentally, if you want to run Eclipse or other IDEs, like IntelliJ IDEA, you will need the JDK, not the JRE).
Regarding IntelliJ IDEA - that will still ask you to install Java 6 as it apparently needs an older class loader or something: just follow the instructions when the dialog pop-up appears and it will install the JDK 6 in the right place.
Afterwards, you will need to do the sudo ln -snf
mentioned in the answer above:
sudo ln -nsf /Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents \
/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK
(copied here as it was mentioned that "above" may eventually not make sense as answers are re-sorted).
I also set my JAVA_HOME
to point to where jdk_1.7.0_xx.jdk
was installed:
export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents/Home"
Then add that to your PATH
:
export PATH=$JAVA_HOME/bin:$PATH
The alternative is to fuzz around with Apple's insane maze of hyperlinks, but honestly life is too short to bother.
Suppose s = "ZWzaAd"
To sort above string the simple solution will be below one.
print ''.join(sorted(s))
<%= Html.Partial("PartialName", Model) %>
The most straight forward answer to this question is: You can't.
Youtube doesn't output their video's in the right format, thus they can't be embedded in a
<video/>
element.
There are a few solutions posted using javascript, but don't trust on those, they all need a fallback, and won't work cross-browser.
Use awk(another great bash utility) instead of grep where you dont have the line buffered option! It will continuously stream your data from tail.
this is how you use grep
tail -f <file> | grep pattern
This is how you would use awk
tail -f <file> | awk '/pattern/{print $0}'
Just use this function.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let index = CategorytableView.indexPathForSelectedRow
let indexNumber = index?.row
let VC = segue.destination as! DestinationViewController
VC.value = self.data
}
An alternative to TikaEncodingDetector is to use Tika AutoDetectReader.
Charset charset = new AutoDetectReader(new FileInputStream(file)).getCharset();
Go to view all content of the site (http://yourdmain.sharepoint/sitename/_layouts/viewlsts.aspx). Select the document library "Pages" (the "Pages" library are named based on the language you created the site in. I.E. in norwegian the library is named "Sider"). Download the default.aspx to you computer and fix it (remove the web part and the <%Register tag). Save it and upload it back to the library (remember to check in the file).
EDIT:
ahh.. you are not using a publishing site template. Go to site action -> site settings. Under "site administration" select the menu "content and structure" you should now see your default.aspx page. But you cant do much with it...(delete, copy or move)
workaround: Enable publishing feature to the root web. Add the fixed default.aspx file to the Pages library and change the welcome page to this. Disable the publishing feature (this will delete all other list create from this feature but not the Pages library since one page is in use.). You will now have a new default.aspx page for the root web but the url is changed from sitename/default.aspx to sitename/Pages/default.aspx.
workaround II Use a feature to change the default.aspx file. The solution is explained here: http://wssguy.com/blogs/dan/archive/2008/10/29/how-to-change-the-default-page-of-a-sharepoint-site-using-a-feature.aspx
You need to manually delete the children. the <condition>
is the same for both queries.
DELETE FROM child
FROM cTable AS child
INNER JOIN table AS parent ON child.ParentId = parent.ParentId
WHERE <condition>;
DELETE FROM parent
FROM table AS parent
WHERE <condition>;
In your INSERT statements:
INSERT INTO employee(hans,germany) values(?,?)
You've got your values where your field names belong. Change it to be:
INSERT INTO employee(emp_name,emp_address) values(?,?)
If you were to run that statement from a SQL prompt, it would look like this:
INSERT INTO employee(emp_name,emp_address) values('hans','germany');
Note that you'd need to put single quotes around the string/varchar values.
Additionally, you are also not adding any parameters to your prepared statement. That is what's actually causing the error you're seeing. Try this:
PreparedStatement ps = con.prepareStatement(inserting);
ps.setString(1, "hans");
ps.setString(2, "germany");
ps.execute();
Also (according to Oracle), you can use "execute" for any SQL statement. Using "executeUpdate" would also be valid in this situation, which would return an integer to indicate the number of rows affected.
There is no mistake in your bash script. But you are executing it with sh which has a less extensive syntax ;)
So, run bash ./choose.sh
instead :)
Nick's answer works great. Be careful when specifying a complete() function inside the animate() call because it will get executed twice since you have two selectors declared (html and body).
$("html, body").animate(
{ scrollTop: "300px" },
{
complete : function(){
alert('this alert will popup twice');
}
}
);
Here's how you can avoid the double callback.
var completeCalled = false;
$("html, body").animate(
{ scrollTop: "300px" },
{
complete : function(){
if(!completeCalled){
completeCalled = true;
alert('this alert will popup once');
}
}
}
);
you could also do it this way, in my case i use it before and after an h1 (brute force it ehehehe)
.titleImage::before {
content: "--------";
letter-spacing: -3px;
}
.titreImage::after {
content: "--------";
letter-spacing: -3px;
}
If the letter spacing makes it so the line get in the text just use a margin to push it away!
Try this:
package main
import (
"io";
)
func main() {
contents,_ := io.ReadFile("filename");
println(string(contents));
io.WriteFile("filename", contents, 0644);
}
Very Simple Example is.
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();
Date date1 = new Date();
try {
System.out.println("Date1: "+date1);
System.out.println("date" + date);
date = simpleDateFormat.parse("01-01-2013");
date1 = simpleDateFormat.parse("06-15-2013");
System.out.println("Date1 is:"+date1);
System.out.println("date" + date);
} catch (Exception e) {
System.out.println(e.getMessage());
}
I suggest using phpjs.org 's number_format()
function number_format(number, decimals, dec_point, thousands_sep) {
// http://kevin.vanzonneveld.net
// + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfix by: Michael White (http://getsprink.com)
// + bugfix by: Benjamin Lupton
// + bugfix by: Allan Jensen (http://www.winternet.no)
// + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// + bugfix by: Howard Yeend
// + revised by: Luke Smith (http://lucassmith.name)
// + bugfix by: Diogo Resende
// + bugfix by: Rival
// + input by: Kheang Hok Chin (http://www.distantia.ca/)
// + improved by: davook
// + improved by: Brett Zamir (http://brett-zamir.me)
// + input by: Jay Klehr
// + improved by: Brett Zamir (http://brett-zamir.me)
// + input by: Amir Habibi (http://www.residence-mixte.com/)
// + bugfix by: Brett Zamir (http://brett-zamir.me)
// + improved by: Theriault
// + improved by: Drew Noakes
// * example 1: number_format(1234.56);
// * returns 1: '1,235'
// * example 2: number_format(1234.56, 2, ',', ' ');
// * returns 2: '1 234,56'
// * example 3: number_format(1234.5678, 2, '.', '');
// * returns 3: '1234.57'
// * example 4: number_format(67, 2, ',', '.');
// * returns 4: '67,00'
// * example 5: number_format(1000);
// * returns 5: '1,000'
// * example 6: number_format(67.311, 2);
// * returns 6: '67.31'
// * example 7: number_format(1000.55, 1);
// * returns 7: '1,000.6'
// * example 8: number_format(67000, 5, ',', '.');
// * returns 8: '67.000,00000'
// * example 9: number_format(0.9, 0);
// * returns 9: '1'
// * example 10: number_format('1.20', 2);
// * returns 10: '1.20'
// * example 11: number_format('1.20', 4);
// * returns 11: '1.2000'
// * example 12: number_format('1.2000', 3);
// * returns 12: '1.200'
var n = !isFinite(+number) ? 0 : +number,
prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
toFixedFix = function (n, prec) {
// Fix for IE parseFloat(0.55).toFixed(0) = 0;
var k = Math.pow(10, prec);
return Math.round(n * k) / k;
},
s = (prec ? toFixedFix(n, prec) : Math.round(n)).toString().split('.');
if (s[0].length > 3) {
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
}
if ((s[1] || '').length < prec) {
s[1] = s[1] || '';
s[1] += new Array(prec - s[1].length + 1).join('0');
}
return s.join(dec);
}
UPDATE 02/13/14
People have been reporting this doesn't work as expected, so I did a JS Fiddle that includes automated tests.
Update 26/11/2017
Here's that fiddle as a Stack Snippet with slightly modified output:
function number_format(number, decimals, dec_point, thousands_sep) {_x000D_
// http://kevin.vanzonneveld.net_x000D_
// + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)_x000D_
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)_x000D_
// + bugfix by: Michael White (http://getsprink.com)_x000D_
// + bugfix by: Benjamin Lupton_x000D_
// + bugfix by: Allan Jensen (http://www.winternet.no)_x000D_
// + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)_x000D_
// + bugfix by: Howard Yeend_x000D_
// + revised by: Luke Smith (http://lucassmith.name)_x000D_
// + bugfix by: Diogo Resende_x000D_
// + bugfix by: Rival_x000D_
// + input by: Kheang Hok Chin (http://www.distantia.ca/)_x000D_
// + improved by: davook_x000D_
// + improved by: Brett Zamir (http://brett-zamir.me)_x000D_
// + input by: Jay Klehr_x000D_
// + improved by: Brett Zamir (http://brett-zamir.me)_x000D_
// + input by: Amir Habibi (http://www.residence-mixte.com/)_x000D_
// + bugfix by: Brett Zamir (http://brett-zamir.me)_x000D_
// + improved by: Theriault_x000D_
// + improved by: Drew Noakes_x000D_
// * example 1: number_format(1234.56);_x000D_
// * returns 1: '1,235'_x000D_
// * example 2: number_format(1234.56, 2, ',', ' ');_x000D_
// * returns 2: '1 234,56'_x000D_
// * example 3: number_format(1234.5678, 2, '.', '');_x000D_
// * returns 3: '1234.57'_x000D_
// * example 4: number_format(67, 2, ',', '.');_x000D_
// * returns 4: '67,00'_x000D_
// * example 5: number_format(1000);_x000D_
// * returns 5: '1,000'_x000D_
// * example 6: number_format(67.311, 2);_x000D_
// * returns 6: '67.31'_x000D_
// * example 7: number_format(1000.55, 1);_x000D_
// * returns 7: '1,000.6'_x000D_
// * example 8: number_format(67000, 5, ',', '.');_x000D_
// * returns 8: '67.000,00000'_x000D_
// * example 9: number_format(0.9, 0);_x000D_
// * returns 9: '1'_x000D_
// * example 10: number_format('1.20', 2);_x000D_
// * returns 10: '1.20'_x000D_
// * example 11: number_format('1.20', 4);_x000D_
// * returns 11: '1.2000'_x000D_
// * example 12: number_format('1.2000', 3);_x000D_
// * returns 12: '1.200'_x000D_
var n = !isFinite(+number) ? 0 : +number, _x000D_
prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),_x000D_
sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,_x000D_
dec = (typeof dec_point === 'undefined') ? '.' : dec_point,_x000D_
toFixedFix = function (n, prec) {_x000D_
// Fix for IE parseFloat(0.55).toFixed(0) = 0;_x000D_
var k = Math.pow(10, prec);_x000D_
return Math.round(n * k) / k;_x000D_
},_x000D_
s = (prec ? toFixedFix(n, prec) : Math.round(n)).toString().split('.');_x000D_
if (s[0].length > 3) {_x000D_
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);_x000D_
}_x000D_
if ((s[1] || '').length < prec) {_x000D_
s[1] = s[1] || '';_x000D_
s[1] += new Array(prec - s[1].length + 1).join('0');_x000D_
}_x000D_
return s.join(dec);_x000D_
}_x000D_
_x000D_
var exampleNumber = 1;_x000D_
function test(expected, number, decimals, dec_point, thousands_sep)_x000D_
{_x000D_
var actual = number_format(number, decimals, dec_point, thousands_sep);_x000D_
console.log(_x000D_
'Test case ' + exampleNumber + ': ' +_x000D_
'(decimals: ' + (typeof decimals === 'undefined' ? '(default)' : decimals) +_x000D_
', dec_point: "' + (typeof dec_point === 'undefined' ? '(default)' : dec_point) + '"' +_x000D_
', thousands_sep: "' + (typeof thousands_sep === 'undefined' ? '(default)' : thousands_sep) + '")'_x000D_
);_x000D_
console.log(' => ' + (actual === expected ? 'Passed' : 'FAILED') + ', got "' + actual + '", expected "' + expected + '".');_x000D_
exampleNumber++;_x000D_
}_x000D_
_x000D_
test('1,235', 1234.56);_x000D_
test('1 234,56', 1234.56, 2, ',', ' ');_x000D_
test('1234.57', 1234.5678, 2, '.', '');_x000D_
test('67,00', 67, 2, ',', '.');_x000D_
test('1,000', 1000);_x000D_
test('67.31', 67.311, 2);_x000D_
test('1,000.6', 1000.55, 1);_x000D_
test('67.000,00000', 67000, 5, ',', '.');_x000D_
test('1', 0.9, 0);_x000D_
test('1.20', '1.20', 2);_x000D_
test('1.2000', '1.20', 4);_x000D_
test('1.200', '1.2000', 3);
_x000D_
.as-console-wrapper {_x000D_
max-height: 100% !important;_x000D_
}
_x000D_
Just becuase your class object has no variables does not mean that it is nothing. Declaring and object and creating an object are two different things. Look and see if you are setting/creating the object.
Take for instance the dictionary object - just because it contains no variables does not mean it has not been created.
Sub test()
Dim dict As Object
Set dict = CreateObject("scripting.dictionary")
If Not dict Is Nothing Then
MsgBox "Dict is something!" '<--- This shows
Else
MsgBox "Dict is nothing!"
End If
End Sub
However if you declare an object but never create it, it's nothing.
Sub test()
Dim temp As Object
If Not temp Is Nothing Then
MsgBox "Temp is something!"
Else
MsgBox "Temp is nothing!" '<---- This shows
End If
End Sub
There are a lot of answers here suggesting something like [value=""]
but I don't think that actually works . . . or at least, the usage is not consistent. I'm trying to do something similar, selecting all inputs with ids beginning with a certain string that also have no entered value. I tried this:
$("input[id^='something'][value='']")
but it doesn't work. Nor does reversing them. See this fiddle. The only ways I found to correctly select all inputs with ids beginning with a string and without an entered value were
$("input[id^='something']").not("[value!='']")
and
$("input[id^='something']:not([value!=''])")
but obviously, the double negatives make that really confusing. Probably, Russ Cam's first answer (with a filtering function) is the most clear method.
Or do a non-recursive checkout of /trunk, then just do a manual update on the 3 directories you need.
Snapshot simply means depending on your configuration Maven will check latest changes on a special dependency. Snapshot is unstable because it is under development but if on a special project needs to has a latest changes you must configure your dependency version to snapshot version. This scenario occurs in big organizations with multiple products that these products related to each other very closely.
Clément's answer is by far the best. Here's a somewhat improved answer, showing different possible alignments, including left-center-right aligned buttons:
label_x000D_
{ padding-right:8px;_x000D_
}_x000D_
_x000D_
.FAligned,.FAlignIn_x000D_
{ display:table;_x000D_
}_x000D_
_x000D_
.FAlignIn_x000D_
{ width:100%;_x000D_
}_x000D_
_x000D_
.FRLeft,.FRRight,.FRCenter_x000D_
{ display:table-row;_x000D_
white-space:nowrap;_x000D_
}_x000D_
_x000D_
.FCLeft,.FCRight,.FCCenter_x000D_
{ display:table-cell;_x000D_
}_x000D_
_x000D_
.FRLeft,.FCLeft,.FILeft_x000D_
{ text-align:left;_x000D_
}_x000D_
_x000D_
.FRRight,.FCRight,.FIRight_x000D_
{ text-align:right;_x000D_
}_x000D_
_x000D_
.FRCenter,.FCCenter,.FICenter_x000D_
{ text-align:center;_x000D_
}
_x000D_
<form class="FAligned">_x000D_
<div class="FRLeft">_x000D_
<p class="FRLeft">_x000D_
<label for="Input0" class="FCLeft">Left:</label>_x000D_
<input id="Input0" type="text" size="30" placeholder="Left Left Left" class="FILeft"/>_x000D_
</p>_x000D_
<p class="FRLeft">_x000D_
<label for="Input1" class="FCRight">Left Right Left:</label>_x000D_
<input id="Input1" type="text" size="30" placeholder="Left Right Left" class="FILeft"/>_x000D_
</p>_x000D_
<p class="FRRight">_x000D_
<label for="Input2" class="FCLeft">Right Left Left:</label>_x000D_
<input id="Input2" type="text" size="30" placeholder="Right Left Left" class="FILeft"/>_x000D_
</p>_x000D_
<p class="FRRight">_x000D_
<label for="Input3" class="FCRight">Right Right Left:</label>_x000D_
<input id="Input3" type="text" size="30" placeholder="Right Right Left" class="FILeft"/>_x000D_
</p>_x000D_
<p class="FRLeft">_x000D_
<label for="Input4" class="FCLeft">Left Left Right:</label>_x000D_
<input id="Input4" type="text" size="30" placeholder="Left Left Right" class="FIRight"/>_x000D_
</p>_x000D_
<p class="FRLeft">_x000D_
<label for="Input5" class="FCRight">Left Right Right:</label>_x000D_
<input id="Input5" type="text" size="30" placeholder="Left Right Right" class="FIRight"/>_x000D_
</p>_x000D_
<p class="FRRight">_x000D_
<label for="Input6" class="FCLeft">Right Left Right:</label>_x000D_
<input id="Input6" type="text" size="30" placeholder="Right Left Right" class="FIRight"/>_x000D_
</p>_x000D_
<p class="FRRight">_x000D_
<label for="Input7" class="FCRight">Right:</label>_x000D_
<input id="Input7" type="text" size="30" placeholder="Right Right Right" class="FIRight"/>_x000D_
</p>_x000D_
<p class="FRCenter">_x000D_
<label for="Input8" class="FCCenter">And centralised is also possible:</label>_x000D_
<input id="Input8" type="text" size="60" placeholder="Center in the centre" class="FICenter"/>_x000D_
</p>_x000D_
</div>_x000D_
<div class="FAlignIn">_x000D_
<div class="FRCenter">_x000D_
<div class="FCLeft"><button type="button">Button on the Left</button></div>_x000D_
<div class="FCCenter"><button type="button">Button on the Centre</button></div>_x000D_
<div class="FCRight"><button type="button">Button on the Right</button></div>_x000D_
</div>_x000D_
</div>_x000D_
</form>
_x000D_
I added some padding on the right of all labels (padding-right:8px
) just to make the example slight less horrible looking, but that should be done more carefully in a real project (adding padding to all other elements would also be a good idea).
A lightweight solution with Check constraint:
CREATE TABLE example (
discriminator INTEGER DEFAULT 0 NOT NULL CHECK (discriminator = 0)
);
OpenJPA allows you to specify non-standard annotation to define index on property.
Details are here.
this should work also with different predicate
myFunction(strings.find( _ == mystring ).isDefined)
The first answer is too complex, historic, and uninformative for my tastes.
It's actually rather simple. Docker provides for a functionality called multi-stage builds the basic idea here is to,
Let's start with the first. Very often with something like Debian you'll see.
RUN apt-get update \
&& apt-get dist-upgrade \
&& apt-get install <whatever> \
&& apt-get clean
We can explain all of this in terms of the above. The above command is chained together so it represents a single change with no intermediate Images required. If it was written like this,
RUN apt-get update ;
RUN apt-get dist-upgrade;
RUN apt-get install <whatever>;
RUN apt-get clean;
It would result in 3 more temporary intermediate Images. Having it reduced to one image, there is one remaining problem: apt-get clean
doesn't clean up artifacts used in the install. If a Debian maintainer includes in his install a script that modifies the system that modification will also be present in the final solution (see something like pepperflashplugin-nonfree
for an example of that).
By using a multi-stage build you get all the benefits of a single changed action, but it will require you to manually whitelist and copy over files that were introduced in the temporary image using the COPY --from
syntax documented here. Moreover, it's a great solution where there is no alternative (like an apt-get clean
), and you would otherwise have lots of un-needed files in your final image.
See also
Simply put, Git is a version control system that lets you manage and keep track of your source code history. GitHub is a cloud-based hosting service that lets you manage Git repositories. If you have open-source projects that use Git, then GitHub is designed to help you better manage them.
As many other pointed out, arguments
contains all the arguments passed to a function.
If you want to call another function with the same args, use apply
Example:
var is_debug = true;
var debug = function() {
if (is_debug) {
console.log.apply(console, arguments);
}
}
debug("message", "another argument")
Lookups in lists are O(n), lookups in dictionaries are amortized O(1), with regard to the number of items in the data structure. If you don't need to associate values, use sets.
Both dictionaries and sets use hashing and they use much more memory than only for object storage. According to A.M. Kuchling in Beautiful Code, the implementation tries to keep the hash 2/3 full, so you might waste quite some memory.
If you do not add new entries on the fly (which you do, based on your updated question), it might be worthwhile to sort the list and use binary search. This is O(log n), and is likely to be slower for strings, impossible for objects which do not have a natural ordering.
Depending on which browsers you aim to support, you could use the :checked
pseudo-class selector in addition to hiding the radio buttons.
Using this HTML:
<input type="radio" id="toggle-on" name="toggle" checked
><label for="toggle-on">On</label
><input type="radio" id="toggle-off" name="toggle"
><label for="toggle-off">Off</label>
You could use something like the following CSS:
input[type="radio"].toggle {
display: none;
}
input[type="radio"].toggle:checked + label {
/* Do something special with the selected state */
}
For instance, (to keep the custom CSS brief) if you were using Bootstrap, you might add class="btn"
to your <label>
elements and style them appropriately to create a toggle that looks like:
...which just requires the following additional CSS:
input[type="radio"].toggle:checked + label {
background-image: linear-gradient(to top,#969696,#727272);
box-shadow: inset 0 1px 6px rgba(41, 41, 41, 0.2),
0 1px 2px rgba(0, 0, 0, 0.05);
cursor: default;
color: #E6E6E6;
border-color: transparent;
text-shadow: 0 1px 1px rgba(40, 40, 40, 0.75);
}
input[type="radio"].toggle + label {
width: 3em;
}
input[type="radio"].toggle:checked + label.btn:hover {
background-color: inherit;
background-position: 0 0;
transition: none;
}
input[type="radio"].toggle-left + label {
border-right: 0;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
input[type="radio"].toggle-right + label {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
I've included this as well as the extra fallback styles in a radio button toggle jsFiddle demo. Note that :checked
is only supported in IE 9, so this approach is limited to newer browsers.
However, if you need to support IE 8 and are willing to fall back on JavaScript*, you can hack in pseudo-support for :checked
without too much difficulty (although you can just as easily set classes directly on the label at that point).
Using some quick and dirty jQuery code as an example of the workaround:
$('.no-checkedselector').on('change', 'input[type="radio"].toggle', function () {
if (this.checked) {
$('input[name="' + this.name + '"].checked').removeClass('checked');
$(this).addClass('checked');
// Force IE 8 to update the sibling selector immediately by
// toggling a class on a parent element
$('.toggle-container').addClass('xyz').removeClass('xyz');
}
});
$('.no-checkedselector input[type="radio"].toggle:checked').addClass('checked');
You can then make a few changes to the CSS to complete things:
input[type="radio"].toggle {
/* IE 8 doesn't seem to like to update radio buttons that are display:none */
position: absolute;
left: -99em;
}
input[type="radio"].toggle:checked + label,
input[type="radio"].toggle.checked + label {
/* Do something special with the selected state */
}
*If you're using Modernizr, you can use the :selector
test to help determine if you need the fallback. I called my test "checkedselector" in the example code, and the jQuery event handler is subsequently only set up when the test fails.
The simplest way of installing SBT on ubuntu is the deb
package provided by Typesafe.
Run the following shell commands:
wget http://apt.typesafe.com/repo-deb-build-0002.deb
sudo dpkg -i repo-deb-build-0002.deb
sudo apt-get update
sudo apt-get install sbt
And you're done !
I know this question is well answered, but just wanted to list the steps I take to create a new branch "myNewBranch" and push to remote ("origin" in my case) and set up tracking. Consider this the "TL;DR" version :)
# create new branch and checkout that branch
git checkout -b myNewBranch
# now push branch to remote
git push origin myNewBranch
# set up the new branch to track remote branch from origin
git branch --set-upstream-to=origin/myNewBranch myNewBranch
Assuming you have access to them (the properties you've declared are protected
), you use them like this:
Person tom = new Person();
tom.Title = "A title";
string hisTitle = tom.Title;
These are properties. They're basically pairs of getter/setter methods (although you can have just a getter, or just a setter) with appropriate metadata. The example you've given is of automatically implemented properties where the compiler is adding a backing field. You can write the code yourself though. For example, the Title
property you've declared is like this:
private string title; // Backing field
protected string Title
{
get { return title; } // Getter
set { title = value; } // Setter
}
... except that the backing field is given an "unspeakable name" - one you can't refer to in your C# code. You're forced to go through the property itself.
You can make one part of a property more restricted than another. For example, this is quite common:
private string foo;
public string Foo
{
get { return foo; }
private set { foo = value; }
}
or as an automatically implemented property:
public string Foo { get; private set; }
Here the "getter" is public but the "setter" is private.
git checkout Last_Stable_commit_Number -- fileName
2.Git revert file to a specific branch
git checkout branchName_Which_Has_stable_Commit fileName
First add the font in .odt format to your resources, in this case we will use DINEngschriftStd.otf, then use this code to assign the font to the label
[theUILabel setFont:[UIFont fontWithName:@"DINEngschriftStd" size:21]];
To make sure your font is loaded on the project just call
NSLog(@"Available Font Families: %@", [UIFont familyNames]);
On the .plist you must declare the font. Just add a 'Fonts provided by application' record and add a item 0 string with the name of the font (DINEngschriftStd.otf)
If you used a raw socket (SOCK_RAW
) and re-implemented TCP in userland, I think the answer is limited in this case only by the number of (local address, source port, destination address, destination port)
tuples (~2^64 per local address).
It would of course take a lot of memory to keep the state of all those connections, and I think you would have to set up some iptables rules to keep the kernel TCP stack from getting upset &/or responding on your behalf.
Use selectors like CSS3
$("banner.html>div:first-child").append(data);
A lot of these answers are pretty old, so I thought I would update with a solution that I think is helpful.
Our issue was similar to OP's, we upgraded 32 bit XP machines to 64 bit windows 7 and our application software that uses a 32 bit ODBC driver stopped being able to write to our database.
Turns out, there are two ODBC Data Source Managers, one for 32 bit and one for 64 bit. So I had to run the 32 bit version which is found in C:\Windows\SysWOW64\odbcad32.exe. Inside the ODBC Data Source Manager, I was able to go to the System DSN tab and Add my driver to the list using the Add button. (You can check the Drivers tab to see a list of the drivers you can add, if your driver isn't in this list then you may need to install it).
The next issue was the software that we ran was compiled to use 'Any CPU'. This would see the operating system was 64 bit, so it would look at the 64 bit ODBC Data Sources. So I had to force the program to compile as an x86 program, which then tells it to look at the 32 bit ODBC Data Sources. To set your program to x86, in Visual Studio go to your project properties and under the build tab at the top there is a platform drop down list, and choose x86. If you don't have the source code and can't compile the program as x86, you might be able to right click the program .exe and go to the compatibility tab and choose a compatibility that works for you.
Once I had the drivers added and the program pointing to the right drivers, everything worked like it use to. Hopefully this helps anyone working with older software.
let dict : [String : Any] = ["FirstName" : "Maninder" , "LastName" : "Singh" , "Address" : "Chandigarh"]
dict.forEach { print($0) }
Result would be
("FirstName", "Maninder") ("LastName", "Singh") ("Address", "Chandigarh")
In Addition to the above answers, there probably should be noted that there is a legacy way to implement the initialization. There is an interface called Initializable from the fxml library.
import javafx.fxml.Initializable;
class MyController implements Initializable {
@FXML private TableView<MyModel> tableView;
@Override
public void initialize(URL location, ResourceBundle resources) {
tableView.getItems().addAll(getDataFromSource());
}
}
Parameters:
location - The location used to resolve relative paths for the root object, or null if the location is not known.
resources - The resources used to localize the root object, or null if the root object was not localized.
And the note of the docs why the simple way of using @FXML public void initialize()
works:
NOTE
This interface has been superseded by automatic injection of location and resources properties into the controller. FXMLLoader will now automatically call any suitably annotated no-arg initialize() method defined by the controller. It is recommended that the injection approach be used whenever possible.
Posed question
Responding to the question 'what metric should be used for multi-class classification with imbalanced data': Macro-F1-measure. Macro Precision and Macro Recall can be also used, but they are not so easily interpretable as for binary classificaion, they are already incorporated into F-measure, and excess metrics complicate methods comparison, parameters tuning, and so on.
Micro averaging are sensitive to class imbalance: if your method, for example, works good for the most common labels and totally messes others, micro-averaged metrics show good results.
Weighting averaging isn't well suited for imbalanced data, because it weights by counts of labels. Moreover, it is too hardly interpretable and unpopular: for instance, there is no mention of such an averaging in the following very detailed survey I strongly recommend to look through:
Sokolova, Marina, and Guy Lapalme. "A systematic analysis of performance measures for classification tasks." Information Processing & Management 45.4 (2009): 427-437.
Application-specific question
However, returning to your task, I'd research 2 topics:
Commonly used metrics. As I can infer after looking through literature, there are 2 main evaluation metrics:
Yu, April, and Daryl Chang. "Multiclass Sentiment Prediction using Yelp Business."
(link) - note that the authors work with almost the same distribution of ratings, see Figure 5.
Pang, Bo, and Lillian Lee. "Seeing stars: Exploiting class relationships for sentiment categorization with respect to rating scales." Proceedings of the 43rd Annual Meeting on Association for Computational Linguistics. Association for Computational Linguistics, 2005.
(link)
Lee, Moontae, and R. Grafe. "Multiclass sentiment analysis with restaurant reviews." Final Projects from CS N 224 (2010).
(link) - they explore both accuracy and MSE, considering the latter to be better
Pappas, Nikolaos, Rue Marconi, and Andrei Popescu-Belis. "Explaining the Stars: Weighted Multiple-Instance Learning for Aspect-Based Sentiment Analysis." Proceedings of the 2014 Conference on Empirical Methods In Natural Language Processing. No. EPFL-CONF-200899. 2014.
(link) - they utilize scikit-learn for evaluation and baseline approaches and state that their code is available; however, I can't find it, so if you need it, write a letter to the authors, the work is pretty new and seems to be written in Python.
Cost of different errors. If you care more about avoiding gross blunders, e.g. assinging 1-star to 5-star review or something like that, look at MSE; if difference matters, but not so much, try MAE, since it doesn't square diff; otherwise stay with Accuracy.
About approaches, not metrics
Try regression approaches, e.g. SVR, since they generally outperforms Multiclass classifiers like SVC or OVA SVM.
Just as an empty Request body is in keeping with the original purpose of a GET request and empty response body is in keeping with the original purpose of a PUT request.
I think what you are looking for is something like this:
$(field).closest("form").submit();
For example, to handle the onchange event, you would have this:
$(select your fields here).change(function() {
$(this).closest("form").submit();
});
If, for some reason you aren't using jQuery 1.3 or above, you can call parents
instead of closest
.
As of today, Windows PowerShell 5.1 is the latest version. It can be installed as part of Windows Management Framework 5.1. It was released in January 2017.
Quoting from the official Microsoft download page here.
Some of the new and updated features in this release include:
- Constrained file copying to/from JEA endpoints
- JEA support for Group Managed Service Accounts and Conditional Access Policies
- PowerShell console support for VT100 and redirecting stdin with interactive input
- Support for catalog signed modules in PowerShell Get
- Specifying which module version to load in a script
- Package Management cmdlet support for proxy servers
- PowerShellGet cmdlet support for proxy servers
- Improvements in PowerShell Script Debugging
- Improvements in Desired State Configuration (DSC)
- Improved PowerShell usage auditing using Transcription and Logging
- New and updated cmdlets based on community feedback
I was having same problem and @webtrifusion's answer helped find the solution.
My model was using the Bind(Exclude)
attribute on the entity's ID which was causing the value of the entity's ID to be zero on HttpPost.
namespace OrderUp.Models
{
[Bind(Exclude = "OrderID")]
public class Order
{
[ScaffoldColumn(false)]
public int OrderID { get; set; }
[ScaffoldColumn(false)]
public System.DateTime OrderDate { get; set; }
[Required(ErrorMessage = "Name is required")]
public string Username { get; set; }
}
}
Is there an easy way to view all methods which contain this comment? Some sort of menu option?
Yes, choose one of the following:
Go to Window ? Show View ? Tasks (Not TaskList). The new view will show up where the "Console" and "Problems" tabs are by default.
As mentioned elsewhere, you can see them next to the scroll bar as little blue rectangles if you have the source file in question open.
If you just want the // TODO Auto-generated method stub
messages (rather than all // TODO
messages) you should use the search function (Ctrl-F for ones in this file Search ? Java Search ? Search string for the ability to specify this workspace, that file, this project, etc.)
match is much faster than search, so instead of doing regex.search("word") you can do regex.match((.*?)word(.*?)) and gain tons of performance if you are working with millions of samples.
This comment from @ivan_bilan under the accepted answer above got me thinking if such hack is actually speeding anything up, so let's find out how many tons of performance you will really gain.
I prepared the following test suite:
import random
import re
import string
import time
LENGTH = 10
LIST_SIZE = 1000000
def generate_word():
word = [random.choice(string.ascii_lowercase) for _ in range(LENGTH)]
word = ''.join(word)
return word
wordlist = [generate_word() for _ in range(LIST_SIZE)]
start = time.time()
[re.search('python', word) for word in wordlist]
print('search:', time.time() - start)
start = time.time()
[re.match('(.*?)python(.*?)', word) for word in wordlist]
print('match:', time.time() - start)
I made 10 measurements (1M, 2M, ..., 10M words) which gave me the following plot:
The resulting lines are surprisingly (actually not that surprisingly) straight. And the search
function is (slightly) faster given this specific pattern combination. The moral of this test: Avoid overoptimizing your code.
You need
var href = $(this).attr('href');
Inside a jQuery click handler, the this
object refers to the element clicked, whereas in your case you're always getting the href for the first <a>
on the page. This, incidentally, is why your example works but your real code doesn't
In short:
JWT vs Cookie Auth
| | Cookie | JWT |
| Stateless | No | Yes |
| Cross domain usage | No | Yes |
| Mobile ready | No | Yes |
| Performance | Low | High (no need in request to DB) |
| Add to request | Automatically | Manually (if not in cookie) |
High performance ANPR Library - http://www.dtksoft.com/dtkanpr.php. This is commercial, but they provide trial key.
require(ggplot2)
require(nlme)
set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)
mp <- within(mp,
{
wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
wow <- rnorm(N)*wav+rnorm(N)*wav^3
})
m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))
Get fitted values (the same as m01$fitted
)
fit <- predict(m01)
Normally we could use something like predict(...,se.fit=TRUE)
to get the confidence intervals on the prediction, but gls
doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :
V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))
Put together a "prediction frame":
predframe <- with(mp,data.frame(year,wav,
wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))
Now plot with geom_ribbon
(p1 <- ggplot(mp, aes(year, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It's easier to see that we got the right answer if we plot against wav
rather than year
:
(p2 <- ggplot(mp, aes(wav, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly()
fits -- see ?makepredictcall
.
I have just tested the following pipeline and it works
parallel firstBranch: {
stage ('Starting Test')
{
build job: 'test1', parameters: [string(name: 'Environment', value: "$env.Environment")]
}
}, secondBranch: {
stage ('Starting Test2')
{
build job: 'test2', parameters: [string(name: 'Environment', value: "$env.Environment")]
}
}
This Job named 'trigger-test' accepts one parameter named 'Environment'
Job 'test1' and 'test2' are simple jobs:
Example for 'test1'
On execution, I am able to see both stages running in the same time
You should not have multiple "uses-sdk" tags in your file. ref - docs
Use this syntax:
<uses-sdk android:minSdkVersion="integer"
android:targetSdkVersion="integer"
android:maxSdkVersion="integer" />
Sometimes things might be simpler. I came here with the exact issue and tried all the suggestions. But later found that the problem was just the local file path was different and I was on a different folder. :-)
eg -
~/myproject/mygitrepo/app/$ git diff app/TestFile.txt
should have been
~/myproject/mygitrepo/app/$ git diff TestFile.txt
I had same problem in the render() method. The problem comes when you return from render() as :
render() {
return
(
<div>Here comes JSX !</div>
);
}
i.e. if you start the parenthesis in a new line
Try using:
render() {
return (
<div>Here comes JSX !</div>
);
}
This will solve the error
Use Collections.swap
and Arrays.asList
:
Collections.swap(Arrays.asList(arr), i, j);
On Mojave
The binary is in
/usr/bin/git
The related scripts are here
/Applications/Xcode.app/Contents/Developer/usr/libexec/git-core/git
I had a similar issue but from reading this question I figured I could run on UI thread:
YourActivity.this.runOnUiThread(new Runnable() {
public void run() {
alertDialog.show();
}
});
Seems to do the trick for me.
If you need to remove text inside nested parentheses, too, then:
var prevStr;
do {
prevStr = str;
str = str.replace(/\([^\)\(]*\)/, "");
} while (prevStr != str);
<table border="1">
<tr>
<td>one</td>
<td style="border-bottom-style: hidden;">two</td>
</tr>
<tr>
<td>one</td>
<td style="border-top-style: hidden;">two</td>
</tr>
</table>
_x000D_
so you can use parent() to reach to the parent tr and then use find to gather the td with class two
var Something = $(this).parent().find(".two").html();
or
var Something = $(this).parent().parent().find(".two").html();
use as much as parent() what ever the depth of the clicked object according to the tr row
hope this works...
If you're looking to scatter by two variables and color by the third, Altair can be a great choice.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df = pd.DataFrame(40*np.random.randn(10, 3), columns=['A', 'B','C'])
Altair plot
from altair import *
Chart(df).mark_circle().encode(x='A',y='B', color='C').configure_cell(width=200, height=150)
Since you've already stashed your changes, all you need is this one-liner:
git stash branch <branchname> [<stash>]
From the docs (https://www.kernel.org/pub/software/scm/git/docs/git-stash.html):
Creates and checks out a new branch named <branchname> starting from the commit at which the <stash> was originally created, applies the changes recorded in <stash> to the new working tree and index. If that succeeds, and <stash> is a reference of the form stash@{<revision>}, it then drops the <stash>. When no <stash> is given, applies the latest one.
This is useful if the branch on which you ran git stash save has changed enough that git stash apply fails due to conflicts. Since the stash is applied on top of the commit that was HEAD at the time git stash was run, it restores the originally stashed state with no conflicts.
That depends on the situation. Often the most simple approach is the best because it is easy to understand:
if (something) {
otherThing = 1;
} else {
otherThing = 0;
}
or
int otherThing = something ? 1 : 0;
But sometimes it useful to use an Enum instead of a boolean flag. Let imagine there are synchronous and asynchronous processes:
Process process = Process.SYNCHRONOUS;
System.out.println(process.getCode());
In Java, enum can have additional attributes and methods:
public enum Process {
SYNCHRONOUS (0),
ASYNCHRONOUS (1);
private int code;
private Process (int code) {
this.code = code;
}
public int getCode() {
return code;
}
}
for what it's worth:
if( document.addEventListener ){
alert("you got IE9 or greater");
}
This successfully targets IE 9+ because the addEventListener
method was supported very early on for every major browser but IE. (Chrome, Firefox, Opera, and Safari) MDN Reference. It is supported currently in IE9 and we can expect it to continue to be supported here on out.
Using html5 I cooked up this one:
Some where on the page:
<h2 id="heading" data-activetab="@ViewBag.activetab">Some random text</h2>
The viewbag should just contain the id for the page/element eg.: "testing"
I created a site.js and added the scrip on the page:
/// <reference path="../jquery-2.1.0.js" />
$(document).ready(
function() {
var setactive = $("#heading").data("activetab");
var a = $('#' + setactive).addClass("active");
}
)
Now all you have to do is to add your id's to your navbar. Eg.:
<ul class="nav navbar-nav">
<li **id="testing" **>
@Html.ActionLink("Lalala", "MyAction", "MyController")
</li>
</ul>
All hail the data attribute :)
If the e.target
is the same element as this
, you've not clicked on a descendant.
$('.foobar').on('click', function(e) {_x000D_
if (e.target !== this)_x000D_
return;_x000D_
_x000D_
alert( 'clicked the foobar' );_x000D_
});
_x000D_
.foobar {_x000D_
padding: 20px; background: yellow;_x000D_
}_x000D_
span {_x000D_
background: blue; color: white; padding: 8px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div class='foobar'> .foobar (alert) _x000D_
<span>child (no alert)</span>_x000D_
</div>
_x000D_
This question is already answered here
The classpath never includes specific files. It includes directories and jar files. So, put that file in a directory that is in your classpath
.
Log4j
properties aren't (normally) used in developing apps (unless you're debugging Eclipse itself!). So what you really want to to build the executable Java app (Application, WAR, EAR or whatever) and include the Log4j
properties in the runtime classpath.
Agile is the practice and Scrum is the process to following this practice same as eXtreme Programming (XP) and Kanban are the alternative process to following Agile development practice.
DiffUtil can the best choice for updating the data in the RecyclerView Adapter which you can find in the android framework. DiffUtil is a utility class that can calculate the difference between two lists and output a list of update operations that converts the first list into the second one.
Most of the time our list changes completely and we set new list to RecyclerView Adapter. And we call notifyDataSetChanged to update adapter. NotifyDataSetChanged is costly. DiffUtil class solves that problem now. It does its job perfectly!
Pure numpy
numpy.loadtxt(open("test.csv", "rb"), delimiter=",", skiprows=1)
Check out the loadtxt documentation.
You can also use python's csv module:
import csv
import numpy
reader = csv.reader(open("test.csv", "rb"), delimiter=",")
x = list(reader)
result = numpy.array(x).astype("float")
You will have to convert it to your favorite numeric type. I guess you can write the whole thing in one line:
result = numpy.array(list(csv.reader(open("test.csv", "rb"), delimiter=","))).astype("float")
Added Hint:
You could also use pandas.io.parsers.read_csv
and get the associated numpy
array which can be faster.
Be careful: Xcode is caseSensitive with file names. It's not the same "Fun" than "fun".
When testing for directories remember that every directory contains two special files.
One is called '.' and the other '..'
. is the directory's own name while .. is the name of it's parent directory.
To avoid trailing backslash problems just test to see if the directory knows it's own name.
eg:
if not exist %temp%\buffer\. mkdir %temp%\buffer
SELECT empname
FROM empdetails
WHERE salary IN(SELECT deptid max(salary) AS salary
FROM empdetails
group by deptid)
EDIT: As of 2019, e.metaKey
is supported on all major browsers as per the MDN.
Note that on Windows, although the ? Windows key is considered to be the "meta" key, it is not going to be captured by browsers as such.
This is only for the command key on MacOS/keyboards.
Unlike Shift/Alt/Ctrl, the Cmd (“Apple”) key is not considered a modifier key—instead, you should listen on keydown
/keyup
and record when a key is pressed and then depressed based on event.keyCode
.
Unfortunately, these key codes are browser-dependent:
224
17
91
(Left Command) or 93
(Right Command)You might be interested in reading the article JavaScript Madness: Keyboard Events, from which I learned that knowledge.
you can also use es6-enum package (https://www.npmjs.com/package/es6-enum). It's very easy to use. See the example below:
import Enum from "es6-enum";
const Colors = Enum("red", "blue", "green");
Colors.red; // Symbol(red)
tidyverse edition with pipe and write_lines()
from readr
library(tidyverse)
c('Hello', 'World') %>% write_lines( "output.txt")
Here's another way of attaching the event based on W3C DOM Level 2 Events Specification:
transport_select.addEventListener(
'change',
function() { toggleSelect(this.id); },
false
);
My favorite:
df = df.iloc[0:0]
But be aware df.index.max() will be nan. To add items I use:
df.loc[0 if math.isnan(df.index.max()) else df.index.max() + 1] = data
I would like to expand on the ===
operator.
===
is not an equality operator!
Not.
Let's get that point really across.
You might be familiar with ===
as an equality operator in Javascript and PHP, but this just not an equality operator in Ruby and has fundamentally different semantics.
So what does ===
do?
===
is the pattern matching operator!
===
matches regular expressions===
checks range membership===
checks being instance of a class ===
calls lambda expressions===
sometimes checks equality, but mostly it does notSo how does this madness make sense?
Enumerable#grep
uses ===
internallycase when
statements use ===
internallyrescue
uses ===
internallyThat is why you can use regular expressions and classes and ranges and even lambda expressions in a case when
statement.
Some examples
case value
when /regexp/
# value matches this regexp
when 4..10
# value is in range
when MyClass
# value is an instance of class
when ->(value) { ... }
# lambda expression returns true
when a, b, c, d
# value matches one of a through d with `===`
when *array
# value matches an element in array with `===`
when x
# values is equal to x unless x is one of the above
end
All these example work with pattern === value
too, as well as with grep
method.
arr = ['the', 'quick', 'brown', 'fox', 1, 1, 2, 3, 5, 8, 13]
arr.grep(/[qx]/)
# => ["quick", "fox"]
arr.grep(4..10)
# => [5, 8]
arr.grep(String)
# => ["the", "quick", "brown", "fox"]
arr.grep(1)
# => [1, 1]
Jacob Helwig mentions in his answer that:
It looks like rev-parse is being used without sufficient error checking before-hand
Commit 62f162f from Jeff King (peff
) should improve the robustness of git rev-parse
in Git 1.9/2.0 (Q1 2014) (in addition of commit 1418567):
For cases where we do not match (e.g., "
doesnotexist..HEAD
"), we would then want to try to treat the argument as a filename.
try_difference()
gets this right, and always unmunges in this case.
However,try_parent_shorthand()
never unmunges, leading to incorrect error messages, or even incorrect results:
$ git rev-parse foobar^@
foobar
fatal: ambiguous argument 'foobar': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
$prompt: /path/to/script
and hit enter. Note you need to make sure the script has execute permissions.
Useful to quickly print entries in a HashMap
System.out.println(Arrays.toString(map.entrySet().toArray()));
If you get code behind, use some like this
MyCustomObject myObject = new MyCustomObject();
myObject.name='try';
//OBJECT -> JSON
var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string myObjectJson = javaScriptSerializer.Serialize(myObject);
//return JSON
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(myObjectJson );
Response.End();
So you return a json object serialized with all attributes of MyCustomObject.
if (!*text) {}
The above dereferences the pointer 'text' and checks to see if it's zero. alternatively:
if (*text == 0) {}
To convert this bytesarray directly to json, you could first convert the bytesarray to a string with decode(), utf-8 is standard. Change the quotation markers.. The last step is to remove the " from the dumped string, to change the json object from string to list.
dumps(s.decode()).replace("'", '"')[1:-1]
if you use Windows 10, this is the directory:
C:\Users<UserName>\AppData\Local\
+
<ProjectName.exe_Url_somedata>\1.0.0.0<filename.config>