A quick way is to use python command line tool.
Simply type import <your module name>
You see an error if module is missing.
$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
>>> import sys
>>> import jocker
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named jocker
$
If you are using asset catalog, and have multiple targets both using same asset catalog file, be sure that this file has checked both targets in the right panel in xcode.
That was my problem.
If you have some changes on your workspace and you want to stash them into a new branch use this command:
git stash branch branchName
It will make:
- a new branch
- move changes to this branch
- and remove latest stash (Like: git stash pop)
math.fabs()
always returns float, while abs()
may return integer.
you can make a new object of your class and then assign it's parameters dynamically from the JSON object's parameters.
const employeeData = JSON.parse(employeeString);
let emp:Employee=new Employee();
const keys=Object.keys(employeeData);
keys.forEach(key=>{
emp[key]=employeeData[key];
});
console.log(emp);
now the emp is an object of Employee containing all fields of employeeString's Json object(employeeData);
You can use android:drawableLeft="@drawable/your_icon"
to set the drawable to be shown on the left side. In order to set a padding for the drawable you should use the android:paddingLeft
or android:paddingRight
to set the left/right padding respectively.
android:paddingRight="10dp"
android:paddingLeft="20dp"
android:drawableRight="@drawable/ic_app_manager"
Below is to check the current limit
csv.field_size_limit()
Out[20]: 131072
Below is to increase the limit. Add it to the code
csv.field_size_limit(100000000)
Try checking the limit again
csv.field_size_limit()
Out[22]: 100000000
Now you won't get the error "_csv.Error: field larger than field limit (131072)"
I think the following code clears the difference:
String A = new String("Venugopal");
String B = A;
A = A +"mitul";
System.out.println("A is " + A);
System.out.println("B is " + B);
StringBuffer SA = new StringBuffer("Venugopal");
StringBuffer SB = SA;
SA = SA.append("mitul");
System.out.println("SA is " + SA);
System.out.println("SB is " + SB);
You just need to wrap object in ()
var arr = [{_x000D_
id: 1,_x000D_
name: 'bill'_x000D_
}, {_x000D_
id: 2,_x000D_
name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
1.1 Create an empty stack
2.1 Do following while root is not NULL
a) Push root's right child and then root to stack.
b) Set root as root's left child.
2.2 Pop an item from stack and set it as root.
a) If the popped item has a right child and the right child
is at top of stack, then remove the right child from stack,
push the root back and set root as root's right child.
b) Else print root's data and set root as NULL.
2.3 Repeat steps 2.1 and 2.2 while stack is not empty.
I'm searched many answers that suggest me to type in cmd:
set path = "%path%;c:program files\java\jdk1.7.0\bin"
but this is WRONG!
the right solution is that you leave "set" and just type
path = %path%;c:program files\java\jdk1.7.0\bin
P/s: of course you have to replace "jdk1.7.0" folder by your current java version folder. This works well on win 7 32bit, but I think it also works on win 8 - try it!
In Python 2, you can input multiple values comma separately (as jcfollower mention in his solution). But if you want to do it explicitly, you can proceed in following way. I am taking multiple inputs from users using a for loop and keeping them in items list by splitting with ','.
items= [x for x in raw_input("Enter your numbers comma separated: ").split(',')]
print items
Detection is automatic. You must specify what css can be used for each screen resolution:
/* for all screens, use 14px font size */
body {
font-size: 14px;
}
/* responsive, form small screens, use 13px font size */
@media (max-width: 479px) {
body {
font-size: 13px;
}
}
Hi the problem is in FileDownloader class
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
You need to remove the above two lines and everything will work fine. Please mark the question as answered if it is working as expected.
Latest solution for the same problem is updated Android PDF Write / Read using Android 9 (API level 28)
Attaching the working code with screenshots.
MainActivity.java
package com.example.downloadread;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void download(View v)
{
new DownloadFile().execute("http://maven.apache.org/maven-1.x/maven.pdf", "maven.pdf");
}
public void view(View v)
{
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/testthreepdf/" + "maven.pdf"); // -> filename = maven.pdf
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try{
startActivity(pdfIntent);
}catch(ActivityNotFoundException e){
Toast.makeText(MainActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
}
private class DownloadFile extends AsyncTask<String, Void, Void>{
@Override
protected Void doInBackground(String... strings) {
String fileUrl = strings[0]; // -> http://maven.apache.org/maven-1.x/maven.pdf
String fileName = strings[1]; // -> maven.pdf
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "testthreepdf");
folder.mkdir();
File pdfFile = new File(folder, fileName);
try{
pdfFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
FileDownloader.downloadFile(fileUrl, pdfFile);
return null;
}
}
}
FileDownloader.java
package com.example.downloadread;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class FileDownloader {
private static final int MEGABYTE = 1024 * 1024;
public static void downloadFile(String fileUrl, File directory){
try {
URL url = new URL(fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
//urlConnection.setRequestMethod("GET");
//urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(directory);
int totalSize = urlConnection.getContentLength();
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.downloadread"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.downloadread.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="15dp"
android:text="download"
android:onClick="download" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/button1"
android:layout_marginTop="38dp"
android:text="view"
android:onClick="view" />
</RelativeLayout>
You can do:
du -h your_directory
which will give you the size of your target directory.
If you want a brief output, du -hcs your_directory
is nice.
Try this:
int dayOfWeek = date.get(Calendar.DAY_OF_WEEK);
String weekday = new DateFormatSymbols().getShortWeekdays()[dayOfWeek];
Below code is self-explanatory, We can use an enum with a switch case:
/**
*
*/
enum ClassNames {
STRING(String.class, String.class.getSimpleName()),
BOOLEAN(Boolean.class, Boolean.class.getSimpleName()),
INTEGER(Integer.class, Integer.class.getSimpleName()),
LONG(Long.class, Long.class.getSimpleName());
private Class typeName;
private String simpleName;
ClassNames(Class typeName, String simpleName){
this.typeName = typeName;
this.simpleName = simpleName;
}
}
Based on the class values from the enum can be mapped:
switch (ClassNames.valueOf(clazz.getSimpleName())) {
case STRING:
String castValue = (String) keyValue;
break;
case BOOLEAN:
break;
case Integer:
break;
case LONG:
break;
default:
isValid = false;
}
Hope it helps :)
I tried find similiar as topic first post.
For my needs I find this
http://answers.oreilly.com/topic/217-how-to-match-whole-words-with-a-regular-expression/
"\b[a-zA-Z0-9]{3}\b"
3 char words only "iokldöajf asd alkjwnkmd asd kja wwda da aij ednm <.jkakla "
They are the same. Boolean helps simplify conversion back and forth between C# and VB.Net. Most C# programmers tend to prefer 'bool', but if you are in a shop where there's a lot of both VB.Net and C# then you may prefer Boolean because it works in both places.
You can try with
.appBackground {
position: relative;
background-image: url(".../img/background.jpg");
background-repeat:no-repeat;
background-size:100% 100vh;
}
works for me :)
This error appears when you wish to run a software which require the Microsoft Visual C++ Redistributable 2012. Download it fromMicrosoft website as x86 or x64 edition. Depending on the software you wish to install you need to install either the 32 bit or the 64 bit version. Visit the following link: http://www.microsoft.com/en-us/download/details.aspx?id=30679#
Tried to install lxml, grab and other extensions, which requires VS 10.0+ and get the same issue. I find own way to solve this problem(Windows 10 x64, Python 3.4+):
Install Visual C++ 2010 Express (download). (Do not install Microsoft Visual Studio 2010 Service Pack 1 )
Remove all the Microsoft Visual C++ 2010 Redistributable packages from Control Panel\Programs and Features. If you don't do those then the install is going to fail with an obscure "Fatal error during installation" error.
Install offline version of Windows SDK for Visual Studio 2010 (v7.1) (download). This is required for 64bit extensions. Windows has builtin mounting for ISOs. Just mount the ISO and run Setup\SDKSetup.exe instead of setup.exe.
Create a vcvars64.bat file in C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64 that contains:
CALL "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.cmd" /x64
Find extension on this site, then put them into the python folder, and install .whl extension with pip:
python -m pip install extensionname.whl
Enjoy
I was having this same issue and after much wrangling I decided to try and isolate the problem and simply load the script manager in an empty page which still resulted in this same error. Having isolated the problem I discovered through a comparison of my site's web.config with a brand new (working) test site that changing <compilation debug="true">
to <compilation debug="false">
in the system.web section of my web.config fixes the problem.
I also had to remove the <xhtmlConformance mode="Legacy"/>
entry from system.web to make the update panel work properly. Click here for a description of this issue.
something
{
something1
something2
}
something3
In Python
Something
something1
something2
something3
I'm finding that it's kind of tricky to get pip3 (v9.0.1, as installed by Ubuntu 18.04's package manager) to actually install the thing I tell it to install. I'm posting this answer to save anyone's time who runs into this problem.
Putting this into a requirements.txt file failed:
git+git://github.com/myname/myrepo.git@my-branch#egg=eggname
By "failed" I mean that while it downloaded the code from Git, it ended up installing the original version of the code, as found on PyPi, instead of the code in the repo on that branch.
However, installing the commmit instead of the branch name works:
git+git://github.com/myname/myrepo.git@d27d07c9e862feb939e56d0df19d5733ea7b4f4d#egg=eggname
You could use POSIX [[:blank:]]
to match a horizontal white-space character.
sed 's/[[:blank:]]\+/\n/g' file
or you may use [[:space:]]
instead of [[:blank:]]
also.
Example:
$ echo 'this is a sentence' | sed 's/[[:blank:]]\+/\n/g'
this
is
a
sentence
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
super.touchesBegan(touches, withEvent: event)
let touch : UITouch = touches.anyObject() as UITouch
if touch.view.isKindOfClass(UIPickerView)
{
}
}
Edit
As pointed out in @Kevin's answer, the correct way would be to use optional type cast operator as?
. You can read more about it on the section Optional Chaining
sub section Downcasting
.
Edit 2
As pointed on the other answer by user @KPM, using the is
operator is the right way to do it.
this is the most simple way but it works for me with a ComboBox1 name
SOLUTION on 3 Basic STEPS:
step 1.
Declare a variable at the beginning of your form which will hold the original text value of the ComboBox. Example:
Dim xCurrentTextValue as string
step 2.
Create the event combobox1 key down and Assign to xCurrentTextValue variable the current text of the combobox if any key diferrent than "ENTER" is pressed the combobox text value keeps the original text value
Example:
Private Sub ComboBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles ComboBox1.KeyDown
xCurrentTextValue = ComboBox1.Text
If e.KeyCode <> Keys.Enter Then
Me.ComboBox1.Text = xCmbItem
End If
End Sub
step 3.
Validate the when the combo text is changed if len(xcurrenttextvalue)> 0 or is different than nothing then the combobox1 takes the xcurrenttextvalue variable value
Private Sub ComboBox1_TextChanged(sender As Object, e As EventArgs) Handles ComboBox1.TextChanged
If Len(xCurrentTextValue) > 0 Then
Me.ComboBox1.Text = xCurrentTextValue
End If
End Sub
========================================================== that's it,
Originally I only tried the step number 2, but I have problems when you press the DEL key and DOWN arrow key, also for some reason it didn't validate the keydown event unless I display any message box
!Sorry, this is a correction on step number 2, I forgot to change the variable xCmbItem to xCurrentTextValue, xCmbItem it was used for my personal use
THIS IS THE CORRECT CODE
xCurrentTextValue = ComboBox1.Text
If e.KeyCode <> Keys.Enter Then
Me.ComboBox1.Text = xCurrentTextValue
End If
Following code uses a third-party ZIP component from Rebex:
// add content of the local directory C:\Data\
// to the root directory in the ZIP archive
// (ZIP archive C:\archive.zip doesn't have to exist)
Rebex.IO.Compression.ZipArchive.Add(@"C:\archive.zip", @"C:\Data\*", "");
Or if you want to add more folders without need to open and close archive multiple times:
using Rebex.IO.Compression;
...
// open the ZIP archive from an existing file
ZipArchive zip = new ZipArchive(@"C:\archive.zip", ArchiveOpenMode.OpenOrCreate);
// add first folder
zip.Add(@"c:\first\folder\*","\first\folder");
// add second folder
zip.Add(@"c:\second\folder\*","\second\folder");
// close the archive
zip.Close(ArchiveSaveAction.Auto);
You can download the ZIP component here.
Using a free, LGPL licensed SharpZipLib is a common alternative.
Disclaimer: I work for Rebex
don't put your commands in variables, just run it
matchdir="/home/joao/robocup/runner_workdir/matches/testmatch/"
PWD=$(pwd)
teamAComm="$PWD/a.sh"
teamBComm="$PWD/b.sh"
include="$PWD/server_official.conf"
serverbin='/usr/local/bin/rcssserver'
cd $matchdir
$serverbin include=$include server::team_l_start = ${teamAComm} server::team_r_start=${teamBComm} CSVSaver::save='true' CSVSaver::filename = 'out.csv'
you can use two different methods to delete or any query in sqlite android
first method is
public void deleteItem(Student item) {
SQLiteDatabase db = getWritableDatabase();
String whereClause = "id=?";
String whereArgs[] = {item.id.toString()};
db.delete("Items", whereClause, whereArgs);
}
second method
public void deleteAll()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+ TABLE_NAME);
db.close();
}
use any method for your use case
Note that starting Python 3.8
, the standard library provides the math.comb
function to compute the binomial coefficient:
math.comb(n, k)
which is the number of ways to choose k items from n items without repetition n! / (k! (n - k)!)
:
import math
math.comb(10, 5) # 252
math.comb(10, 10) # 1
To fully overload it you also need to implement the __setitem__
and __delitem__
methods.
edit
I almost forgot... if you want to completely emulate a list, you also need __getslice__, __setslice__ and __delslice__
.
There are all documented in http://docs.python.org/reference/datamodel.html
Here is a rough description of HashMap
's mechanism, for Java 8
version, (it might be slightly different from Java 6).
hash()
on key, and it decide which bucket of the hashtable to use for a given key.Map.Entry
HashMap.Node
Linked list version of node.
It could represent:
HashMap.TreeNode
Node[] table
Set<Map.Entry> entrySet
Set of entities.int size
float loadFactor
int threshold
threshold = capacity * loadFactor
int hash(key)
How to map hash to bucket?
Use following logic:
static int hashToBucket(int tableSize, int hash) { return (tableSize - 1) & hash; }
In hash table, capacity means the bucket count, it could be get from table.length
.
Also could be calculated via threshold
and loadFactor
, thus no need to be defined as a class field.
Could get the effective capacity via: capacity()
threshold
reached, will double hashtable's capacity(table.length
), then perform a re-hash on all elements to rebuild the table.O(1)
, because:
O(1)
.O(1)
.O(1)
, not O(log N)
.Window > Perspective > Reset Perspective
It's also possible to use a regular expression to achieve this when you want to test for any whitespace character and not just a space.
var text = "sossjj ssskkk";
var regex = new Regex(@"\s");
regex.IsMatch(text); // true
Just enter plt.hold(False)
before the first plt.plot, and you can stick to your original code.
The old way:
xcopy [source] [destination] /E
xcopy is deprecated. Robocopy replaces Xcopy. It comes with Windows 8, 8.1 and 10.
robocopy [source] [destination] /E
robocopy has several advantages:
More details here.
bootstrap.yml
or bootstrap.properties
It's only used/needed if you're using Spring Cloud and your application's configuration is stored on a remote configuration server (e.g. Spring Cloud Config Server).
From the documentation:
A Spring Cloud application operates by creating a "bootstrap" context, which is a parent context for the main application. Out of the box it is responsible for loading configuration properties from the external sources, and also decrypting properties in the local external configuration files.
Note that the bootstrap.yml
or bootstrap.properties
can contain additional configuration (e.g. defaults) but generally you only need to put bootstrap config here.
Typically it contains two properties:
spring.cloud.config.uri
)spring.application.name
)Upon startup, Spring Cloud makes an HTTP call to the config server with the name of the application and retrieves back that application's configuration.
application.yml
or application.properties
Contains standard application configuration - typically default configuration since any configuration retrieved during the bootstrap process will override configuration defined here.
As in your question, which is actually a simple 2-D array wouldn't it be better? Have a look-
Let say your 2-D array name $my_array and value to find is $id
function idExists($needle='', $haystack=array()){
//now go through each internal array
foreach ($haystack as $item) {
if ($item['id']===$needle) {
return true;
}
}
return false;
}
and to call it:
idExists($id, $my_array);
As you can see, it actually only check if any internal index with key_name 'id' only, have your $value. Some other answers here might also result true if key_name 'name' also has $value
This is similar to the top answer, but I like it better because it avoids explicit indexing. Assuming your list has the name lst
, you can generate
(item, next_item)
tuples from your list with zip
:
all(x <= y for x,y in zip(lst, lst[1:]))
In Python 3, zip
already returns a generator, in Python 2 you can use itertools.izip
for better memory efficiency.
Small demo:
>>> lst = [1, 2, 3, 4]
>>> zip(lst, lst[1:])
[(1, 2), (2, 3), (3, 4)]
>>> all(x <= y for x,y in zip(lst, lst[1:]))
True
>>>
>>> lst = [1, 2, 3, 2]
>>> zip(lst, lst[1:])
[(1, 2), (2, 3), (3, 2)]
>>> all(x <= y for x,y in zip(lst, lst[1:]))
False
The last one fails when the tuple (3, 2)
is evaluated.
Bonus: checking finite (!) generators which cannot be indexed:
>>> def gen1():
... yield 1
... yield 2
... yield 3
... yield 4
...
>>> def gen2():
... yield 1
... yield 2
... yield 4
... yield 3
...
>>> g1_1 = gen1()
>>> g1_2 = gen1()
>>> next(g1_2)
1
>>> all(x <= y for x,y in zip(g1_1, g1_2))
True
>>>
>>> g2_1 = gen2()
>>> g2_2 = gen2()
>>> next(g2_2)
1
>>> all(x <= y for x,y in zip(g2_1, g2_2))
False
Make sure to use itertools.izip
here if you are using Python 2, otherwise you would defeat the purpose of not having to create lists from the generators.
Isn't this the simplest way?
By column name:
In [20]: df = pd.DataFrame({'x' : [1, 2, 3, 4], 'y' : [4, 5, 6, 7]})
In [21]: df
Out[21]:
x y
0 1 4
1 2 5
2 3 6
3 4 7
In [23]: df.x
Out[23]:
0 1
1 2
2 3
3 4
Name: x, dtype: int64
In [24]: type(df.x)
Out[24]:
pandas.core.series.Series
in java 7
public class Main {
public static void main(String[] args) {
byte b = -2;
int i = 0 ;
i = ( b & 0b1111_1111 ) ;
System.err.println(i);
}
}
result : 254
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int n;
System.out.println("Enter number: ");
n = keyboard.nextInt();
int number = calculatefactorial(n);
System.out.println("Factorial: " +number);
}
public static int calculatefactorial(int n){
int factorialnumbers=1;
while(n>0){
factorialnumbers=(int)(factorialnumbers*n--);
}
return factorialnumbers;
}
}
POJO: If the class can be executed with underlying JDK,without any other external third party libraries support then its called POJO
JavaBean: If class only contains attributes with accessors(setters and getters) those are called javabeans.Java beans generally will not contain any bussiness logic rather those are used for holding some data in it.
All Javabeans are POJOs but all POJO are not Javabeans
This works even if the objects are different. you could customize the methods in the utilities class maybe you want to compare private properties as well...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class ObjectA
{
public string PropertyA { get; set; }
public string PropertyB { get; set; }
public string PropertyC { get; set; }
public DateTime PropertyD { get; set; }
public string FieldA;
public DateTime FieldB;
}
class ObjectB
{
public string PropertyA { get; set; }
public string PropertyB { get; set; }
public string PropertyC { get; set; }
public DateTime PropertyD { get; set; }
public string FieldA;
public DateTime FieldB;
}
class Program
{
static void Main(string[] args)
{
// create two objects with same properties
ObjectA a = new ObjectA() { PropertyA = "test", PropertyB = "test2", PropertyC = "test3" };
ObjectB b = new ObjectB() { PropertyA = "test", PropertyB = "test2", PropertyC = "test3" };
// add fields to those objects
a.FieldA = "hello";
b.FieldA = "Something differnt";
if (a.ComparePropertiesTo(b))
{
Console.WriteLine("objects have the same properties");
}
else
{
Console.WriteLine("objects have diferent properties!");
}
if (a.CompareFieldsTo(b))
{
Console.WriteLine("objects have the same Fields");
}
else
{
Console.WriteLine("objects have diferent Fields!");
}
Console.Read();
}
}
public static class Utilities
{
public static bool ComparePropertiesTo(this Object a, Object b)
{
System.Reflection.PropertyInfo[] properties = a.GetType().GetProperties(); // get all the properties of object a
foreach (var property in properties)
{
var propertyName = property.Name;
var aValue = a.GetType().GetProperty(propertyName).GetValue(a, null);
object bValue;
try // try to get the same property from object b. maybe that property does
// not exist!
{
bValue = b.GetType().GetProperty(propertyName).GetValue(b, null);
}
catch
{
return false;
}
if (aValue == null && bValue == null)
continue;
if (aValue == null && bValue != null)
return false;
if (aValue != null && bValue == null)
return false;
// if properties do not match return false
if (aValue.GetHashCode() != bValue.GetHashCode())
{
return false;
}
}
return true;
}
public static bool CompareFieldsTo(this Object a, Object b)
{
System.Reflection.FieldInfo[] fields = a.GetType().GetFields(); // get all the properties of object a
foreach (var field in fields)
{
var fieldName = field.Name;
var aValue = a.GetType().GetField(fieldName).GetValue(a);
object bValue;
try // try to get the same property from object b. maybe that property does
// not exist!
{
bValue = b.GetType().GetField(fieldName).GetValue(b);
}
catch
{
return false;
}
if (aValue == null && bValue == null)
continue;
if (aValue == null && bValue != null)
return false;
if (aValue != null && bValue == null)
return false;
// if properties do not match return false
if (aValue.GetHashCode() != bValue.GetHashCode())
{
return false;
}
}
return true;
}
}
SQLAlchemy's ORM is meant to be used together with the SQL layer, not hide it. But you do have to keep one or two things in mind when using the ORM and plain SQL in the same transaction. Basically, from one side, ORM data modifications will only hit the database when you flush the changes from your session. From the other side, SQL data manipulation statements don't affect the objects that are in your session.
So if you say
for c in session.query(Stuff).all():
c.foo = c.foo+1
session.commit()
it will do what it says, go fetch all the objects from the database, modify all the objects and then when it's time to flush the changes to the database, update the rows one by one.
Instead you should do this:
session.execute(update(stuff_table, values={stuff_table.c.foo: stuff_table.c.foo + 1}))
session.commit()
This will execute as one query as you would expect, and because at least the default session configuration expires all data in the session on commit you don't have any stale data issues.
In the almost-released 0.5 series you could also use this method for updating:
session.query(Stuff).update({Stuff.foo: Stuff.foo + 1})
session.commit()
That will basically run the same SQL statement as the previous snippet, but also select the changed rows and expire any stale data in the session. If you know you aren't using any session data after the update you could also add synchronize_session=False
to the update statement and get rid of that select.
Can be caused by a miss configured SPF record on the senders end.
There are a few characters which can indicate a new line. The usual ones are these two: '\n' or '0x0A' (10 in decimal) -> This character is called "Line Feed" (LF). '\r' or '0x0D' (13 in decimal) -> This one is called "Carriage return" (CR).
Different Operating Systems handle newlines in a different way. Here is a short list of the most common ones:
DOS and Windows
They expect a newline to be the combination of two characters, namely '\r\n' (or 13 followed by 10).
Unix (and hence Linux as well)
Unix uses a single '\n' to indicate a new line.
Mac
Macs use a single '\r'.
This function gets the series names, puts them into an array, sorts the array and based on that defines the plotting order which will give the desired output.
Function Increasing_Legend_Sort(mychart As Chart)
Dim Arr()
ReDim Arr(1 To mychart.FullSeriesCollection.Count)
'Assigning Series names to an array
For i = LBound(Arr) To UBound(Arr)
Arr(i) = mychart.FullSeriesCollection(i).Name
Next i
'Bubble-Sort (Sort the array in increasing order)
For r1 = LBound(Arr) To UBound(Arr)
rval = Arr(r1)
For r2 = LBound(Arr) To UBound(Arr)
If Arr(r2) > rval Then 'Change ">" to "<" to make it decreasing
Arr(r1) = Arr(r2)
Arr(r2) = rval
rval = Arr(r1)
End If
Next r2
Next r1
'Defining the PlotOrder
For i = LBound(Arr) To UBound(Arr)
mychart.FullSeriesCollection(Arr(i)).PlotOrder = i
Next i
End Function
names=[line.strip() for line in open('names.txt')]
only you need to have one parameter in xml file
android:paddingLeft="20dp"
Alternatively, this
def simpleaxis(ax):
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.get_xaxis().tick_bottom()
ax.get_yaxis().tick_left()
seems to achieve the same effect on an axis without losing rotated label support.
(Matplotlib 1.0.1; solution inspired by this).
Your css will only work in IE browser. And the css suggessted by hayk.mart will olny work in webkit browsers. And by using different css hacks you can't style your browsers scroll bars with a same result.
So, it is better to use a jQuery/Javascript plugin to achieve a cross browser solution with a same result.
Solution:
By Using jScrollPane a jQuery plugin, you can achieve a cross browser solution
all of the solution here are great but not necessarily can be implemented for old mysql servers (at least at my case). so you can use sub-queries (i think it is less complicated).
select sum(t1.cnt) from
(SELECT column, COUNT(column) as cnt
FROM
table
GROUP BY
column
HAVING
COUNT(column) > 1) as t1 ;
I wanted to use the top rated answer above
Object.prototype.keys = function () ...
However when using in conjunction with the google maps API v3, google maps is non-functional.
for (var key in h) ...
works well.
Try this MEX file for ACTUALLY calling Python from MATLAB not the other way around as others suggest. It provides fairly decent integration : http://algoholic.eu/matpy/
You can do something like this easily:
[X,Y]=meshgrid(-10:0.1:10,-10:0.1:10);
Z=sin(X)+cos(Y);
py_export('X','Y','Z')
stmt = sprintf(['import matplotlib\n' ...
'matplotlib.use(''Qt4Agg'')\n' ...
'import matplotlib.pyplot as plt\n' ...
'from mpl_toolkits.mplot3d import axes3d\n' ...
'f=plt.figure()\n' ...
'ax=f.gca(projection=''3d'')\n' ...
'cset=ax.plot_surface(X,Y,Z)\n' ...
'ax.clabel(cset,fontsize=9,inline=1)\n' ...
'plt.show()']);
py('eval', stmt);
For clarity, I thought that a direct example of grabbing onto a resource can be shown from the following that I think contributes to the response for this question with a quick direct example.
private MenuItem menuItem_;
@Override
public boolean onCreateOptionsMenu(Menu menuF)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_layout, menuF);
menuItem_ = menuF.findItem(R.id.menu_item_identifier);
return true;
}
In this case you hold onto a MenuItem reference at the beginning and then change the state of it (for icon state changes for example) at a later given point in time.
Cryptographic algorithms generally rely for their security on having a "difficult problem". Most modern algorithms seem to use the factoring of very large numbers as their difficult problem - if you multiply two large numbers together, computing their factors is "difficult" (i.e. time-consuming). If those two numbers are prime numbers, then there is only one answer, which makes it even more difficult, and also guarantees that when you find the answer, it's the right one, not some other answer that just happens to give the same result.
x is the target angle. y is the source or starting angle:
atan2(sin(x-y), cos(x-y))
It returns the signed delta angle. Note that depending on your API the order of the parameters for the atan2() function might be different.
Here is my solution to see if I am using an argparse variable
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("-1", "--first", required=True)
ap.add_argument("-2", "--second", required=True)
ap.add_argument("-3", "--third", required=False)
# Combine all arguments into a list called args
args = vars(ap.parse_args())
if args["third"] is not None:
# do something
This might give more insight to the above answer which I used and adapted to work for my program.
Here are two worthy caveats from the comments.
Either you want user to be of type
User | {}
orPartial<User>
, or you need to redefine theUser
type to allow an empty object. Right now, the compiler is correctly telling you that user is not a User. –jcalz
I don't think this should be considered a proper answer because it creates an inconsistent instance of the type, undermining the whole purpose of TypeScript. In this example, the property
Username
is left undefined, while the type annotation is saying it can't be undefined. –Ian Liu Rodrigues
One of the design goals of TypeScript is to "strike a balance between correctness and productivity." If it will be productive for you to do this, use Type Assertions to create empty objects for typed variables.
type User = {
Username: string;
Email: string;
}
const user01 = {} as User;
const user02 = <User>{};
user01.Email = "[email protected]";
Here is a working example for you.
Performance-Wise this probably might not be the best solution but it works.
var str = "filename:with&bad$separators.txt";
char[] charArray = new char[] { '#', '%', '&', '{', '}', '\\', '<', '>', '*', '?', '/', ' ', '$', '!', '\'', '"', ':', '@' };
foreach (var singleChar in charArray)
{
str = str.Replace(singleChar, '_');
}
The size member function.
myList.size();
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html
The Html.Hidden creates a hidden input but you have to specify the name and all the attributes you want to give that field and value. The Html.HiddenFor
creates a hidden input for the object that you pass to it, they look like this:
Html.Hidden("yourProperty",model.yourProperty);
Html.HiddenFor(m => m.yourProperty)
In this case the output is the same!
Example from the numpy documentation:
>>> a = numpy.array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
>>> numpy.delete(a, numpy.s_[1:3], axis=0) # remove rows 1 and 2
array([[ 0, 1, 2, 3],
[12, 13, 14, 15]])
>>> numpy.delete(a, numpy.s_[1:3], axis=1) # remove columns 1 and 2
array([[ 0, 3],
[ 4, 7],
[ 8, 11],
[12, 15]])
You must add a line with #include <stdlib.h>
to include that header file
and exit
must return a value so assign some integer in exit(any_integer)
.
With intelliJ 16.1.4 I had the same issue. You should have a look at the Event Log, because it told me "Non-managed pom.xml file found:..." I then clicked on it and the problem was solved.
getElementById
returns a reference to the element using its id
. The element is the input
in the first case and the paragraph in the second case.
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById
You need to download the JavaMail API, and put the relevant jar files in your classpath.
I had the same problem and I solved by using the postcast server. You can install it locally and use it.
REPLACE INTO table(column_list) VALUES(value_list);
is a shorter form of
INSERT OR REPLACE INTO table(column_list) VALUES(value_list);
For REPLACE to execute correctly your table structure must have unique rows, whether a simple primary key or a unique index.
REPLACE deletes, then INSERTs the record and will cause an INSERT Trigger to execute if you have them setup. If you have a trigger on INSERT, you may encounter issues.
This is a work around.. not checked the speed..
INSERT OR IGNORE INTO table (column_list) VALUES(value_list);
followed by
UPDATE table SET field=value,field2=value WHERE uniqueid='uniquevalue'
This method allows a replace to occur without causing a trigger.
You can create a stored procedure passing 2 dates
CREATE PROCEDURE SELECTALLDATES
(
@StartDate as date,
@EndDate as date
)
AS
Declare @Current as date = DATEADD(DD, 1, @BeginDate);
Create table #tmpDates
(displayDate date)
WHILE @Current < @EndDate
BEGIN
insert into #tmpDates
VALUES(@Current);
set @Current = DATEADD(DD, 1, @Current) -- add 1 to current day
END
Select *
from #tmpDates
drop table #tmpDates
This would be easier to do with flexbox. Using flexbox will let you not to specify the height of your content and can adjust automatically on the height it contains.
here's the gist of the demo
.container{
display: flex;
height: 100%;
justify-content: center;
align-items: center;
}
html
<div class="container">
<div class='content'> //you can size this anyway you want
put anything you want here,
</div>
</div>
Scroll To Top
- CGPoint topOffset = CGPointMake(0, 0);
- [scrollView setContentOffset:topOffset animated:YES];
Scroll To Bottom
- CGPoint bottomOffset = CGPointMake(0, scrollView.contentSize.height - self.scrollView.bounds.size.height);
- [scrollView setContentOffset:bottomOffset animated:YES];
I'm not sure whether ZohoGorganzola's solution is correct; however, you may want to try getting at the element directly rather than trying to invoke a method on the jQuery collection, so instead of
$("#videoContainer").pause();
try
$("#videoContainer")[0].pause();
I wanted to post something a bit different then some of the other answers. Even though this is most likely not the most understandable, or fastest option, it provides a bit of an inside view of how deep copy works, as well as being another alternative option for deep copying. It doesn't really matter if my function has bugs, since the point of this is to show a way to copy objects like the question answers, but also to use this as a point to explain how deepcopy works at its core.
At the core of any deep copy function is way to make a shallow copy. How? Simple. Any deep copy function only duplicates the containers of immutable objects. When you deepcopy a nested list, you are only duplicating the outer lists, not the mutable objects inside of the lists. You are only duplicating the containers. The same works for classes, too. When you deepcopy a class, you deepcopy all of its mutable attributes. So, how? How come you only have to copy the containers, like lists, dicts, tuples, iters, classes, and class instances?
It's simple. A mutable object can't really be duplicated. It can never be changed, so it is only a single value. That means you never have to duplicate strings, numbers, bools, or any of those. But how would you duplicate the containers? Simple. You make just initialize a new container with all of the values. Deepcopy relies on recursion. It duplicates all the containers, even ones with containers inside of them, until no containers are left. A container is an immutable object.
Once you know that, completely duplicating an object without any references is pretty easy. Here's a function for deepcopying basic data-types (wouldn't work for custom classes but you could always add that)
def deepcopy(x):
immutables = (str, int, bool, float)
mutables = (list, dict, tuple)
if isinstance(x, immutables):
return x
elif isinstance(x, mutables):
if isinstance(x, tuple):
return tuple(deepcopy(list(x)))
elif isinstance(x, list):
return [deepcopy(y) for y in x]
elif isinstance(x, dict):
values = [deepcopy(y) for y in list(x.values())]
keys = list(x.keys())
return dict(zip(keys, values))
Python's own built-in deepcopy is based around that example. The only difference is it supports other types, and also supports user-classes by duplicating the attributes into a new duplicate class, and also blocks infinite-recursion with a reference to an object it's already seen using a memo list or dictionary. And that's really it for making deep copies. At its core, making a deep copy is just making shallow copies. I hope this answer adds something to the question.
EXAMPLES
Say you have this list: [1, 2, 3]. The immutable numbers cannot be duplicated, but the other layer can. You can duplicate it using a list comprehension: [x for x in [1, 2, 3]
Now, imagine you have this list: [[1, 2], [3, 4], [5, 6]]. This time, you want to make a function, which uses recursion to deep copy all layers of the list. Instead of the previous list comprehension:
[x for x in _list]
It uses a new one for lists:
[deepcopy_list(x) for x in _list]
And deepcopy_list looks like this:
def deepcopy_list(x):
if isinstance(x, (str, bool, float, int)):
return x
else:
return [deepcopy_list(y) for y in x]
Then now you have a function which can deepcopy any list of strs, bools, floast, ints and even lists to infinitely many layers using recursion. And there you have it, deepcopying.
TLDR: Deepcopy uses recursion to duplicate objects, and merely returns the same immutable objects as before, as immutable objects cannot be duplicated. However, it deepcopies the most inner layers of mutable objects until it reaches the outermost mutable layer of an object.
You really should try to use screen
. It is a bit more complicated than just doing nohup long_running &
, but understanding screen once you never come back again.
Start your screen session at first:
user@host:~$ screen
Run anything you want:
wget http://mirror.yandex.ru/centos/4.6/isos/i386/CentOS-4.6-i386-binDVD.iso
Press ctrl+A and then d. Done. Your session keeps going on in background.
You can list all sessions by screen -ls
, and attach to some by screen -r 20673.pts-0.srv
command, where 0673.pts-0.srv is an entry list.
You are making sense, but you seem to misunderstand the concept of sending emails.
HTML is parsed on the client side, while the e-mail needs to be sent from the server. You cannot do it in pure HTML. I would suggest writing a PHP script that will deal with the email sending for you.
Basically, instead of the MAILTO, your form's action will need to point to that PHP script. In the script, retrieve the values passed by the form (in PHP, they are available through the $_POST
superglobal) and use the email sending function (mail()
).
Of course, this can be done in other server-side languages as well. I'm giving a PHP solution because PHP is the language I work with.
A simple example code:
form.html:
<form method="post" action="email.php">
<input type="text" name="subject" /><br />
<textarea name="message"></textarea>
</form>
email.php:
<?php
mail('[email protected]', $_POST['subject'], $_POST['message']);
?>
<p>Your email has been sent.</p>
Of course, the script should contain some safety measures, such as checking whether the $_POST valies are at all available, as well as additional email headers (sender's email, for instance), perhaps a way to deal with character encoding - but that's too complex for a quick example ;).
It is actually possible.
See: CSS Tip: How to Make Circles Without Images. See demo.
But be warned, It has serious disadvantages in terms of compatibility basically, you are making a cat bark.
See it working here
As you will see you just have to set up the height
and width
to half the border-radius
Good luck!
textBox1.Enabled = false;
"false" property will make the text box disable. and "true" will make it in regular form. Thanks.
I am using DBLINK to connect internal database for cross database queries.
Reference taken from this article.
Install DbLink extension.
CREATE EXTENSION dblink;
Verify DbLink:
SELECT pg_namespace.nspname, pg_proc.proname
FROM pg_proc, pg_namespace
WHERE pg_proc.pronamespace=pg_namespace.oid
AND pg_proc.proname LIKE '%dblink%';
Test connection of database:
SELECT dblink_connect('host=localhost user=postgres password=enjoy dbname=postgres');
Extract the package to C:\ from here and install it
Copy the path C:\MinGW\bin
which contains gcc.exe.
go to Control Panel->System->Advanced>Environment variables
, and add or modify PATH. (just concatenate with ';')
Then, open a cmd.exe command prompt
(Windows + R and type cmd, if already opened, please close and open a new one, to get the path change)
change the folder to your file path by cd D:\c code Path
type gcc main.c -o helloworld.o
. It will compile the code. for C++ use g++
7 type ./helloworld
to run the program.
If zlib1.dll is missing, download from here
I have been using the latter for a lot of nice lightweight animations. You can use it crossfade two views, or fade one in in front of another, or fade it out. You can shoot a view over another like a banner, you can make a view stretch or shrink... I'm getting a lot of mileage out of beginAnimation
/commitAnimations
.
Don't think that all you can do is:
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:myview cache:YES];
Here is a sample:
[UIView beginAnimations:nil context:NULL]; {
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:1.0];
[UIView setAnimationDelegate:self];
if (movingViewIn) {
// after the animation is over, call afterAnimationProceedWithGame
// to start the game
[UIView setAnimationDidStopSelector:@selector(afterAnimationProceedWithGame)];
// [UIView setAnimationRepeatCount:5.0]; // don't forget you can repeat an animation
// [UIView setAnimationDelay:0.50];
// [UIView setAnimationRepeatAutoreverses:YES];
gameView.alpha = 1.0;
topGameView.alpha = 1.0;
viewrect1.origin.y = selfrect.size.height - (viewrect1.size.height);
viewrect2.origin.y = -20;
topGameView.alpha = 1.0;
}
else {
// call putBackStatusBar after animation to restore the state after this animation
[UIView setAnimationDidStopSelector:@selector(putBackStatusBar)];
gameView.alpha = 0.0;
topGameView.alpha = 0.0;
}
[gameView setFrame:viewrect1];
[topGameView setFrame:viewrect2];
} [UIView commitAnimations];
As you can see, you can play with alpha, frames, and even sizes of a view. Play around. You may be surprised with its capabilities.
As far as the compiler is concerned, those two methods are identical. There will be one implementation of both.
This isn't a problem if the two methods are effectively identical, in that they should have the same implementation. If they are contractually different (as per the documentation for each interface), you'll be in trouble.
the source to the ssl version of this is here: http://atmospherian.wordpress.com/downloads/
Simplifying from pctroll's answer, similarly based on this blog post.
# look up the commit id in git log or on github, e.g. 42480f3, then do
git checkout master
git checkout your_branch
git revert 42480f3
# a text editor will open, close it with ctrl+x (editor dependent)
git push origin your_branch
# or replace origin with your remote
On Mac OS - Installing tensorflow 1.3 - it will automatically remove other protobuf installs and install protobuf 3.4. However, this does not work and neither does installing or downgrading to any other protobuf version.
However I found a solution. Not sure why this works - but on Mac OS this solved it.
pip install google
Search for a null value by using \00
For example:
ldapsearch -D cn=admin -w pass -s sub -b ou=users,dc=acme 'manager=\00' uid manager
Make sure if you use the null value on the command line to use quotes around it to prevent the OS shell from sending a null character to LDAP. For example, this won't work:
ldapsearch -D cn=admin -w pass -s sub -b ou=users,dc=acme manager=\00 uid manager
There are various sites that reference this, along with other special characters. Example:
The accepted answer still threw a Javascript error in IE for me (for Angular 1.2 at least). It is a bug but the workaround is to use ngAttr detailed on https://docs.angularjs.org/guide/interpolation
<input type="text" ng-model="inputText" ng-attr-placeholder="{{somePlaceholder}}" />
As others have said, @Transient
is used to mark fields which shouldn't be persisted. Consider this short example:
public enum Gender { MALE, FEMALE, UNKNOWN }
@Entity
public Person {
private Gender g;
private long id;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public long getId() { return id; }
public void setId(long id) { this.id = id; }
public Gender getGender() { return g; }
public void setGender(Gender g) { this.g = g; }
@Transient
public boolean isMale() {
return Gender.MALE.equals(g);
}
@Transient
public boolean isFemale() {
return Gender.FEMALE.equals(g);
}
}
When this class is fed to the JPA, it persists the gender
and id
but doesn't try to persist the helper boolean methods - without @Transient
the underlying system would complain that the Entity class Person
is missing setMale()
and setFemale()
methods and thus wouldn't persist Person
at all.
If you haven't pushed your changes yet use git reset --soft [Hash for one commit]
to rollback to a specific commit. --soft
tells git to keep the changes being rolled back (i.e., mark the files as modified). --hard
tells git to delete the changes being rolled back.
You may use CString
, CStringA
, CStringW
to do automatic conversions and convert between these types. Further, you may also use CStrBuf
, CStrBufA
, CStrBufW
to get RAII pattern modifiable strings
Use jquery.csrf (https://github.com/swordray/jquery.csrf).
Rails 5.1 or later
$ yarn add jquery.csrf
//= require jquery.csrf
Rails 5.0 or before
source 'https://rails-assets.org' do
gem 'rails-assets-jquery.csrf'
end
//= require jquery.csrf
Source code
(function($) {
$(document).ajaxSend(function(e, xhr, options) {
var token = $('meta[name="csrf-token"]').attr('content');
if (token) xhr.setRequestHeader('X-CSRF-Token', token);
});
})(jQuery);
Check if the Node
is a Dom Element
, cast, and call getElementsByTagName()
Node doc = docs.item(i);
if(doc instanceof Element) {
Element docElement = (Element)doc;
...
cell = doc.getElementsByTagName("aoo").item(0);
}
A few months ago I had the same problem and every library I found provides too much functionality and complexity for my final goal. So I end up developing my own library - HtmlFlow - that provides a very simple and intuitive API that allows me to write HTML in a fluent style. Check it here: https://github.com/fmcarvalho/HtmlFlow (it also supports dynamic binding to HTML elements)
Here is an example of binding the properties of a Task
object into HTML elements. Consider a Task
Java class with three properties: Title
, Description
and a Priority
and then we can produce an HTML document for a Task
object in the following way:
import htmlflow.HtmlView;
import model.Priority;
import model.Task;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
public class App {
private static HtmlView<Task> taskDetailsView(){
HtmlView<Task> taskView = new HtmlView<>();
taskView
.head()
.title("Task Details")
.linkCss("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css");
taskView
.body().classAttr("container")
.heading(1, "Task Details")
.hr()
.div()
.text("Title: ").text(Task::getTitle)
.br()
.text("Description: ").text(Task::getDescription)
.br()
.text("Priority: ").text(Task::getPriority);
return taskView;
}
public static void main(String [] args) throws IOException{
HtmlView<Task> taskView = taskDetailsView();
Task task = new Task("Special dinner", "Have dinner with someone!", Priority.Normal);
try(PrintStream out = new PrintStream(new FileOutputStream("Task.html"))){
taskView.setPrintStream(out).write(task);
Desktop.getDesktop().browse(URI.create("Task.html"));
}
}
}
Well you already give the answer yourself; you have to wait for the creation of the file to finish. One way to do this is via checking if the file is still in use. An example of this can be found here: Is there a way to check if a file is in use?
Note that you will have to modify this code for it to work in your situation. You might want to have something like (pseudocode):
public static void listener_Created()
{
while CheckFileInUse()
wait 1000 milliseconds
CopyFile()
}
Obviously you should protect yourself from an infinite while
just in case the owner application never releases the lock. Also, it might be worth checking out the other events from FileSystemWatcher
you can subscribe to. There might be an event which you can use to circumvent this whole problem.
Use FormulaR1C1:
Cells((1,3),(10,3)).FormulaR1C1 = "=RC[-2]+RC[-1]"
Unlike Formula, FormulaR1C1 has relative referencing.
I know this answer is ridiculous, but consider just disabling this rule until the bugs are worked out or you've upgraded your tooling:
/* eslint-disable react/prop-types */ // TODO: upgrade to latest eslint tooling
Or disable project-wide in your eslintrc:
"rules": {
"react/prop-types": "off"
}
I have checked on Windows: Ctrl + F11 and Ctrl + F12 both are working to change the orientation of the Android simulator.
For other shortcut keys:
In the Eclipse toolbar go to "Help-->key Assist.. "
You can also use Ctrl + Shift + L here, so many shortcut keys of Eclipse are given.
You may also be interested in the write-up from Sun, as part of the standard JSSE documentation:
http://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#Stores
Typically, the trust store is used to store only public keys, for verification purposes, such as with X.509 authentication. For manageability purposes, it's quite common for admins or developers to simply conflate the two into a single store.
If you need a lot of decimal numbers, in this example 17, I share with you MySql code:
This is the calculate:
=(9/1147)*100
SELECT TRUNCATE(((CAST(9 AS DECIMAL(30,20))/1147)*100),17);
The Answer by Bhesh Gurung is correct… unless your NetBeans project is Maven based.
Under Maven, you add a "dependency". A dependency is a description of a library (its name & version number) you want to use from your code.
Or a dependency could be a description of a library which another library needs ("depends on"). Maven automatically handles this chain, libraries that need other libraries that then need other libraries and so on. For the mathematical-minded, perhaps the phrase "Maven resolves the transitive dependencies" makes sense.
Maven gets this related-ness information, and the libraries themselves from a Maven repository. A repository is basically an online database and collection of download files (the dependency library).
Adding a dependency to a Maven-based project is really quite easy. That is the whole point to Maven, to make managing dependent libraries easy and to make building them into your project easy. To get started with adding a dependency, see this Question, Adding dependencies in Maven Netbeans and my Answer with screenshot.
It's a design pattern and it's not specific to c#. More about it all over the internet and SO, like on this wikipedia article.
In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects (say, five). Some consider it an anti-pattern, judging that it is overused, introduces unnecessary limitations in situations where a sole instance of a class is not actually required, and introduces global state into an application.
You should use it if you want a class that can only be instanciated once.
You can use r libraries for 3 D plotting.
Steps are:
First create a data frame using data.frame() command.
Create a 3D plot by using scatterplot3D library.
Or You can also rotate your chart using rgl library by plot3d() command.
Alternately you can use plot3d() command from rcmdr library.
In MATLAB, you can use surf(), mesh() or surfl() command as per your requirement.
[http://in.mathworks.com/help/matlab/examples/creating-3-d-plots.html]
New Note: You probably don't want or need to do this. What you probably want to do is just put those types of command dependencies for build/test etc. in the devDependencies
section of your package.json. Anytime you use something from scripts
in package.json your devDependencies commands (in node_modules/.bin) act as if they are in your path.
For example:
npm i --save-dev mocha # Install test runner locally
npm i --save-dev babel # Install current babel locally
Then in package.json:
// devDependencies has mocha and babel now
"scripts": {
"test": "mocha",
"build": "babel -d lib src",
"prepublish": "babel -d lib src"
}
Then at your command prompt you can run:
npm run build # finds babel
npm test # finds mocha
npm publish # will run babel first
But if you really want to install globally, you can add a preinstall in the scripts section of the package.json:
"scripts": {
"preinstall": "npm i -g themodule"
}
So actually my npm install executes npm install again .. which is weird but seems to work.
Note: you might have issues if you are using the most common setup for npm
where global Node package installs required sudo
. One option is to change your npm
configuration so this isn't necessary:
npm config set prefix ~/npm
, add $HOME/npm/bin to $PATH by appending export PATH=$HOME/npm/bin:$PATH
to your ~/.bashrc
.
If you are trying to loop over a NodeList
like this:
const allParagraphs = document.querySelectorAll("p");
I highly recommend loop it this way:
Array.prototype.forEach.call(allParagraphs , function(el) {
// Write your code here
})
Personally, I've tried several ways but most of them didn't work as I wanted to loop over a NodeList
, but this one works like a charm, give it a try!
The NodeList
isn't an Array, but we treat it as an Array, using Array.
So, you need to know that it is not supported in older browsers!
Need more information about NodeList
? Please read its documentation on MDN.
Use the which function:
A <- c('a','a','b','b','b')
B <- c(1,0,1,1,0)
d <- data.frame(A, B)
r <- with(d, which(B==0, arr.ind=TRUE))
newd <- d[-r, ]
You've nearly got it. The problem is that the Class Under Test (CUT) is not built for unit testing - it has not really been TDD'd.
Think of it like this…
In the unit test
@Spy
on it@Mock
all of the other class/service/database (i.e. external dependencies) In order to avoid executing code that you are not strictly testing, you could abstract that code away into something that can be @Mock
ed.
In this very simple example, a function that creates an object will be difficult to test
public void doSomethingCool(String foo) {
MyObject obj = new MyObject(foo);
// can't do much with obj in a unit test unless it is returned
}
But a function that uses a service to get MyObject is easy to test, as we have abstracted the difficult/impossible to test code into something that makes this method testable.
public void doSomethingCool(String foo) {
MyObject obj = MyObjectService.getMeAnObject(foo);
}
as MyObjectService can be mocked and also verified that .getMeAnObject() is called with the foo variable.
If you have the liberty to configure your webserver yourself, tools like mod_xsendfile (for Apache) are considerably better than reading and printing the file in PHP. Your PHP code would look like this:
header("Content-type: $type");
header("X-Sendfile: $file"); # make sure $file is the full path, not relative
exit();
mod_xsendfile picks up the X-Sendfile header and sends the file to the browser itself. This can make a real difference in performance, especially for big files. Most of the proposed solutions read the whole file into memory and then print it out. That's OK for a 20kbyte image file, but if you have a 200 MByte TIFF file, you're bound to get problems.
I just wanted something really basic to move some files out of the main folder, like user2889485's reply, but his specific answer didnt work for me. I didnt care if they were in the same package or not.
My GOPATH workspace is c:\work\go
and under that I have
/src/pg/main.go (package main)
/src/pg/dbtypes.go (pakage dbtypes)
in main.go
I import "/pg/dbtypes"
I used jQuery AutoSize. When I tried using Elastic it frequently gave me bogus heights (really tall textarea's). jQuery AutoSize has worked well and hasn't had this issue.
sourceString.Replace(removeString, "");
It is not possible to assign values to an array all at once after initialization. The best alternative would be to use a loop.
for(i=0;i<N;i++)
{
array[i] = i;
}
You can hard code and assign values like --array[0] = 1
and so on.
Memcpy can also be used if you have the data stored in an array already.
I want to share something that blocked us for a couple of days: the fileprovider code MUST be inserted between the application tags, not after it. It may be trivial, but it's never specified, and I thought that I could have helped someone! (thanks again to piolo94)
Display property 'inline-block' will place both headers next to each other. You can run this code snippet to see it
<h1 style="display: inline-block" >Text 1</h1>
<h1 style="display: inline-block" >Text 2</h1>
_x000D_
If you want to see what you haven't git add
ed yet:
git diff myfile.txt
or if you want to see already added changes
git diff --cached myfile.txt
This can be done with lodash _.tail
and _.dropRight
:
var fruits = ["Banana", "Orange", "Apple", "Mango"];_x000D_
console.log(_.dropRight(_.tail(fruits)));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
I hate foo and bar .. who dreamed up these non descriptive terms in programming anyway?
my $oldstring = "replace donotreplace replace donotreplace replace donotreplace";
my $newstring = $oldstring;
$newstring =~ s/replace/newword/g; # inplace replacement
print $newstring;
%: newword donotreplace newword donotreplace newword donotreplace
If you have a flash FLA file that shows the FLV movie you can add a button inside the FLA file. This button can be given an action to load the URL.
on (release) {
getURL("http://someurl/");
}
To make the button transparent you can place a square inside it that is moved to the hit-area frame of the button.
I think it would go too far to explain into depth with pictures how to go about in stackoverflow.
First off it's important to understand that there are two kinds of "event listeners":
Scope event listeners registered via $on
:
$scope.$on('anEvent', function (event, data) {
...
});
Event handlers attached to elements via for example on
or bind
:
element.on('click', function (event) {
...
});
When $scope.$destroy()
is executed it will remove all listeners registered via $on
on that $scope.
It will not remove DOM elements or any attached event handlers of the second kind.
This means that calling $scope.$destroy()
manually from example within a directive's link function will not remove a handler attached via for example element.on
, nor the DOM element itself.
Note that remove
is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.
When element.remove()
is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on
.
It will not destroy the $scope associated with the element.
To make it more confusing there is also a jQuery event called $destroy
. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:
element.on('$destroy', function () {
scope.$destroy();
});
This depends on how the directive is "destroyed".
A normal case is that a directive is destroyed because ng-view
changes the current view. When this happens the ng-view
directive will destroy the associated $scope, sever all the references to its parent scope and call remove()
on the element.
This means that if that view contains a directive with this in its link function when it's destroyed by ng-view
:
scope.$on('anEvent', function () {
...
});
element.on('click', function () {
...
});
Both event listeners will be removed automatically.
However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references
.
Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.
For example if you have registered a listener on $rootScope
:
var unregisterFn = $rootScope.$on('anEvent', function () {});
scope.$on('$destroy', unregisterFn);
This is needed since $rootScope
is never destroyed during the lifetime of the application.
The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.
Another situation would be to cancel $interval
/$timeout
:
var promise = $interval(function () {}, 1000);
scope.$on('$destroy', function () {
$interval.cancel(promise);
});
If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:
var windowClick = function () {
...
};
angular.element(window).on('click', windowClick);
scope.$on('$destroy', function () {
angular.element(window).off('click', windowClick);
});
These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view
or ng-if
.
If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.
$('#thedate,#dateid').datepicker({
changeMonth:true,
changeYear:true,
yearRange:"-100:+0",
dateFormat:"dd/mm/yy" ,
maxDate: '0',
});
});
Use elevation to implement shadows on RN Android. Added elevation prop #27
<View elevation={5}>
</View>
file_path = "/path/to/yourfile.txt"
with open(file_path, 'a') as file:
file.write("This will be added to the next line\n")
or
log_file = open('log.txt', 'a')
log_file.write("This will be added to the next line\n")
This is what worked for me:
In the build.gradle
file, setting the minSdkVersion
under defaultConfig
:
Good Luck...
you can parse string with int.parse('your string value');
.
Example:- int num = int.parse('110011'); print(num); // prints 110011 ;
you can do that by simple way, simply change the variable value that used in for loop to the end value as shown in example
Sub TEST_ONLY()
For i = 1 To 10
ActiveSheet.Cells(i, 1).Value = i
If i = 5 Then
i = 10
End If
Next i
End Sub
_x000D_
The real answer is no (at least not by itself). You can still write your own code to do it.
You can access afterRender
hook by using plugins
.
And here are all the plugin api available.
In html file:
<html>
<canvas id="myChart"></canvas>
<div id="imgWrap"></div>
</html>
In js file:
var chart = new Chart(ctx, {
...,
plugins: [{
afterRender: function () {
// Do anything you want
renderIntoImage()
},
}],
...,
});
const renderIntoImage = () => {
const canvas = document.getElementById('myChart')
const imgWrap = document.getElementById('imgWrap')
var img = new Image();
img.src = canvas.toDataURL()
imgWrap.appendChild(img)
canvas.style.display = 'none'
}
outfile = open( 'dict.txt', 'w' )
for key, value in sorted( mydict.items() ):
outfile.write( str(key) + '\t' + str(value) + '\n' )
Typescript is (a superset of) javascript, so you just use JSON.parse
as you would in javascript:
let obj = JSON.parse(jsonString);
Only that in typescript you can have a type to the resulting object:
interface MyObj {
myString: string;
myNumber: number;
}
let obj: MyObj = JSON.parse('{ "myString": "string", "myNumber": 4 }');
console.log(obj.myString);
console.log(obj.myNumber);
If anyone wanted nates' solution but in swift, then here is a rough swift translation:
class SomeClass: UIViewController {
var animating : Bool = false
@IBOutlet weak var activityIndicatorImage: UIImageView!
func startSpinning() {
if(!animating) {
animating = true;
spinWithOptions(UIViewAnimationOptions.CurveEaseIn);
}
}
func stopSpinning() {
animating = false
}
func spinWithOptions(options: UIViewAnimationOptions) {
UIView.animateWithDuration(0.5, delay: 0.0, options: options, animations: { () -> Void in
let val : CGFloat = CGFloat((M_PI / Double(2.0)));
self.activityIndicatorImage.transform = CGAffineTransformRotate(self.activityIndicatorImage.transform,val)
}) { (finished: Bool) -> Void in
if(finished) {
if(self.animating){
self.spinWithOptions(UIViewAnimationOptions.CurveLinear)
} else if (options != UIViewAnimationOptions.CurveEaseOut) {
self.spinWithOptions(UIViewAnimationOptions.CurveEaseOut)
}
}
}
}
override func viewDidLoad() {
startSpinning()
}
}
I ran into this same issue, but I think I know what's causing the confusion. If you use MySql Query Analyzer, you can do this just fine:
SELECT myvalue
INTO @myvar
FROM mytable
WHERE anothervalue = 1;
However, if you put that same query in MySql Workbench, it will throw a syntax error. I don't know why they would be different, but they are. To work around the problem in MySql Workbench, you can rewrite the query like this:
SELECT @myvar:=myvalue
FROM mytable
WHERE anothervalue = 1;
I am using intellij CE to create the WAR, and deploying the war externally using tomcat deployment manager. This works for testing the application however I still couldnt find the way to debug it.
var now = new Date();
now.format("dd/MM/yyyy hh:mm TT");
Get full details here: Flagrant Badassery » JavaScript Date Format
Incase someone is still trying to figure this out. This is how you get the center X and Y of the view
.
int pos[] = new int[2];
view.getLocationOnScreen(pos);
int centerX = pos[0] + view.getMeasuredWidth() / 2;
int centerY = pos[1] + view.getMeasuredHeight() / 2;
on arch linux. (im not sure on other distros) you can view the operstate. which shows up if connected or down if not the operstate lives on
/sys/class/net/(interface name here)/operstate
#you can also put watch
watch -d -n -1 /sys/class/net/(interface name here)/operstate
I had this, I added EXIT
and initially it didn't work, I guess per requiring the called program exiting
advice mentioned in another response here, however it now works without further ado - not sure what's caused this, but the point to note is that I'm calling a data file .html
rather than the program that handles it browser.exe
, I did not edit anything else but suffice it to say it's much neater just using a bat file to access the main access pages of those web documents and only having title.bat
, contents.bat
, index.bat
in the root folder with the rest of the content in a subfolder.
i.e.: contents.bat reads
cd subfolder
"contents.html"
exit
It also looks better if I change the bat file icons for just those items to suit the context they are in too, but that's another matter, hiding the bat files in the subfolder and creating custom icon shortcuts to them in the root folder with the images called for the customisation also hidden.
The Selenium
client bindings will try to locate the geckodriver
executable from the system PATH
. You will need to add the directory containing the executable to the system path.
On Unix systems you can do the following to append it to your system’s search path, if you’re using a bash-compatible shell:
export PATH=$PATH:/path/to/geckodriver
On Windows you need to update the Path system variable to add the full directory path to the executable. The principle is the same as on Unix.
All below configuration for launching latest firefox using any programming language binding is applicable for Selenium2
to enable Marionette explicitly. With Selenium 3.0 and later, you shouldn't need to do anything to use Marionette, as it's enabled by default.
To use Marionette in your tests you will need to update your desired capabilities to use it.
Java :
As exception is clearly saying you need to download latest geckodriver.exe
from here and set downloaded geckodriver.exe
path where it's exists in your computer as system property with with variable webdriver.gecko.driver
before initiating marionette driver and launching firefox as below :-
//if you didn't update the Path system variable to add the full directory path to the executable as above mentioned then doing this directly through code
System.setProperty("webdriver.gecko.driver", "path/to/geckodriver.exe");
//Now you can Initialize marionette driver to launch firefox
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
WebDriver driver = new MarionetteDriver(capabilities);
And for Selenium3
use as :-
WebDriver driver = new FirefoxDriver();
If you're still in trouble follow this link as well which would help you to solving your problem
.NET :
var driver = new FirefoxDriver(new FirefoxOptions());
Python :
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
caps = DesiredCapabilities.FIREFOX
# Tell the Python bindings to use Marionette.
# This will not be necessary in the future,
# when Selenium will auto-detect what remote end
# it is talking to.
caps["marionette"] = True
# Path to Firefox DevEdition or Nightly.
# Firefox 47 (stable) is currently not supported,
# and may give you a suboptimal experience.
#
# On Mac OS you must point to the binary executable
# inside the application package, such as
# /Applications/FirefoxNightly.app/Contents/MacOS/firefox-bin
caps["binary"] = "/usr/bin/firefox"
driver = webdriver.Firefox(capabilities=caps)
Ruby :
# Selenium 3 uses Marionette by default when firefox is specified
# Set Marionette in Selenium 2 by directly passing marionette: true
# You might need to specify an alternate path for the desired version of Firefox
Selenium::WebDriver::Firefox::Binary.path = "/path/to/firefox"
driver = Selenium::WebDriver.for :firefox, marionette: true
JavaScript (Node.js) :
const webdriver = require('selenium-webdriver');
const Capabilities = require('selenium-webdriver/lib/capabilities').Capabilities;
var capabilities = Capabilities.firefox();
// Tell the Node.js bindings to use Marionette.
// This will not be necessary in the future,
// when Selenium will auto-detect what remote end
// it is talking to.
capabilities.set('marionette', true);
var driver = new webdriver.Builder().withCapabilities(capabilities).build();
Using RemoteWebDriver
If you want to use RemoteWebDriver
in any language, this will allow you to use Marionette
in Selenium
Grid.
Python:
caps = DesiredCapabilities.FIREFOX
# Tell the Python bindings to use Marionette.
# This will not be necessary in the future,
# when Selenium will auto-detect what remote end
# it is talking to.
caps["marionette"] = True
driver = webdriver.Firefox(capabilities=caps)
Ruby :
# Selenium 3 uses Marionette by default when firefox is specified
# Set Marionette in Selenium 2 by using the Capabilities class
# You might need to specify an alternate path for the desired version of Firefox
caps = Selenium::WebDriver::Remote::Capabilities.firefox marionette: true, firefox_binary: "/path/to/firefox"
driver = Selenium::WebDriver.for :remote, desired_capabilities: caps
Java :
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
// Tell the Java bindings to use Marionette.
// This will not be necessary in the future,
// when Selenium will auto-detect what remote end
// it is talking to.
capabilities.setCapability("marionette", true);
WebDriver driver = new RemoteWebDriver(capabilities);
.NET
DesiredCapabilities capabilities = DesiredCapabilities.Firefox();
// Tell the .NET bindings to use Marionette.
// This will not be necessary in the future,
// when Selenium will auto-detect what remote end
// it is talking to.
capabilities.SetCapability("marionette", true);
var driver = new RemoteWebDriver(capabilities);
Note : Just like the other drivers available to Selenium from other browser vendors, Mozilla has released now an executable that will run alongside the browser. Follow this for more details.
You can download latest geckodriver executable to support latest firefox from here
In Build: v22.6.2-1085508 ADT you need to add(select Android 4.4.2)
Goto project --> properties --> Android(This is second in listed item order leftPanel) and in the RightPanel Project Build Target, select Android 4.4.2 as Target name and apply changes It will rebuild the workspace.
In my case unable to resolve target 'android-17' eclipse was being shown as compile error and in code: import java.util.HashMap was not being referenced.
My problem was similar but I overcame me without keeping the fragment alive. Suppose you have an activity that has 2 fragments - F1 and F2. F1 is started initially and lets say in contains some user info and then upon some condition F2 pops on asking user to fill in additional attribute - their phone number. Next, you want that phone number to pop back to F1 and complete signup but you realize all previous user info is lost and you don't have their previous data. The fragment is recreated from scratch and even if you saved this information in onSaveInstanceState
the bundle comes back null in onActivityCreated
.
Solution: Save required information as an instance variable in calling activity. Then pass that instance variable into your fragment.
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle args = getArguments();
// this will be null the first time F1 is created.
// it will be populated once you replace fragment and provide bundle data
if (args != null) {
if (args.get("your_info") != null) {
// do what you want with restored information
}
}
}
So following on with my example: before I display F2 I save user data in the instance variable using a callback. Then I start F2, user fills in phone number and presses save. I use another callback in activity, collect this information and replace my fragment F1, this time it has bundle data that I can use.
@Override
public void onPhoneAdded(String phone) {
//replace fragment
F1 f1 = new F1 ();
Bundle args = new Bundle();
yourInfo.setPhone(phone);
args.putSerializable("you_info", yourInfo);
f1.setArguments(args);
getFragmentManager().beginTransaction()
.replace(R.id.fragmentContainer, f1).addToBackStack(null).commit();
}
}
More information about callbacks can be found here: https://developer.android.com/training/basics/fragments/communicating.html
You can also create a small VBScript script:
Set env = CreateObject("WScript.Shell").Environment("System")
If env(WScript.Arguments(0)) <> vbNullString Then env.Remove WScript.Arguments(0)
Then call it like %windir%\System32\cscript.exe //Nologo "script_name.vbs" FOOBAR
.
The disadvantage is you need an extra script, but it does not require a reboot.
You can also try -j%NUMBER_OF_PROCESSORS% as an argument it will use all your cores. Makes things super fast on my quad core.
public static bool IsPositive<T>(T value)
where T : struct, IComparable<T>
{
return value.CompareTo(default(T)) > 0;
}
Surprisingly, no one mentioned this alternative that uses only built-in bash commands:
i="$IFS";IFS='/';set -f;p=($PWD);set +f;IFS="$i";echo "${p[-1]}"
As an added bonus you can easily obtain the name of the parent directory with:
[ "${#p[@]}" -gt 1 ] && echo "${p[-2]}"
These will work on Bash 4.3-alpha or newer.
String longString = new String(""+long);
or
String longString = new Long(datelong).toString();
First, you should download the suitable version for your system from here: https://pecl.php.net/package/mcrypt/1.0.3/windows
Then, you should copy php_mcrypt.dll
to ../xampp/php/ext/
and enable the extension by adding extension=mcrypt
to your xampp/php/php.ini
file.
It looks to me like the background images aren't actually background images...the site has the background images and the quotes in sibling divs with the children of the div containing the images having been assigned position: fixed; The quotes div is also given a transparent background.
wrapper div{
image wrapper div{
div for individual image{ <--- Fixed position
image <--- relative position
}
}
quote wrapper div{
div for individual quote{
quote
}
}
}
if Condition then command1 : else command2...
Another reason of the above error is corrupted jar file. I got the same error but for Junit when running unit tests. Removing jar and downloading it again fixed the issue.
const messages = document.getElementById('messages');_x000D_
_x000D_
function appendMessage() {_x000D_
const message = document.getElementsByClassName('message')[0];_x000D_
const newMessage = message.cloneNode(true);_x000D_
messages.appendChild(newMessage);_x000D_
}_x000D_
_x000D_
function getMessages() {_x000D_
// Prior to getting your messages._x000D_
shouldScroll = messages.scrollTop + messages.clientHeight === messages.scrollHeight;_x000D_
/*_x000D_
* Get your messages, we'll just simulate it by appending a new one syncronously._x000D_
*/_x000D_
appendMessage();_x000D_
// After getting your messages._x000D_
if (!shouldScroll) {_x000D_
scrollToBottom();_x000D_
}_x000D_
}_x000D_
_x000D_
function scrollToBottom() {_x000D_
messages.scrollTop = messages.scrollHeight;_x000D_
}_x000D_
_x000D_
scrollToBottom();_x000D_
_x000D_
setInterval(getMessages, 100);
_x000D_
#messages {_x000D_
height: 200px;_x000D_
overflow-y: auto;_x000D_
}
_x000D_
<div id="messages">_x000D_
<div class="message">_x000D_
Hello world_x000D_
</div>_x000D_
</div>
_x000D_
As Greg Hewgill said, the typedef means you no longer have to write struct
all over the place. That not only saves keystrokes, it also can make the code cleaner since it provides a smidgen more abstraction.
Stuff like
typedef struct {
int x, y;
} Point;
Point point_new(int x, int y)
{
Point a;
a.x = x;
a.y = y;
return a;
}
becomes cleaner when you don't need to see the "struct" keyword all over the place, it looks more as if there really is a type called "Point" in your language. Which, after the typedef
, is the case I guess.
Also note that while your example (and mine) omitted naming the struct
itself, actually naming it is also useful for when you want to provide an opaque type. Then you'd have code like this in the header, for instance:
typedef struct Point Point;
Point * point_new(int x, int y);
and then provide the struct
definition in the implementation file:
struct Point
{
int x, y;
};
Point * point_new(int x, int y)
{
Point *p;
if((p = malloc(sizeof *p)) != NULL)
{
p->x = x;
p->y = y;
}
return p;
}
In this latter case, you cannot return the Point by value, since its definition is hidden from users of the header file. This is a technique used widely in GTK+, for instance.
UPDATE Note that there are also highly-regarded C projects where this use of typedef
to hide struct
is considered a bad idea, the Linux kernel is probably the most well-known such project. See Chapter 5 of The Linux Kernel CodingStyle document for Linus' angry words. :) My point is that the "should" in the question is perhaps not set in stone, after all.
The notion of complex numbers was introduced in mathematics, from the need of calculating negative quadratic roots. Complex number concept was taken by a variety of engineering fields.
Today that complex numbers are widely used in advanced engineering domains such as physics, electronics, mechanics, astronomy, etc...
Real and imaginary part, of a negative square root example:
#include <stdio.h>
#include <complex.h>
int main()
{
int negNum;
printf("Calculate negative square roots:\n"
"Enter negative number:");
scanf("%d", &negNum);
double complex negSqrt = csqrt(negNum);
double pReal = creal(negSqrt);
double pImag = cimag(negSqrt);
printf("\nReal part %f, imaginary part %f"
", for negative square root.(%d)",
pReal, pImag, negNum);
return 0;
}
I see that you are all editing or updating from our files
For those who want automatic updates you can use our Ubuntu PPA
sudo add-apt-repository ppa:phpmyadmin/ppa
And for Debian users you will need to wait for next version of Debian or use PPA
Ubuntu 20 has phpMyAdmin 4.9 or a later version
Countable issues on our tracker
TLDR Update to latest 4.9 or 5.0 version to solve this issue.
After a bit of time (and more searching), I found this blog entry by Jomo Fisher.
One of the recent problems we’ve seen is that, because of the support for side-by-side runtimes, .NET 4.0 has changed the way that it binds to older mixed-mode assemblies. These assemblies are, for example, those that are compiled from C++\CLI. Currently available DirectX assemblies are mixed mode. If you see a message like this then you know you have run into the issue:
Mixed mode assembly is built against version 'v1.1.4322' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.
[Snip]
The good news for applications is that you have the option of falling back to .NET 2.0 era binding for these assemblies by setting an app.config flag like so:
<startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version="v4.0"/> </startup>
So it looks like the way the runtime loads mixed-mode assemblies has changed. I can't find any details about this change, or why it was done. But the useLegacyV2RuntimeActivationPolicy
attribute reverts back to CLR 2.0 loading.
The question is relatively old, but I hope this post still might be relevant for others.
TL;DR: use AlarmManager to schedule a task, use IntentService, see the sample code here;
Simple helloworld app, which sends you notification every 2 hours. Clicking on notification - opens secondary Activity in the app; deleting notification tracks.
Once you need to run some task on a scheduled basis. My own case: once a day, I want to fetch new content from server, compose a notification based on the content I got and show it to user.
First, let's create 2 activities: MainActivity, which starts notification-service and NotificationActivity, which will be started by clicking notification:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<Button
android:id="@+id/sendNotifications"
android:onClick="onSendNotificationsButtonClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Sending Notifications Every 2 Hours!" />
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onSendNotificationsButtonClick(View view) {
NotificationEventReceiver.setupAlarm(getApplicationContext());
}
}
and NotificationActivity is any random activity you can come up with. NB! Don't forget to add both activities into AndroidManifest.
Then let's create WakefulBroadcastReceiver
broadcast receiver, I called NotificationEventReceiver in code above.
Here, we'll set up AlarmManager
to fire PendingIntent
every 2 hours (or with any other frequency), and specify the handled actions for this intent in onReceive()
method. In our case - wakefully start IntentService
, which we'll specify in the later steps. This IntentService
would generate notifications for us.
Also, this receiver would contain some helper-methods like creating PendintIntents, which we'll use later
NB1! As I'm using WakefulBroadcastReceiver
, I need to add extra-permission into my manifest: <uses-permission android:name="android.permission.WAKE_LOCK" />
NB2! I use it wakeful version of broadcast receiver, as I want to ensure, that the device does not go back to sleep during my IntentService
's operation. In the hello-world it's not that important (we have no long-running operation in our service, but imagine, if you have to fetch some relatively huge files from server during this operation). Read more about Device Awake here.
NotificationEventReceiver.java
public class NotificationEventReceiver extends WakefulBroadcastReceiver {
private static final String ACTION_START_NOTIFICATION_SERVICE = "ACTION_START_NOTIFICATION_SERVICE";
private static final String ACTION_DELETE_NOTIFICATION = "ACTION_DELETE_NOTIFICATION";
private static final int NOTIFICATIONS_INTERVAL_IN_HOURS = 2;
public static void setupAlarm(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent alarmIntent = getStartPendingIntent(context);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
getTriggerAt(new Date()),
NOTIFICATIONS_INTERVAL_IN_HOURS * AlarmManager.INTERVAL_HOUR,
alarmIntent);
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Intent serviceIntent = null;
if (ACTION_START_NOTIFICATION_SERVICE.equals(action)) {
Log.i(getClass().getSimpleName(), "onReceive from alarm, starting notification service");
serviceIntent = NotificationIntentService.createIntentStartNotificationService(context);
} else if (ACTION_DELETE_NOTIFICATION.equals(action)) {
Log.i(getClass().getSimpleName(), "onReceive delete notification action, starting notification service to handle delete");
serviceIntent = NotificationIntentService.createIntentDeleteNotification(context);
}
if (serviceIntent != null) {
startWakefulService(context, serviceIntent);
}
}
private static long getTriggerAt(Date now) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(now);
//calendar.add(Calendar.HOUR, NOTIFICATIONS_INTERVAL_IN_HOURS);
return calendar.getTimeInMillis();
}
private static PendingIntent getStartPendingIntent(Context context) {
Intent intent = new Intent(context, NotificationEventReceiver.class);
intent.setAction(ACTION_START_NOTIFICATION_SERVICE);
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
public static PendingIntent getDeleteIntent(Context context) {
Intent intent = new Intent(context, NotificationEventReceiver.class);
intent.setAction(ACTION_DELETE_NOTIFICATION);
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
}
Now let's create an IntentService
to actually create notifications.
There, we specify onHandleIntent()
which is responses on NotificationEventReceiver's intent we passed in startWakefulService
method.
If it's Delete action - we can log it to our analytics, for example. If it's Start notification intent - then by using NotificationCompat.Builder
we're composing new notification and showing it by NotificationManager.notify
. While composing notification, we are also setting pending intents for click and remove actions. Fairly Easy.
NotificationIntentService.java
public class NotificationIntentService extends IntentService {
private static final int NOTIFICATION_ID = 1;
private static final String ACTION_START = "ACTION_START";
private static final String ACTION_DELETE = "ACTION_DELETE";
public NotificationIntentService() {
super(NotificationIntentService.class.getSimpleName());
}
public static Intent createIntentStartNotificationService(Context context) {
Intent intent = new Intent(context, NotificationIntentService.class);
intent.setAction(ACTION_START);
return intent;
}
public static Intent createIntentDeleteNotification(Context context) {
Intent intent = new Intent(context, NotificationIntentService.class);
intent.setAction(ACTION_DELETE);
return intent;
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d(getClass().getSimpleName(), "onHandleIntent, started handling a notification event");
try {
String action = intent.getAction();
if (ACTION_START.equals(action)) {
processStartNotification();
}
if (ACTION_DELETE.equals(action)) {
processDeleteNotification(intent);
}
} finally {
WakefulBroadcastReceiver.completeWakefulIntent(intent);
}
}
private void processDeleteNotification(Intent intent) {
// Log something?
}
private void processStartNotification() {
// Do something. For example, fetch fresh data from backend to create a rich notification?
final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle("Scheduled Notification")
.setAutoCancel(true)
.setColor(getResources().getColor(R.color.colorAccent))
.setContentText("This notification has been triggered by Notification Service")
.setSmallIcon(R.drawable.notification_icon);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
NOTIFICATION_ID,
new Intent(this, NotificationActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
builder.setDeleteIntent(NotificationEventReceiver.getDeleteIntent(this));
final NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(NOTIFICATION_ID, builder.build());
}
}
Almost done. Now I also add broadcast receiver for BOOT_COMPLETED, TIMEZONE_CHANGED, and TIME_SET events to re-setup my AlarmManager, once device has been rebooted or timezone has changed (For example, user flown from USA to Europe and you don't want notification to pop up in the middle of the night, but was sticky to the local time :-) ).
NotificationServiceStarterReceiver.java
public final class NotificationServiceStarterReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
NotificationEventReceiver.setupAlarm(context);
}
}
We need to also register all our services, broadcast receivers in AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="klogi.com.notificationbyschedule">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".notifications.NotificationIntentService"
android:enabled="true"
android:exported="false" />
<receiver android:name=".broadcast_receivers.NotificationEventReceiver" />
<receiver android:name=".broadcast_receivers.NotificationServiceStarterReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.TIMEZONE_CHANGED" />
<action android:name="android.intent.action.TIME_SET" />
</intent-filter>
</receiver>
<activity
android:name=".NotificationActivity"
android:label="@string/title_activity_notification"
android:theme="@style/AppTheme.NoActionBar"/>
</application>
</manifest>
The source code for this project you can find here. I hope, you will find this post helpful.
You can't for Internet Explorer.
See this comment I wrote on a related topic:
There doesn't seem to be a good way, see: How to change color of disabled html controls in IE8 using css - you can set the input to
readonly
instead, but that has other consequences (such as withreadonly
, theinput
will be sent to the server on submit, but withdisabled
, it won't be): http://jsfiddle.net/wCFBw/40
Also, see: Changing font colour in Textboxes in IE which are disabled
Visual studio 2015
I hope this helps.
export your C++ functions as extern "C" (aka C style symbols), or use the .def file format to define undecorated export symbols for the C++ linker when it creates the C++ library, then the C linker should have no troubles reading it
Here is another solution for adding class definitions to the widgets after declaring the fields in the class.
def __init__(self, *args, **kwargs):
super(SampleClass, self).__init__(*args, **kwargs)
self.fields['name'].widget.attrs['class'] = 'my_class'
import java.util.List;
import java.util.stream.Stream;
class Main {
public static void main(String[] args) {
// Create a stream of strings from list of strings
Stream<String> myStreamOfStrings = List.of("lala", "foo", "bar").stream();
// Convert stream to array by using toArray method
String[] myArrayOfStrings = myStreamOfStrings.toArray(String[]::new);
// Print results
for (String string : myArrayOfStrings) {
System.out.println(string);
}
}
}
Try it out online: https://repl.it/@SmaMa/Stream-to-array
The following is a sample code to pass values from one page to another using html. Here the data from page1 is passed to page2 and it's retrieved by using javascript.
1) page1.html
<!-- Value passing one page to another
Author: Codemaker
-->
<html>
<head>
<title> Page 1 - Codemaker</title>
</head>
<body>
<form method="get" action="page2.html">
<table>
<tr>
<td>First Name:</td>
<td><input type=text name=firstname size=10></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type=text name=lastname size=10></td>
</tr>
<tr>
<td>Age:</td>
<td><input type=text name=age size=10></td>
</tr>
<tr>
<td colspan=2><input type=submit value="Submit">
</td>
</tr>
</table>
</form>
</body>
</html>
2) page2.html
<!-- Value passing one page to another
Author: Codemaker
-->
<html>
<head>
<title> Page 2 - Codemaker</title>
</head>
<body>
<script>
function getParams(){
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
for (var i=0; i<pairs.length; i++){
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params;
}
params = getParams();
firstname = unescape(params["firstname"]);
lastname = unescape(params["lastname"]);
age = unescape(params["age"]);
document.write("firstname = " + firstname + "<br>");
document.write("lastname = " + lastname + "<br>");
document.write("age = " + age + "<br>");
</script>
</body>
</html>
it is because view child require two argument try like this
@ViewChild('nameInput', { static: false, }) nameInputRef: ElementRef;
@ViewChild('amountInput', { static: false, }) amountInputRef: ElementRef;
Facebook now supports hiding the count, use this in the markup:
data-layout="button"
It seems that I found a solution to my problem. Very good explanations are given here and here. Here is my example:
pulic class MyActivity extends FragmentActivity{
private ViewPager pager;
private TitlePageIndicator indicator;
private TabsAdapter adapter;
private Bundle savedInstanceState;
@Override
public void onCreate(Bundle savedInstanceState) {
....
this.savedInstanceState = savedInstanceState;
pager = (ViewPager) findViewById(R.id.pager);;
indicator = (TitlePageIndicator) findViewById(R.id.indicator);
adapter = new TabsAdapter(getSupportFragmentManager(), false);
if (savedInstanceState == null){
adapter.addFragment(new FirstFragment());
adapter.addFragment(new SecondFragment());
}else{
Integer count = savedInstanceState.getInt("tabsCount");
String[] titles = savedInstanceState.getStringArray("titles");
for (int i = 0; i < count; i++){
adapter.addFragment(getFragment(i), titles[i]);
}
}
indicator.notifyDataSetChanged();
adapter.notifyDataSetChanged();
// push first task
FirstTask firstTask = new FirstTask(MyActivity.this);
// set first fragment as listener
firstTask.setTaskListener((TaskListener) getFragment(0));
firstTask.execute();
}
private Fragment getFragment(int position){
return savedInstanceState == null ? adapter.getItem(position) : getSupportFragmentManager().findFragmentByTag(getFragmentTag(position));
}
private String getFragmentTag(int position) {
return "android:switcher:" + R.id.pager + ":" + position;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tabsCount", adapter.getCount());
outState.putStringArray("titles", adapter.getTitles().toArray(new String[0]));
}
indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
Fragment currentFragment = adapter.getItem(position);
((Taskable) currentFragment).executeTask();
}
@Override
public void onPageScrolled(int i, float v, int i1) {}
@Override
public void onPageScrollStateChanged(int i) {}
});
The main idea in this code is that, while running your application normally, you create new fragments and pass them to the adapter. When you are resuming your application fragment manager already has this fragment's instance and you need to get it from fragment manager and pass it to the adapter.
UPDATE
Also, it is a good practice when using fragments to check isAdded before getActivity() is called. This helps avoid a null pointer exception when the fragment is detached from the activity. For example, an activity could contain a fragment that pushes an async task. When the task is finished, the onTaskComplete listener is called.
@Override
public void onTaskComplete(List<Feed> result) {
progress.setVisibility(View.GONE);
progress.setIndeterminate(false);
list.setVisibility(View.VISIBLE);
if (isAdded()) {
adapter = new FeedAdapter(getActivity(), R.layout.feed_item, result);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
If we open the fragment, push a task, and then quickly press back to return to a previous activity, when the task is finished, it will try to access the activity in onPostExecute() by calling the getActivity() method. If the activity is already detached and this check is not there:
if (isAdded())
then the application crashes.
I am going to assume this is a WinForms questions (which it feels like, based on it being a "program" rather than a website/app). In which case you can simple do the following to change the text colour of a label:
myLabel.ForeColor = System.Drawing.Color.Red;
Or any other colour of your choice. If you want to be more specific you can use an RGB value like so:
myLabel.ForeColor = Color.FromArgb(0, 0, 0);//(R, G, B) (0, 0, 0 = black)
Having different colours for different users can be done a number of ways. For example, you could allow each user to specify their own RGB value colours, store these somewhere and then load them when the user "connects".
An alternative method could be to just use 2 colours - 1 for the current user (running the app) and another colour for everyone else. This would help the user quickly identify their own messages above others.
A third approach could be to generate the colour randomly - however you will likely get conflicting values that do not show well against your background, so I would suggest not taking this approach. You could have a pre-defined list of "acceptable" colours and just pop one from that list for each user that joins.
As yet another new answer to an old question, I'd suggest a look at DefiantJS. It's not an XSLT equivalent for JSON, it is XSLT for JSON. The "Templating" section of the documentation includes this example:
<!-- Defiant template -->
<script type="defiant/xsl-template">
<xsl:template name="books_template">
<xsl:for-each select="//movie">
<xsl:value-of select="title"/><br/>
</xsl:for-each>
</xsl:template>
</script>
<script type="text/javascript">
var data = {
"movie": [
{"title": "The Usual Suspects"},
{"title": "Pulp Fiction"},
{"title": "Independence Day"}
]
},
htm = Defiant.render('books_template', data);
console.log(htm);
// The Usual Suspects<br>
// Pulp Fiction<br>
// Independence Day<br>
Anyone who has this error, especially on Azure, try adding "tcp:" to the db-server-name in your connection string in your application. This forces the sql client to communicate with the db using tcp. I'm assuming the connection is UDP by default and there can be intermittent connection issues
To know the usage of the specific directory in GB's or TB's in linux the command is,
df -h /dir/inner_dir/
or
df -sh /dir/inner_dir/
and to know the usage of the specific directory in bits in linux the command is,
df-k /dir/inner_dir/
You get this error, despite everything being in line, because of a conflict caused by one of the packages that are currently loaded in your R environment.
So, to solve this issue, detach all the packages that are not needed from the R environment. For example, when I had the same issue, I did the following:
detach(package:neuralnet)
bottom line: detach all the libraries no longer needed for execution... and the problem will be solved.
create a folder in main. like: 'res_notification_btn'
and create tree folder in. like 'drawable' or 'layout'
then in 'build.gradle' add this
sourceSets
{
main
{
res
{
srcDirs = ['src/main/res_notification_btn', 'src/main/res']
or
srcDir 'src/main/res_notification_btn'
}
}
}
Just in case someone wants to do it for exact matches of strings, you can use the -w
flag in grep - w for whole. That is, for example if you want to delete the lines that have number 11, but keep the lines with number 111:
-bash-4.1$ head file
1
11
111
-bash-4.1$ grep -v "11" file
1
-bash-4.1$ grep -w -v "11" file
1
111
It also works with the -f
flag if you want to exclude several exact patterns at once. If "blacklist" is a file with several patterns on each line that you want to delete from "file":
grep -w -v -f blacklist file
There are no keys in JavaScript arrays. Use objects for that purpose.
var obj = {};
$.getJSON("displayjson.php",function (data) {
$.each(data.news, function (i, news) {
obj[news.title] = news.link;
});
});
// later:
$.each(obj, function (index, value) {
alert( index + ' : ' + value );
});
In JavaScript, objects fulfill the role of associative arrays. Be aware that objects do not have a defined "sort order" when iterating them (see below).
However, In your case it is not really clear to me why you transfer data from the original object (data.news
) at all. Why do you not simply pass a reference to that object around?
You can combine objects and arrays to achieve predictable iteration and key/value behavior:
var arr = [];
$.getJSON("displayjson.php",function (data) {
$.each(data.news, function (i, news) {
arr.push({
title: news.title,
link: news.link
});
});
});
// later:
$.each(arr, function (index, value) {
alert( value.title + ' : ' + value.link );
});
label
is an inline element so its width is equal to the width of the text it contains. The browser is actually displaying the label with text-align:center
but since the label is only as wide as the text you don't notice.
The best thing to do is to apply a specific width to the label
that is greater than the width of the content - this will give you the results you want.
Check spring application.properties
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
here testdb is database defined Make sure h2 console have same value while connecting other wise it will connect to default db
For regular Windows users who are not skilled with computers, it is practically not possible to install and use extensions from outside the Chrome Web Store.
Users of other operating systems (Linux, Mac, Chrome OS) can easily install unpacked extensions (in developer mode).
Windows users can also load an unpacked extension, but they will always see an information bubble with "Disable developer mode extensions" when they start Chrome or open a new incognito window, which is really annoying. The only way for Windows users to use unpacked extensions without such dialogs is to switch to Chrome on the developer channel, by installing https://www.google.com/chrome/browser/index.html?extra=devchannel#eula.
Extensions can be loaded in unpacked mode by following the following steps:
chrome://extensions
(via omnibox or menu -> Tools -> Extensions).If you have a crx
file, then it needs to be extracted first. CRX files are zip files with a different header. Any capable zip program should be able to open it. If you don't have such a program, I recommend 7-zip.
These steps will work for almost every extension, except extensions that rely on their extension ID. If you use the previous method, you will get an extension with a random extension ID. If it is important to preserve the extension ID, then you need to know the public key of your CRX file and insert this in your manifest.json. I have previously given a detailed explanation on how to get and use this key at https://stackoverflow.com/a/21500707.
There are some great answers here but I wanted to point out the jvm is free to store a char value in any size space >= 2 bytes.
On many architectures there is a penalty for performing unaligned memory access so a char might easily be padded to 4 bytes. A volatile char might even be padded to the size of the CPU cache line to prevent false sharing. https://en.wikipedia.org/wiki/False_sharing
It might be non-intuitive to new Java programmers that a character array or a string is NOT simply multiple characters. You should learn and think about strings and arrays distinctly from "multiple characters".
I also want to point out that java characters are often misused. People don't realize they are writing code that won't properly handle codepoints over 16 bits in length.
You'll need at least PHP Version 5.4 to implement this solution without exploding into a variable on one line and concatenating on the next, but an easy one liner would be:
$_SERVER["HTTP_HOST"].explode('?', $_SERVER["REQUEST_URI"], 2)[0];
Server Variables: http://php.net/manual/en/reserved.variables.server.php
Array Dereferencing: https://wiki.php.net/rfc/functionarraydereferencing
ngModel is coming from FormsModule. There are some cases when you can receive this kind of error:
let the FormsModule be imported into the import array from both modules:module1 and module2. As the rule: Importing a module does not provide access to its imported modules. (Imports are not inherited)
declare the FormsModule into the import and export arrays in module1 to be able to see it in model2 also
Try this:
window.open(url, '_blank');
This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)
The blog post you quoted overstates its claim a bit. FP doesn't eliminate the need for design patterns. The term "design patterns" just isn't widely used to describe the same thing in FP languages. But they exist. Functional languages have plenty of best practice rules of the form "when you encounter problem X, use code that looks like Y", which is basically what a design pattern is.
However, it's correct that most OOP-specific design patterns are pretty much irrelevant in functional languages.
I don't think it should be particularly controversial to say that design patterns in general only exist to patch up shortcomings in the language. And if another language can solve the same problem trivially, that other language won't have need of a design pattern for it. Users of that language may not even be aware that the problem exists, because, well, it's not a problem in that language.
Here is what the Gang of Four has to say about this issue:
The choice of programming language is important because it influences one's point of view. Our patterns assume Smalltalk/C++-level language features, and that choice determines what can and cannot be implemented easily. If we assumed procedural languages, we might have included design patterns called "Inheritance", "Encapsulation," and "Polymorphism". Similarly, some of our patterns are supported directly by the less common object-oriented languages. CLOS has multi-methods, for example, which lessen the need for a pattern such as Visitor. In fact, there are enough differences between Smalltalk and C++ to mean that some patterns can be expressed more easily in one language than the other. (See Iterator for example.)
(The above is a quote from the Introduction to the Design Patterns book, page 4, paragraph 3)
The main features of functional programming include functions as first-class values, currying, immutable values, etc. It doesn't seem obvious to me that OO design patterns are approximating any of those features.
What is the command pattern, if not an approximation of first-class functions? :) In an FP language, you'd simply pass a function as the argument to another function. In an OOP language, you have to wrap up the function in a class, which you can instantiate and then pass that object to the other function. The effect is the same, but in OOP it's called a design pattern, and it takes a whole lot more code. And what is the abstract factory pattern, if not currying? Pass parameters to a function a bit at a time, to configure what kind of value it spits out when you finally call it.
So yes, several GoF design patterns are rendered redundant in FP languages, because more powerful and easier to use alternatives exist.
But of course there are still design patterns which are not solved by FP languages. What is the FP equivalent of a singleton? (Disregarding for a moment that singletons are generally a terrible pattern to use.)
And it works both ways too. As I said, FP has its design patterns too; people just don't usually think of them as such.
But you may have run across monads. What are they, if not a design pattern for "dealing with global state"? That's a problem that's so simple in OOP languages that no equivalent design pattern exists there.
We don't need a design pattern for "increment a static variable", or "read from that socket", because it's just what you do.
Saying a monad is a design pattern is as absurd as saying the Integers with their usual operations and zero element is a design pattern. No, a monad is a mathematical pattern, not a design pattern.
In (pure) functional languages, side effects and mutable state are impossible, unless you work around it with the monad "design pattern", or any of the other methods for allowing the same thing.
Additionally, in functional languages which support OOP (such as F# and OCaml), it seems obvious to me that programmers using these languages would use the same design patterns found available to every other OOP language. In fact, right now I use F# and OCaml everyday, and there are no striking differences between the patterns I use in these languages vs the patterns I use when I write in Java.
Perhaps because you're still thinking imperatively? A lot of people, after dealing with imperative languages all their lives, have a hard time giving up on that habit when they try a functional language. (I've seen some pretty funny attempts at F#, where literally every function was just a string of 'let' statements, basically as if you'd taken a C program, and replaced all semicolons with 'let'. :))
But another possibility might be that you just haven't realized that you're solving problems trivially which would require design patterns in an OOP language.
When you use currying, or pass a function as an argument to another, stop and think about how you'd do that in an OOP language.
Is there any truth to the claim that functional programming eliminates the need for OOP design patterns?
Yep. :) When you work in a FP language, you no longer need the OOP-specific design patterns. But you still need some general design patterns, like MVC or other non-OOP specific stuff, and you need a couple of new FP-specific "design patterns" instead. All languages have their shortcomings, and design patterns are usually how we work around them.
Anyway, you may find it interesting to try your hand at "cleaner" FP languages, like ML (my personal favorite, at least for learning purposes), or Haskell, where you don't have the OOP crutch to fall back on when you're faced with something new.
As expected, a few people objected to my definition of design patterns as "patching up shortcomings in a language", so here's my justification:
As already said, most design patterns are specific to one programming paradigm, or sometimes even one specific language. Often, they solve problems that only exist in that paradigm (see monads for FP, or abstract factories for OOP).
Why doesn't the abstract factory pattern exist in FP? Because the problem it tries to solve does not exist there.
So, if a problem exists in OOP languages, which does not exist in FP languages, then clearly that is a shortcoming of OOP languages. The problem can be solved, but your language does not do so, but requires a bunch of boilerplate code from you to work around it. Ideally, we'd like our programming language to magically make all problems go away. Any problem that is still there is in principle a shortcoming of the language. ;)
Adding to previous answers: check the pexpect module for dealing with interactive commands (adduser, passwd etc.)
Just run into this with another cause:
running unit tests in release mode but the library being loaded was the debug mode version which had not been updated
You can simply install a vncserver along with Firefox :)
I pushed an image, vnc/firefox, here: docker pull creack/firefox-vnc
The image has been made with this Dockerfile:
# Firefox over VNC
#
# VERSION 0.1
# DOCKER-VERSION 0.2
FROM ubuntu:12.04
# Make sure the package repository is up to date
RUN echo "deb http://archive.ubuntu.com/ubuntu precise main universe" > /etc/apt/sources.list
RUN apt-get update
# Install vnc, xvfb in order to create a 'fake' display and firefox
RUN apt-get install -y x11vnc xvfb firefox
RUN mkdir ~/.vnc
# Setup a password
RUN x11vnc -storepasswd 1234 ~/.vnc/passwd
# Autostart firefox (might not be the best way to do it, but it does the trick)
RUN bash -c 'echo "firefox" >> /.bashrc'
This will create a Docker container running VNC with the password 1234
:
For Docker version 18 or newer:
docker run -p 5900:5900 -e HOME=/ creack/firefox-vnc x11vnc -forever -usepw -create
For Docker version 1.3 or newer:
docker run -p 5900 -e HOME=/ creack/firefox-vnc x11vnc -forever -usepw -create
For Docker before version 1.3:
docker run -p 5900 creack/firefox-vnc x11vnc -forever -usepw -create
//Making a POST request using WebClient.
Function()
{
WebClient wc = new WebClient();
var URI = new Uri("http://your_uri_goes_here");
//If any encoding is needed.
wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
//Or any other encoding type.
//If any key needed
wc.Headers["KEY"] = "Your_Key_Goes_Here";
wc.UploadStringCompleted +=
new UploadStringCompletedEventHandler(wc_UploadStringCompleted);
wc.UploadStringAsync(URI,"POST","Data_To_Be_sent");
}
void wc__UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
try
{
MessageBox.Show(e.Result);
//e.result fetches you the response against your POST request.
}
catch(Exception exc)
{
MessageBox.Show(exc.ToString());
}
}
With JDK,
You can also use jinfo to connect to the JVM for the <PROCESS_ID>
in question and get the value for MaxHeapSize:
jinfo -flag MaxHeapSize <PROCESS_ID>
The Resource Exception means there is an error with your resources, any resource folder file is corrupted, try to open all images in drawable folder to see if these are opening fine.
There is a good command to check for corrupted resource pngs.
f -name "*.png" | xargs -L 1 -I{} file -I {} | grep -v 'image/png; charset=binary$'
First, import java.util.Calendar
Calendar now = Calendar.getInstance();
System.out.println(now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE));
You can check by using the size
field on the $_FILES
array like so:
if ($_FILES['cover_image']['size'] == 0 && $_FILES['cover_image']['error'] == 0)
{
// cover_image is empty (and not an error)
}
(I also check error
here because it may be 0
if something went wrong. I wouldn't use name
for this check since that can be overridden)
Implement your adapter Filterable:
public class vJournalAdapter extends ArrayAdapter<JournalModel> implements Filterable{
private ArrayList<JournalModel> items;
private Context mContext;
....
then create your Filter class:
private class JournalFilter extends Filter{
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults result = new FilterResults();
List<JournalModel> allJournals = getAllJournals();
if(constraint == null || constraint.length() == 0){
result.values = allJournals;
result.count = allJournals.size();
}else{
ArrayList<JournalModel> filteredList = new ArrayList<JournalModel>();
for(JournalModel j: allJournals){
if(j.source.title.contains(constraint))
filteredList.add(j);
}
result.values = filteredList;
result.count = filteredList.size();
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.count == 0) {
notifyDataSetInvalidated();
} else {
items = (ArrayList<JournalModel>) results.values;
notifyDataSetChanged();
}
}
}
this way, your adapter is Filterable, you can pass filter item to adapter's filter and do the work. I hope this will be helpful.
We can use factorial to find how many strings started with particular letter.
Example: take the input abcd
. (3!) == 6
strings will start with every letter of abcd
.
static public int facts(int x){
int sum = 1;
for (int i = 1; i < x; i++) {
sum *= (i+1);
}
return sum;
}
public static void permutation(String str) {
char[] str2 = str.toCharArray();
int n = str2.length;
int permutation = 0;
if (n == 1) {
System.out.println(str2[0]);
} else if (n == 2) {
System.out.println(str2[0] + "" + str2[1]);
System.out.println(str2[1] + "" + str2[0]);
} else {
for (int i = 0; i < n; i++) {
if (true) {
char[] str3 = str.toCharArray();
char temp = str3[i];
str3[i] = str3[0];
str3[0] = temp;
str2 = str3;
}
for (int j = 1, count = 0; count < facts(n-1); j++, count++) {
if (j != n-1) {
char temp1 = str2[j+1];
str2[j+1] = str2[j];
str2[j] = temp1;
} else {
char temp1 = str2[n-1];
str2[n-1] = str2[1];
str2[1] = temp1;
j = 1;
} // end of else block
permutation++;
System.out.print("permutation " + permutation + " is -> ");
for (int k = 0; k < n; k++) {
System.out.print(str2[k]);
} // end of loop k
System.out.println();
} // end of loop j
} // end of loop i
}
}
If you just want to find a match.
SELECT * FROM MyTable WHERE INSTR('word1 word2 word3',Column1)<>0
SQL Server :
CHARINDEX(Column1, 'word1 word2 word3', 1)<>0
To get exact match. Example (';a;ab;ac;',';b;')
will not get a match.
SELECT * FROM MyTable WHERE INSTR(';word1;word2;word3;',';'||Column1||';')<>0
The three operators have related but different meanings, despite the misleading note from the IDE.
The ::
operator is known as the scope resolution operator, and it is used to get from a namespace or class to one of its members.
The .
and ->
operators are for accessing an object instance's members, and only comes into play after creating an object instance. You use .
if you have an actual object (or a reference to the object, declared with &
in the declared type), and you use ->
if you have a pointer to an object (declared with *
in the declared type).
The this
object is always a pointer to the current instance, hence why the ->
operator is the only one that works.
Examples:
// In a header file
namespace Namespace {
class Class {
private:
int x;
public:
Class() : x(4) {}
void incrementX();
};
}
// In an implementation file
namespace Namespace {
void Class::incrementX() { // Using scope resolution to get to the class member when we aren't using an instance
++(this->x); // this is a pointer, so using ->. Equivalent to ++((*this).x)
}
}
// In a separate file lies your main method
int main() {
Namespace::Class myInstance; // instantiates an instance. Note the scope resolution
Namespace::Class *myPointer = new Namespace::Class;
myInstance.incrementX(); // Calling a function on an object instance.
myPointer->incrementX(); // Calling a function on an object pointer.
(*myPointer).incrementX(); // Calling a function on an object pointer by dereferencing first
return 0;
}
I have tried all above answers it's showing me same vertically recycler view, so I have tried another example.
Initialize the adapter
private Adapter mAdapter;
set the adapter like this
mAdapter = new Adapter();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
recycler_view.setLayoutManager(linearLayoutManager);
recycler_view.setAdapter(mAdapter);
Hope this will also work for you For Complete code please refer this link
UPDATED
I've updated your demo: http://jsfiddle.net/terryyounghk/QS56z/18/
Also, I've changed two ^=
to *=
. See http://api.jquery.com/category/selectors/
And note the :checked
selector. See http://api.jquery.com/checked-selector/
function createcodes() {
//run through each row
$('.authors-list tr').each(function (i, row) {
// reference all the stuff you need first
var $row = $(row),
$family = $row.find('input[name*="family"]'),
$grade = $row.find('input[name*="grade"]'),
$checkedBoxes = $row.find('input:checked');
$checkedBoxes.each(function (i, checkbox) {
// assuming you layout the elements this way,
// we'll take advantage of .next()
var $checkbox = $(checkbox),
$line = $checkbox.next(),
$size = $line.next();
$line.val(
$family.val() + ' ' + $size.val() + ', ' + $grade.val()
);
});
});
}
Ascending order
Reserved.objects.all().filter(client=client_id).order_by('check_in')
Descending order
Reserved.objects.all().filter(client=client_id).order_by('-check_in')
-
(hyphen) is used to indicate descending order here.
For Disable Right Click Option
<script type="text/javascript">
var message="Function Disabled!";
function clickIE4(){
if (event.button==2){
alert(message);
return false;
}
}
function clickNS4(e){
if (document.layers||document.getElementById&&!document.all){
if (e.which==2||e.which==3){
alert(message);
return false;
}
}
}
if (document.layers){
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=clickNS4;
}
else if (document.all&&!document.getElementById){
document.onmousedown=clickIE4;
}
document.oncontextmenu=new Function("alert(message);return false")
</script>