Far from bad practice, Python (and other languages?) extended the for
loop structure so part of it will only be executed if the loop doesn't break
.
for n in range(5):
for m in range(3):
if m >= n:
print('stop!')
break
print(m, end=' ')
else:
print('finished.')
Output:
stop!
0 stop!
0 1 stop!
0 1 2 finished.
0 1 2 finished.
Equivalent code without break
and that handy else
:
for n in range(5):
aborted = False
for m in range(3):
if not aborted:
if m >= n:
print('stop!')
aborted = True
else:
print(m, end=' ')
if not aborted:
print('finished.')
I would tackle the problem like this:
BufferedWriter output;
output = new BufferedWriter(new FileWriter("file.txt", true));
String sizeX = jTextField1.getText();
String sizeY = jTextField2.getText();
output.append(sizeX);
output.append(sizeY);
output.newLine();
output.close();
The true in the FileWriter constructor allows to append.
The method newLine() is provided by BufferedWriter
Could be ok as solution?
Tested on Marshmallow S5 and it works!
Uri uri = Uri.parse("smsto:" + "phone number with country code");
Intent sendIntent = new Intent(Intent.ACTION_SENDTO, uri);
sendIntent.setPackage("com.whatsapp");
startActivity(sendIntent);
This will open a direct chat with a person, if whatsapp not installed this will throw exception, if phone number not known to whatsapp they will offer to send invite via sms or simple sms message
You can do the same on document ready
event like below
<script>
$(document).ready(function(){
var number = 112;
$("yourClass/Element/id...").html(number);
// $("yourClass/Element/id...").text(number);
});
</script>
or you can simply do it using document.write(number);
.
If you have an issue where you only want to remove trailing characters, you can try this:
WHILE EXISTS
(SELECT * FROM @ReportSet WHERE
ASCII(right(addr_3,1)) = 10
OR ASCII(right(addr_3,1)) = 13
OR ASCII(right(addr_3,1)) = 32)
BEGIN
UPDATE @ReportSet
SET addr_3 = LEFT(addr_3,LEN(addr_3)-1)
WHERE
ASCII(right(addr_3,1)) = 10
OR ASCII(right(addr_3,1)) = 13
OR ASCII(right(addr_3,1)) = 32
END
This solved a problem I had with addresses where a procedure created a field with a fixed number of lines, even if those lines were empty. To save space in my SSRS report, I cut them down.
You can update values from another table using inner join like this
UPDATE [table1_name] AS t1 INNER JOIN [table2_name] AS t2 ON t1.column1_name] = t2.[column1_name] SET t1.[column2_name] = t2.column2_name];
Follow here to know how to use this query http://www.voidtricks.com/mysql-inner-join-update/
or you can use select as subquery to do this
UPDATE [table_name] SET [column_name] = (SELECT [column_name] FROM [table_name] WHERE [column_name] = [value]) WHERE [column_name] = [value];
query explained in details here http://www.voidtricks.com/mysql-update-from-select/
A short demonstration of @gregmac's (excellent and detailed) answer, which essentially recommends $PSCommandPath
as the only reliable command to return the currently running script where Powershell 3.0 and above is used.
Here I show returning either the full path or just the file name.
Test.ps1:
'Direct:'
$PSCommandPath # Full Path
Split-Path -Path $PSCommandPath -Leaf # File Name only
function main () {
''
'Within a function:'
$PSCommandPath
Split-Path -Path $PSCommandPath -Leaf
}
main
Output:
PS> .\Test.ps1
Direct:
C:\Users\John\Documents\Sda\Code\Windows\PowerShell\Apps\xBankStatementRename\Test.ps1
Test.ps1
Within a function:
C:\Users\John\Documents\Sda\Code\Windows\PowerShell\Apps\xBankStatementRename\Test.ps1
Test.ps1
Yes. I recommend you check out Kimberly Tripp's articles on indexing.
If an index is "covering", then there is no need to use anything but the index. In SQL Server 2005, you can also add additional columns to the index that are not part of the key which can eliminate trips to the rest of the row.
Having multiple indexes, each on a single column may mean that only one index gets used at all - you will have to refer to the execution plan to see what effects different indexing schemes offer.
You can also use the tuning wizard to help determine what indexes would make a given query or workload perform the best.
HTML:
<div class="bool-answer">
<div class="answer">Nej</div>
</div>
CSS:
.bool-answer {
border-radius: 50%;
width: 100px;
height: 100px;
display: flex;
justify-content: center;
align-items: center;
}
In a truly optimized implementation, the method for choosing pivot should depend on the array size - for a large array, it pays off to spend more time choosing a good pivot. Without doing a full analysis, I would guess "middle of O(log(n)) elements" is a good start, and this has the added bonus of not requiring any extra memory: Using tail-call on the larger partition and in-place partitioning, we use the same O(log(n)) extra memory at almost every stage of the algorithm.
Standard UITableViewCell already contains UIImageView that appears to the left to all your labels if its image is set. You can access it using imageView property:
cell.imageView.image = someImage;
If for some reason standard behavior does not suit your needs (note that you can customize properties of that standard image view) then you can add your own UIImageView to the cell as Aman suggested in his answer. But in that approach you'll have to manage cell's layout yourself (e.g. make sure that cell labels do not overlap image). And do not add subviews to the cell directly - add them to cell's contentView:
// DO NOT!
[cell addSubview:imv];
// DO:
[cell.contentView addSubview:imv];
with
function and single
parameters:
$ms = Person::where('name', 'Foo Bar');
$persons = Person::order_by('list_order', 'ASC')->get();
return $view->with(compact('ms', 'persons'));
with
function and array
parameter:
$ms = Person::where('name', 'Foo Bar');
$persons = Person::order_by('list_order', 'ASC')->get();
$array = ['ms' => $ms, 'persons' => $persons];
return $view->with($array);
i would go around this by making a 2d dynamic array:
long long** a = new long long*[x];
for (unsigned i = 0; i < x; i++) a[i] = new long long[y];
more on this here https://stackoverflow.com/a/936702/3517001
Foolproof:
df.loc[:, 'NewCol'] = 'New_Val'
Example:
df = pd.DataFrame(data=np.random.randn(20, 4), columns=['A', 'B', 'C', 'D'])
df
A B C D
0 -0.761269 0.477348 1.170614 0.752714
1 1.217250 -0.930860 -0.769324 -0.408642
2 -0.619679 -1.227659 -0.259135 1.700294
3 -0.147354 0.778707 0.479145 2.284143
4 -0.529529 0.000571 0.913779 1.395894
5 2.592400 0.637253 1.441096 -0.631468
6 0.757178 0.240012 -0.553820 1.177202
7 -0.986128 -1.313843 0.788589 -0.707836
8 0.606985 -2.232903 -1.358107 -2.855494
9 -0.692013 0.671866 1.179466 -1.180351
10 -1.093707 -0.530600 0.182926 -1.296494
11 -0.143273 -0.503199 -1.328728 0.610552
12 -0.923110 -1.365890 -1.366202 -1.185999
13 -2.026832 0.273593 -0.440426 -0.627423
14 -0.054503 -0.788866 -0.228088 -0.404783
15 0.955298 -1.430019 1.434071 -0.088215
16 -0.227946 0.047462 0.373573 -0.111675
17 1.627912 0.043611 1.743403 -0.012714
18 0.693458 0.144327 0.329500 -0.655045
19 0.104425 0.037412 0.450598 -0.923387
df.drop([3, 5, 8, 10, 18], inplace=True)
df
A B C D
0 -0.761269 0.477348 1.170614 0.752714
1 1.217250 -0.930860 -0.769324 -0.408642
2 -0.619679 -1.227659 -0.259135 1.700294
4 -0.529529 0.000571 0.913779 1.395894
6 0.757178 0.240012 -0.553820 1.177202
7 -0.986128 -1.313843 0.788589 -0.707836
9 -0.692013 0.671866 1.179466 -1.180351
11 -0.143273 -0.503199 -1.328728 0.610552
12 -0.923110 -1.365890 -1.366202 -1.185999
13 -2.026832 0.273593 -0.440426 -0.627423
14 -0.054503 -0.788866 -0.228088 -0.404783
15 0.955298 -1.430019 1.434071 -0.088215
16 -0.227946 0.047462 0.373573 -0.111675
17 1.627912 0.043611 1.743403 -0.012714
19 0.104425 0.037412 0.450598 -0.923387
df.loc[:, 'NewCol'] = 0
df
A B C D NewCol
0 -0.761269 0.477348 1.170614 0.752714 0
1 1.217250 -0.930860 -0.769324 -0.408642 0
2 -0.619679 -1.227659 -0.259135 1.700294 0
4 -0.529529 0.000571 0.913779 1.395894 0
6 0.757178 0.240012 -0.553820 1.177202 0
7 -0.986128 -1.313843 0.788589 -0.707836 0
9 -0.692013 0.671866 1.179466 -1.180351 0
11 -0.143273 -0.503199 -1.328728 0.610552 0
12 -0.923110 -1.365890 -1.366202 -1.185999 0
13 -2.026832 0.273593 -0.440426 -0.627423 0
14 -0.054503 -0.788866 -0.228088 -0.404783 0
15 0.955298 -1.430019 1.434071 -0.088215 0
16 -0.227946 0.047462 0.373573 -0.111675 0
17 1.627912 0.043611 1.743403 -0.012714 0
19 0.104425 0.037412 0.450598 -0.923387 0
There is no such thing as an "epoch" in a specific timezone. The epoch is well-defined as a specific moment in time, so if you change the timezone, the time itself changes as well. Specifically, this time is Jan 1 1970 00:00:00 UTC
. So time.time()
returns the number of seconds since the epoch.
I found this maven
repo where you could download from directly a zip
file containing all the jars you need.
The solution I prefer is using Maven
, it is easy and you don't have to download each jar
alone. You can do it with the following steps:
Create an empty folder anywhere with any name you prefer, for example spring-source
Create a new file named pom.xml
Copy the xml below into this file
Open the spring-source
folder in your console
Run mvn install
After download finished, you'll find spring jars in /spring-source/target/dependencies
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>spring-source-download</groupId>
<artifactId>SpringDependencies</artifactId>
<version>1.0</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.8</version>
<executions>
<execution>
<id>download-dependencies</id>
<phase>generate-resources</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/dependencies</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Also, if you need to download any other spring project, just copy the dependency
configuration from its corresponding web page.
For example, if you want to download Spring Web Flow
jars, go to its web page, and add its dependency
configuration to the pom.xml
dependencies
, then run mvn install
again.
<dependency>
<groupId>org.springframework.webflow</groupId>
<artifactId>spring-webflow</artifactId>
<version>2.3.2.RELEASE</version>
</dependency>
Here is an update for Swift 3 and an addition to Mani's answer. I would suggest using sender.view
in combination with tagging UIViews (or other elements, depending on what you are trying to track) for a somewhat more "advanced" approach.
let yourTapEvent = UITapGestureRecognizer(target: self, action: #selector(yourController.yourFunction))
yourObject.addGestureRecognizer(yourTapEvent) // adding the gesture to your object
Defining the function in the same testController (that's the name of your View Controller). We are going to use tags here - tags are Int IDs, which you can add to your UIView with yourButton.tag = 1
. If you have a dynamic list of elements like an array you can make a for-loop, which iterates through your array and adds a tag, which increases incrementally
func yourFunction(_ sender: AnyObject) {
let yourTag = sender.view!.tag // this is the tag of your gesture's object
// do whatever you want from here :) e.g. if you have an array of buttons instead of just 1:
for button in buttonsArray {
if(button.tag == yourTag) {
// do something with your button
}
}
}
The reason for all of this is because you cannot pass further arguments for yourFunction when using it in conjunction with #selector.
If you have an even more complex UI structure and you want to get the parent's tag of the item attached to your tap gesture you can use let yourAdvancedTag = sender.view!.superview?.tag
e.g. getting the UIView's tag of a pressed button inside that UIView; can be useful for thumbnail+button lists etc.
I have created step by step instructions on how to do this as I also was very confused about how to get this working.
How to make a self extracting archive that runs your setup.exe with 7zip -sfx switch
Here are the steps.
To make this easy create a folder c:\Install. This is where we will copy all the required files.
You need to download 7zSD.sfx
7zSD.sfx
in the bin
folder.I would recommend using NotePad++ to edit this text file as you will need to encode in UTF-8, the following instructions are using notepad++.
Enter something like this:
;!@Install@!UTF-8!
Title="SOFTWARE v1.0.0.0"
BeginPrompt="Do you want to install SOFTWARE v1.0.0.0?"
RunProgram="setup.exe"
;!@InstallEnd@!
Edit this replacing [SOFTWARE v1.0.0.0] with your product name. Notes on the parameters and options for the setup file are here.
You should now have a folder "c:\Install" with the following 3 files:
These instructions I found on the web but nowhere did it explain any of the 4 steps above.
In the command window type the following
cd \
cd Install
copy /b 7zSD.sfx + config.txt + Installer.7z MyInstaller.exe
Look in c:\Install and you will now see you have a MyInstaller.exe
Double click on MyInstaller.exe and it will prompt with your message. Click OK and the setup.exe will run.
Now that you have this working in your c:\Install directory I would create an "Install.bat" file and put the copy script in it.
copy /b 7zSD.sfx + config.txt + Installer.7z MyInstaller.exe
Now you can just edit and run the Install.bat every time you need to rebuild a new version of you deployment package.
A Simple solution :
Create a drawable file as edittext_stroke.xml in drawable folder. Add the below code:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line"
>
<stroke
android:width="1dp"
android:color="@android:color/white" >
</stroke>
</shape>
In layout file , add the drawable to edittext as
android:drawableBottom="@drawable/edittext_stroke"
<EditText
android:textColor="@android:color/white"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableBottom="@drawable/edittext_stroke"
/>
Performs a left outer join to an unsharded collection in the same database to filter in documents from the “joined” collection for processing. To each input document, the $lookup stage adds a new array field whose elements are the matching documents from the “joined” collection. The $lookup stage passes these reshaped documents to the next stage. The $lookup stage has the following syntaxes:
To perform an equality match between a field from the input documents with a field from the documents of the “joined” collection, the $lookup stage has the following syntax:
{
$lookup:
{
from: <collection to join>,
localField: <field from the input documents>,
foreignField: <field from the documents of the "from" collection>,
as: <output array field>
}
}
The operation would correspond to the following pseudo-SQL statement:
SELECT *, <output array field>
FROM collection
WHERE <output array field> IN (SELECT <documents as determined from the pipeline>
FROM <collection to join>
WHERE <pipeline> );
I'm using the following configuration:
#site.yml:
- name: Example play
hosts: all
remote_user: ansible
become: yes
become_method: sudo
vars:
ansible_ssh_private_key_file: "/home/ansible/.ssh/id_rsa"
Because these days ASP.NET is open source, you can find it on GitHub: AspNet.Identity 3.0 and AspNet.Identity 2.0.
From the comments:
/* =======================
* HASHED PASSWORD FORMATS
* =======================
*
* Version 2:
* PBKDF2 with HMAC-SHA1, 128-bit salt, 256-bit subkey, 1000 iterations.
* (See also: SDL crypto guidelines v5.1, Part III)
* Format: { 0x00, salt, subkey }
*
* Version 3:
* PBKDF2 with HMAC-SHA256, 128-bit salt, 256-bit subkey, 10000 iterations.
* Format: { 0x01, prf (UInt32), iter count (UInt32), salt length (UInt32), salt, subkey }
* (All UInt32s are stored big-endian.)
*/
in the manifest:
<activity android:name=".activity.MainActivity"
android:screenOrientation="portrait"
tools:ignore="LockedOrientationActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
or : in the MainActivity
@SuppressLint("SourceLockedOrientationActivity")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
try this:
String str = "9B7D2C34A366BF890C730641E6CECF6F";
String[] temp = str.split(",");
bytesArray = new byte[temp.length];
int index = 0;
for (String item: temp) {
bytesArray[index] = Byte.parseByte(item);
index++;
}
function array_not_unique( $a = array() )
{
return array_diff_key( $a , array_unique( $a ) );
}
On a side note, good to know
This answer works (https://stackoverflow.com/a/13468685/7034327)
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
this.finish();
whereas this doesn't work
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
.setFlags()
replaces any previous flags and doesn't append any new flags while .addFlags()
does.
So this will also work
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
ECUs (EC2 Computer Units) are a rough measure of processor performance that was introduced by Amazon to let you compare their EC2 instances ("servers").
CPU performance is of course a multi-dimensional measure, so putting a single number on it (like "5 ECU") can only be a rough approximation. If you want to know more exactly how well a processor performs for a task you have in mind, you should choose a benchmark that is similar to your task.
In early 2014, there was a nice benchmarking site comparing cloud hosting offers by tens of different benchmarks, over at CloudHarmony benchmarks. However, this seems gone now (and archive.org can't help as it was a web application). Only an introductory blog post is still available.
Also useful: ec2instances.info, which at least aggregates the ECU information of different EC2 instances for comparison. (Add column "Compute Units (ECU)" to make it work.)
AFAIK you cannot do it with linear layouts, you'll have to go for a RelativeLayout.
I found this thread when I was searching for an answer to the same question. While I realize that it's a late answer, I thought I'd contribute it in case it's useful to anyone else:
def find_dict_in_list(dicts, default=None, **kwargs):
"""Find first matching :obj:`dict` in :obj:`list`.
:param list dicts: List of dictionaries.
:param dict default: Optional. Default dictionary to return.
Defaults to `None`.
:param **kwargs: `key=value` pairs to match in :obj:`dict`.
:returns: First matching :obj:`dict` from `dicts`.
:rtype: dict
"""
rval = default
for d in dicts:
is_found = False
# Search for keys in dict.
for k, v in kwargs.items():
if d.get(k, None) == v:
is_found = True
else:
is_found = False
break
if is_found:
rval = d
break
return rval
if __name__ == '__main__':
# Tests
dicts = []
keys = 'spam eggs shrubbery knight'.split()
start = 0
for _ in range(4):
dct = {k: v for k, v in zip(keys, range(start, start+4))}
dicts.append(dct)
start += 4
# Find each dict based on 'spam' key only.
for x in range(len(dicts)):
spam = x*4
assert find_dict_in_list(dicts, spam=spam) == dicts[x]
# Find each dict based on 'spam' and 'shrubbery' keys.
for x in range(len(dicts)):
spam = x*4
assert find_dict_in_list(dicts, spam=spam, shrubbery=spam+2) == dicts[x]
# Search for one correct key, one incorrect key:
for x in range(len(dicts)):
spam = x*4
assert find_dict_in_list(dicts, spam=spam, shrubbery=spam+1) is None
# Search for non-existent dict.
for x in range(len(dicts)):
spam = x+100
assert find_dict_in_list(dicts, spam=spam) is None
I met the problem because of the primary key generation is wrong,when I insert a row like this:
public void addTerminal(String typeOfDevice,Map<Byte,Integer> map) {
// TODO Auto-generated method stub
try {
Set<Byte> keySet = map.keySet();
for (Byte byte1 : keySet) {
Device device=new Device();
device.setNumDevice(DeviceCount.map.get(byte1));
device.setTimestamp(System.currentTimeMillis());
device.setTypeDevice(byte1);
this.getHibernateTemplate().save(device);
}
System.out.println("hah");
}catch (Exception e) {
// TODO: handle exception
logger.warn("wrong");
logger.warn(e.getStackTrace()+e.getMessage());
}
}
I change the id generator class to identity
<id name="id" type="int">
<column name="id" />
<generator class="identity" />
</id>
I like this one: it - vec.begin()
, because to me it clearly says "distance from beginning". With iterators we're used to thinking in terms of arithmetic, so the -
sign is the clearest indicator here.
First some code, then the explanaition. The official docs describing this are here.
import { trigger, transition, animate, style } from '@angular/animations'
@Component({
...
animations: [
trigger('slideInOut', [
transition(':enter', [
style({transform: 'translateY(-100%)'}),
animate('200ms ease-in', style({transform: 'translateY(0%)'}))
]),
transition(':leave', [
animate('200ms ease-in', style({transform: 'translateY(-100%)'}))
])
])
]
})
In your template:
<div *ngIf="visible" [@slideInOut]>This element will slide up and down when the value of 'visible' changes from true to false and vice versa.</div>
I found the angular way a bit tricky to grasp, but once you understand it, it quite easy and powerful.
The animations part in human language:
->then animate the translateY value until we are at 0%, where the element would naturally be.
When the element is removed, animate the translateY value (currently 0), to -100% (off screen).
The easing function we're using is ease-in, in 200 milliseconds, you can change that to your liking.
Hope this helps!
Try to replace the \n
with %0A
just like you have spaces replaced with %20
.
Incorrect:
SELECT * FROM customers WHERE name LIKE '%Bob Smith%';
Instead:
select count(*)
from rearp.customers c
where c.name LIKE '%Bob smith.8%';
select count
will just query (totals)
C
will link the db.table to the names row you need this to index
LIKE
should be obvs
8
will call all references in DB 8 or less (not really needed but i like neatness)
When you call another .bat file, I think you need "call" in front of the call:
call otherCommand.bat
create or replace procedure pro_ss(v_str varchar2) as
v_str1 varchar2(100);
v_comma_pos number := 0;
v_start_pos number := 1;
begin
loop
v_comma_pos := instr(v_str,',',v_start_pos);
if v_comma_pos = 0 then
v_str1 := substr(v_str,v_start_pos);
dbms_output.put_line(v_str1);
exit;
end if;
v_str1 := substr(v_str,v_start_pos,(v_comma_pos - v_start_pos));
dbms_output.put_line(v_str1);
v_start_pos := v_comma_pos + 1;
end loop;
end;
/
call pro_ss('aa,bb,cc,dd,ee,ff,gg,hh,ii,jj');
outout: aa bb cc dd ee ff gg hh ii jj
flex: 1
means the following:
flex-grow : 1; ? The div will grow in same proportion as the window-size
flex-shrink : 1; ? The div will shrink in same proportion as the window-size
flex-basis : 0; ? The div does not have a starting value as such and will
take up screen as per the screen size available for
e.g:- if 3 divs are in the wrapper then each div will take 33%.
Here is an example that uses scipy.optimize to fit a non-linear functions like a Gaussian, even when the data is in a histogram that isn't well ranged, so that a simple mean estimate would fail. An offset constant also would cause simple normal statistics to fail ( just remove p[3] and c[3] for plain gaussian data).
from pylab import *
from numpy import loadtxt
from scipy.optimize import leastsq
fitfunc = lambda p, x: p[0]*exp(-0.5*((x-p[1])/p[2])**2)+p[3]
errfunc = lambda p, x, y: (y - fitfunc(p, x))
filename = "gaussdata.csv"
data = loadtxt(filename,skiprows=1,delimiter=',')
xdata = data[:,0]
ydata = data[:,1]
init = [1.0, 0.5, 0.5, 0.5]
out = leastsq( errfunc, init, args=(xdata, ydata))
c = out[0]
print "A exp[-0.5((x-mu)/sigma)^2] + k "
print "Parent Coefficients:"
print "1.000, 0.200, 0.300, 0.625"
print "Fit Coefficients:"
print c[0],c[1],abs(c[2]),c[3]
plot(xdata, fitfunc(c, xdata))
plot(xdata, ydata)
title(r'$A = %.3f\ \mu = %.3f\ \sigma = %.3f\ k = %.3f $' %(c[0],c[1],abs(c[2]),c[3]));
show()
Output:
A exp[-0.5((x-mu)/sigma)^2] + k
Parent Coefficients:
1.000, 0.200, 0.300, 0.625
Fit Coefficients:
0.961231625289 0.197254597618 0.293989275502 0.65370344131
Following code works..
datePickerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog(0);
}
});
@Override
@Deprecated
protected Dialog onCreateDialog(int id) {
return new DatePickerDialog(this, datePickerListener, year, month, day);
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
day = selectedDay;
month = selectedMonth;
year = selectedYear;
datePickerButton.setText(selectedDay + " / " + (selectedMonth + 1) + " / "
+ selectedYear);
}
};
I created a file called test.py
and ran it on the interpreter. You may change what you want to, to test for sure how things is going on behind the scenes.
import dis
def func1():
matchesIterator = None
if matchesIterator:
print( "On if." );
def func2():
matchesIterator = None
if matchesIterator is not None:
print( "On if." );
print( "\nFunction 1" );
dis.dis(func1)
print( "\nFunction 2" );
dis.dis(func2)
This is the assembler difference:
Source:
>>> import importlib
>>> reload( test )
Function 1
6 0 LOAD_CONST 0 (None)
3 STORE_FAST 0 (matchesIterator)
8 6 LOAD_FAST 0 (matchesIterator)
9 POP_JUMP_IF_FALSE 20
10 12 LOAD_CONST 1 ('On if.')
15 PRINT_ITEM
16 PRINT_NEWLINE
17 JUMP_FORWARD 0 (to 20)
>> 20 LOAD_CONST 0 (None)
23 RETURN_VALUE
Function 2
14 0 LOAD_CONST 0 (None)
3 STORE_FAST 0 (matchesIterator)
16 6 LOAD_FAST 0 (matchesIterator)
9 LOAD_CONST 0 (None)
12 COMPARE_OP 9 (is not)
15 POP_JUMP_IF_FALSE 26
18 18 LOAD_CONST 1 ('On if.')
21 PRINT_ITEM
22 PRINT_NEWLINE
23 JUMP_FORWARD 0 (to 26)
>> 26 LOAD_CONST 0 (None)
29 RETURN_VALUE
<module 'test' from 'test.py'>
$('#pagedwn').bind("click", function () {
$('html, body').animate({ scrollTop:3031 },"fast");
return false;
});
This solution worked for me. It is working in Page Scroll Down fastly.
something like so might work:
<script type="text/javascript">
$(document).ready(function(){
var $input = $("<input name='myField' type='text'>");
$('#section2').append($input);
});
</script>
<form>
<div id="section1"><!-- some controls--></div>
<div id="section2"><!-- for dynamic controls--></div>
</form>
IMHO, this looks better:
Chess *array = malloc(size * sizeof(Chess)); // array of pointers of size `size`
for ( int i =0; i < SOME_VALUE; ++i )
{
array[i] = (Chess) malloc(sizeof(Chess));
}
I've seen 3 other fixes so far:
The solution boils down to clean up the .metadata folder with correct contents
SWT was created as a response to the sluggishness of Swing around the turn of the century. Now that the differences in performance are becoming negligable, I think Swing is a better option for your standard applications. SWT/Eclipse has a nice framework which helps with a lot of boiler plate code.
I've had the same problem, our work environment is based on Eclipse Java projects, and we needed to build automatically an ANT file so that we could use a continuous integration server (Jenkins, in our case).
We rolled out our own Eclipse Java to Ant tool, which is now available on GitHub:
To use it, call:
java -jar ant-build-for-java.jar <folder with repositories> [<.userlibraries file>]
The first argument is the folder with the repositories. It will search the folder recursively for any .project
file. The tool will create a build.xml
in the given folder.
Optionally, the second argument can be an exported .userlibraries file, from Eclipse, needed when any of the projects use Eclipse user libraries. The tool was tested only with user libraries using relative paths, it's how we use them in our repo. This implies that JARs and other archives needed by projects are inside an Eclipse project, and referenced from there.
The tool only supports dependencies from other Eclipse projects and from Eclipse user libraries.
This is because PHP uses the period character .
for string concatenation, not the plus character +
. Therefore to append to a string you want to use the .=
operator:
for ($i=1;$i<=100;$i++)
{
$selectBox .= '<option value="' . $i . '">' . $i . '</option>';
}
$selectBox .= '</select>';
First load select dropdown and then selectize it. It will work with normal $(select).val().
You can call the method newLine()
provided by java, to insert the new line in to a file.
For more refernce -http://download.oracle.com/javase/1.4.2/docs/api/java/io/BufferedWriter.html#newLine()
Detecting mobile devices
Related answer: https://stackoverflow.com/a/13805337/1306809
There's no single approach that's truly foolproof. The best bet is to mix and match a variety of tricks as needed, to increase the chances of successfully detecting a wider range of handheld devices. See the link above for a few different options.
You can use Object.values():
The
Object.values()
method returns an array of a given object's own enumerable property values, in the same order as that provided by afor...in
loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
and then use the indexOf() method:
The
indexOf()
method returns the first index at which a given element can be found in the array, or -1 if it is not present.
For example:
Object.values(obj).indexOf("test`") >= 0
A more verbose example is below:
var obj = {_x000D_
"a": "test1",_x000D_
"b": "test2"_x000D_
}_x000D_
_x000D_
_x000D_
console.log(Object.values(obj).indexOf("test1")); // 0_x000D_
console.log(Object.values(obj).indexOf("test2")); // 1_x000D_
_x000D_
console.log(Object.values(obj).indexOf("test1") >= 0); // true_x000D_
console.log(Object.values(obj).indexOf("test2") >= 0); // true _x000D_
_x000D_
console.log(Object.values(obj).indexOf("test10")); // -1_x000D_
console.log(Object.values(obj).indexOf("test10") >= 0); // false
_x000D_
set scrolling="no"
attribute in your iframe.
The question does not contain a nested loop, just a single loop. But THIS nested version works, too:
# for i in c d; do for j in a b; do echo $i $j; done; done
c a
c b
d a
d b
This has been fully answered here.
See Oracle's docs on SELECT to see how subquery factoring works, and Mark's example:
WITH employee AS (SELECT * FROM Employees)
SELECT * FROM employee WHERE ID < 20
UNION ALL
SELECT * FROM employee WHERE Sex = 'M'
As a general way to handle error in a loop like your sample code, I would rather use:
on error resume next
for each...
'do something that might raise an error, then
if err.number <> 0 then
...
end if
next ....
Make sure that the value of the column is really NULL and not an empty string or 0.
You can also do something like this...
<input @input="myHandler('foo', 'bar', ...arguments)">
Evan You himself recommended this technique in one post on Vue forum. In general some events may emit more than one argument. Also as documentation states internal variable $event is meant for passing original DOM event.
I'd consider passing your IDs as an XML string, and then you could shred the XML into a temp table to join against, or you could also query against the XML directly using SP_XML_PREPAREDOCUMENT and OPENXML.
Just add !
before an exclusion rule.
According to the gitignore man page:
Patterns have the following format:
...
- An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.
If you take a look at @types/node-fetch you will see the body definition
export class Body {
bodyUsed: boolean;
body: NodeJS.ReadableStream;
json(): Promise<any>;
json<T>(): Promise<T>;
text(): Promise<string>;
buffer(): Promise<Buffer>;
}
That means that you could use generics in order to achieve what you want. I didn't test this code, but it would looks something like this:
import { Actor } from './models/actor';
fetch(`http://swapi.co/api/people/1/`)
.then(res => res.json<Actor>())
.then(res => {
let b:Actor = res;
});
The main difference is not what can be modified by the trigger, that depends on the DBMS. A trigger (row or statement level) may modify one or many rows*, of the same or other tables as well and may have cascading effects (trigger other actions/triggers) but all these depend on the DBMS of course.
The main difference is how many times the trigger is activated. Imagine you have a 1M rows table and you run:
UPDATE t
SET columnX = columnX + 1
A statement-level trigger will be activated once (and even if no rows are updated). A row-level trigger will be activated a million times, once for every updated row.
Another difference is the order or activation. For example in Oracle the 4 different types of triggers will be activated in the following order:
Before the triggering statement executes
Before each row that the triggering statement affects
After each row that the triggering statement affects
After the triggering statement executes
In the previous example, we'd have something like:
Before statement-level trigger executes
Before row-level trigger executes
One row is updated
After row-level trigger executes
Before row-level trigger executes
Second row is updated
After row-level trigger executes
...
Before row-level trigger executes
Millionth row is updated
After row-level trigger executes
After statement-level trigger executes
Addendum
* Regarding what rows can be modified by a trigger: Different DBMS have different limitations on this, depending on the specific implementation or triggers in the DBMS. For example, Oracle may show a "mutating table" errors for some cases, e.g. when a row-level trigger selects from the whole table (SELECT MAX(col) FROM tablename
) or if it modifies other rows or the whole table and not only the row that is related to / triggered from.
It is perfectly valid of course for a row-level trigger (in Oracle or other) to modify the row that its change has triggered it and that is a very common use. Example in dbfiddle.uk.
Other DBMS may have different limitations on what any type of trigger can do and even what type of triggers are offered (some do not have BEFORE
triggers for example, some do not have statement level triggers at all, etc).
As I said in your previous question, there is no need to base64 encode the string, it will only make the program slower. Just use the repr
>>> with open("images/image.gif", "rb") as fin:
... image_data=fin.read()
...
>>> with open("image.py","wb") as fout:
... fout.write("image_data="+repr(image_data))
...
Now the image is stored as a variable called image_data
in a file called image.py
Start a fresh interpreter and import the image_data
>>> from image import image_data
>>>
Couple of comments (at least for APIs >= 21) which I found out from my experience and gave me headaches:
http
and https
urls are different. Setting a cookie for http://www.example.com
is different than setting a cookie for https://www.example.com
https://www.example.com/
works but https://www.example.com
does not work.CookieManager.getInstance().setCookie
is performing an asynchronous operation. So, if you load a url right away after you set it, it is not guaranteed that the cookies will have already been written. To prevent unexpected and unstable behaviours, use the CookieManager#setCookie(String url, String value, ValueCallback callback) (link) and start loading the url after the callback will be called.I hope my two cents save some time from some people so you won't have to face the same problems like I did.
You want to use absolute positioning.
An absolute position element is positioned relative to the first parent element that has a position other than static. If no such element is found, the containing block is html
For instance :
.yourDiv{
position:absolute;
top: 123px;
}
To get it to work, the parent needs to be relative (position:relative
)
In your case this should do the trick:
.suggestionsBox{position:absolute; top:40px;}
#specific_locations_add{position:relative;}
I spent ages trying to fix this. Every solution talks about 'setting options'. I don't know what that means. Finally, I figured it out. You can just include a commented out line at the top of the file /*jshint esversion: 6 */
.
Technically you only need to run ls -lR *.py | md5sum
. Unless you are worried about someone modifying the files and touching them back to their original dates and never changing the files' sizes, the output from ls
should tell you if the file has changed. My unix-foo is weak so you might need some more command line parameters to get the create time and modification time to print. ls
will also tell you if permissions on the files have changed (and I'm sure there are switches to turn that off if you don't care about that).
Add following command in Dockerfile:
RUN apt-get update
To remove a timezone (tzinfo) from a datetime object:
# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)
If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.
# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')
# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime
# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)
Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime
object to insert into the database. The solution is to convert your datetime.datetime
object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime
objects where one is timezone aware and another is timezone naive.
##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')
arrowDt = arrowObj.to("utc").datetime
# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)
# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()
# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3
# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True
To get the rest of the string after the second instance of the space delimiter
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX('Sachin ramesh tendulkar', ' ', 1), ' ', -1) AS first_name,
SUBSTRING_INDEX(SUBSTRING_INDEX('Sachin ramesh tendulkar', ' ', 2), ' ', -1)
AS middle_name,
SUBSTRING('Sachin ramesh tendulkar',LENGTH(SUBSTRING_INDEX('Sachin ramesh tendulkar', ' ', 2))+1) AS last_name
Session.Abandon()
destroys the session and the Session_OnEnd event is triggered.
Session.Clear()
just removes all values (content) from the Object. The session with the same key is still alive.
So, if you use Session.Abandon()
, you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.
Use Session.Clear()
, if you want that the user remaining in the same session (if you don't want the user to relogin for example) and reset all the session specific data.
The API can't be loaded after the document has finished loading by default, you'll need to load it asynchronous.
modify the page with the map:
<div id="map_canvas" style="height: 354px; width:713px;"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize"></script>
<script>
var directionsDisplay,
directionsService,
map;
function initialize() {
var directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var mapOptions = { zoom:7, mapTypeId: google.maps.MapTypeId.ROADMAP, center: chicago }
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
directionsDisplay.setMap(map);
}
</script>
For more details take a look at: https://stackoverflow.com/questions/14184956/async-google-maps-api-v3-undefined-is-not-a-function/14185834#14185834
The call to InitializeComponent()
(which is usually called in the default constructor of at least Window
and UserControl
) is actually a method call to the partial class of the control (rather than a call up the object hierarchy as I first expected).
This method locates a URI to the XAML for the Window
/UserControl
that is loading, and passes it to the System.Windows.Application.LoadComponent()
static method. LoadComponent()
loads the XAML file that is located at the passed in URI, and converts it to an instance of the object that is specified by the root element of the XAML file.
In more detail, LoadComponent
creates an instance of the XamlParser
, and builds a tree of the XAML. Each node is parsed by the XamlParser.ProcessXamlNode()
. This gets passed to the BamlRecordWriter
class. Some time after this I get a bit lost in how the BAML is converted to objects, but this may be enough to help you on the path to enlightenment.
Note: Interestingly, the InitializeComponent
is a method on the System.Windows.Markup.IComponentConnector
interface, of which Window
/UserControl
implement in the partial generated class.
Hope this helps!
select your table -> view dependencies -> Objects that depend on
An epoch reference date is a point on the timeline from which we count time. Moments before that point are counted with a negative number, moments after are counted with a positive number.
Why is 1 January 1970 00:00:00 considered the epoch time?
No, not the epoch, an epoch. There are many epochs in use.
This choice of epoch is arbitrary.
Major computers systems and libraries use any of at least a couple dozen various epochs. One of the most popular epochs is commonly known as Unix Time, using the 1970 UTC moment you mentioned.
While popular, Unix Time’s 1970 may not be the most common. Also in the running for most common would be January 0, 1900 for countless Microsoft Excel & Lotus 1-2-3 spreadsheets, or January 1, 2001 used by Apple’s Cocoa framework in over a billion iOS/macOS machines worldwide in countless apps. Or perhaps January 6, 1980 used by GPS devices?
Different systems use different granularity in counting time.
Even the so-called “Unix Time” varies, with some systems counting whole seconds and some counting milliseconds. Many database such as Postgres use microseconds. Some, such as the modern java.time framework in Java 8 and later, use nanoseconds. Some use still other granularities.
Because there is so much variance in the use of an epoch reference and in the granularities, it is generally best to avoid communicating moments as a count-from-epoch. Between the ambiguity of epoch & granularity, plus the inability of humans to perceive meaningful values (and therefore miss buggy values), use plain text instead of numbers.
The ISO 8601 standard provides an extensive set of practical well-designed formats for expressing date-time values as text. These formats are easy to parse by machine as well as easy to read by humans across cultures.
These include:
2019-01-23
2019-01-23T12:34:56.123456Z
2019-01-23T18:04:56.123456+05:30
2019-234
I ended up here looking to delete my node_modules
folders before doing a backup of my work in progress using rsync
. A key requirements is that the node_modules
folder can be nested, so you need the -prune
option.
First I ran this to visually verify the folders to be deleted:
find -type d -name node_modules -prune
Then I ran this to delete them all:
find -type d -name node_modules -prune -exec rm -rf {} \;
Thanks to pistache
Most of the time you can't - depending on the host. You can contact the support team where your hosting is subscribed to, and if they confirmed that it is really not allowed, you can just set up the composer on your dev machine, and commit and push all dependencies to your live server using Git or whatever you prefer.
Reference Resolution is described by RFC 3986 Uniform Resource Identifier (URI): Generic Syntax. And that is exactly how it supposed to work. To preserve base URI path you need to add slash at the end of the base URI and remove slash at the beginning of relative URI.
If base URI contains non-empty path, merge procedure discards it's last part (after last /
). Relevant section:
5.2.3. Merge Paths
The pseudocode above refers to a "merge" routine for merging a relative-path reference with the path of the base URI. This is accomplished as follows:
If the base URI has a defined authority component and an empty path, then return a string consisting of "/" concatenated with the reference's path; otherwise
return a string consisting of the reference's path component appended to all but the last segment of the base URI's path (i.e., excluding any characters after the right-most "/" in the base URI path, or excluding the entire base URI path if it does not contain any "/" characters).
If relative URI starts with a slash, it is called a absolute-path relative URI. In this case merge procedure ignore all base URI path. For more information check 5.2.2. Transform References section.
Try this one for data...
function get_album_data() {
$this->db->select ( 'album.*,cat.*,s_track.*' )
->from ( 'albums as album' );
->join ( 'categories cat', 'cat.cat_id = album.cat_id')
->join ( 'soundtracks s_tracks ', 's_tracks.album_id = album.album_id');
$query = $this->db->get ();
return $query->result ();
}
while for datum try this...
function get_album_datum($album_id) {
$this->db->select ( 'album.*,cat.*,s_track.*' )
->from ( 'albums as album' );
->join ( 'categories cat', 'cat.cat_id = album.cat_id')
->join ( 'soundtracks s_tracks ', 's_tracks.album_id = album.album_id');
$this->db->where ( 'album.album_id', $album_id);
$query = $this->db->get ();
return $query->row();
}7
855788
Use m.toString()
or String.valueOf(m)
. String.valueOf uses toString() but is null safe.
Try to capitalize 'app' like
const App = props => {...}
export default App;
In React, components need to be capitalized, and custom hooks need to start with use
.
Strong typing probably means that variables have a well-defined type and that there are strict rules about combining variables of different types in expressions. For example, if A is an integer and B is a float, then the strict rule about A+B might be that A is cast to a float and the result returned as a float. If A is an integer and B is a string, then the strict rule might be that A+B is not valid.
Static typing probably means that types are assigned at compile time (or its equivalent for non-compiled languages) and cannot change during program execution.
Note that these classifications are not mutually exclusive, indeed I would expect them to occur together frequently. Many strongly-typed languages are also statically-typed.
And note that when I use the word 'probably' it is because there are no universally accepted definitions of these terms. As you will already have seen from the answers so far.
After spending half a day with nothing working. Using a header check service though everything was working. The firewall at work was stripping them
I know this question has already been answered, but another option is simply to open the destination and source folders in Finder and then drag and drop them into the terminal. The paths will automatically be copied and properly formatted (thus negating the need to actually figure out proper file names/extensions).
I have to do over-network copies between Mac and Windows machines, sometimes fairly deep down in filetrees, and have found this the most effective way to do so.
So, as an example:
cp -r [drag and drop source folder from finder] [drag and drop destination folder from finder]
similar to R0byn's experience, i was experimenting with a Powerpoint slide presentation and dumped out the main body of text on the slide, finding that all the places where one would typically find carriage return (ASCII 13/0x0d/^M) or line feed/new line (ASCII 10/0x0a/^J) characters, it uses vertical tab (ASCII 11/0x0b/^K) instead, presumably for the exact reason that dan04 described above for Word: to serve as a "newline" while staying within the same paragraph. good question though as i totally thought this character would be as useless as a teletype terminal today.
If you want to see the array as an array, you can say
alert(JSON.stringify(aCustomers));
instead of all those document.write
s.
However, if you want to display them cleanly, one per line, in your popup, do this:
alert(aCustomers.join("\n"));
That is only possible if that site has declared anchors in the page. It is done by giving a tag a name or id attribute, so look for any of those close to where you want to link to.
And then the syntax would be
<a href="page.html#anchor">text</a>
If you want to display some buttons with actions when an list item is swipe are a lot of libraries on the internet that have this behavior. I implemented the library that I found on the internet and I am very satisfied. It is very simple to use and very quick. I improved the original library and I added a new click listener for item click. Also I added font awesome library (http://fortawesome.github.io/Font-Awesome/) and now you can simply add a new item title and specify the icon name from font awesome.
Here is the github link
Try this,
x in mylist
is better and more readable than x in mylist[:]
and your len(x)
should be equal to 3
.
>>> mylist = [[1,2,3],[4,5,6,7],[8,9,10]]
>>> for x in mylist:
... if len(x)==3:
... print x
...
[1, 2, 3]
[8, 9, 10]
or if you need more pythonic use list-comprehensions
>>> [x for x in mylist if len(x)==3]
[[1, 2, 3], [8, 9, 10]]
>>>
Make sure your account uses IIS 7. For more information, see Customizing IIS Settings on Your Windows Hosting Account. Follow the instructions in Changing Pipeline Mode on Your Windows IIS 7 Hosting Account. Select Integrated Pipeline Mode. In your Project References section, set Copy Local to True for the following assemblies:
System.Web.Abstractions
System.Web.Helpers
System.Web.Routing
System.Web.Mvc
System.Web.WebPages
Add the following assemblies to your project, and then set Copy Local to True:
Microsoft.Web.Infrastructure
System.Web.Razor
System.Web.WebPages.Deployment
System.Web.WebPages.Razor
Publish your application.
"2.7.0_bf4fda703454".split("_")
gives a list of strings:
In [1]: "2.7.0_bf4fda703454".split("_")
Out[1]: ['2.7.0', 'bf4fda703454']
This splits the string at every underscore. If you want it to stop after the first split, use "2.7.0_bf4fda703454".split("_", 1)
.
If you know for a fact that the string contains an underscore, you can even unpack the LHS and RHS into separate variables:
In [8]: lhs, rhs = "2.7.0_bf4fda703454".split("_", 1)
In [9]: lhs
Out[9]: '2.7.0'
In [10]: rhs
Out[10]: 'bf4fda703454'
An alternative is to use partition()
. The usage is similar to the last example, except that it returns three components instead of two. The principal advantage is that this method doesn't fail if the string doesn't contain the separator.
Since I've already been where you are right now, I think I can "answer" you.
The fact is there is no easy way to make a GUI. GUI's are highly dependent on platform and OS specific code, that's why you should start reading your target platform/OS documentation on window management APIs. The good thing is: there are plenty of libraries that address these limitations and abstract architecture differences into a single multi-platform API. Those suggested before, GTK and Qt, are some of these libraries.
But even these are a little too complicated, since lots of new concepts, data types, namespaces and classes are introduced, all at once. For this reason, they use to come bundled with some GUI WYSIWYG editor. They pretty much make programming software with GUIs possible.
To sum it up, there are also non free "environments" for GUI development such as Visual Studio from Microsoft. For those with Delphi experience backgrounds, Visual Studio may be more familiar. There are also free alternatives to the full Visual Studio environment supplied from Microsoft: Visual Studio Express, which is more than enough for starting on GUI development.
This task can be accomplished using one of the android's main building block named as Intents and One of the methods public void startActivity (Intent intent)
which belongs to your Activity class.
An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.
An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed.
Refer the official docs -- http://developer.android.com/reference/android/content/Intent.html
public void startActivity (Intent intent)
-- Used to launch a new activity.
So suppose you have two Activity class --
PresentActivity -- This is your current activity from which you want to go the second activity.
NextActivity -- This is your next Activity on which you want to move.
So the Intent would be like this
Intent(PresentActivity.this, NextActivity.class)
Finally this will be the complete code
public class PresentActivity extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.content_layout_id);
final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Intent activityChangeIntent = new Intent(PresentActivity.this, NextActivity.class);
// currentContext.startActivity(activityChangeIntent);
PresentActivity.this.startActivity(activityChangeIntent);
}
});
}
}
As per the PHP manual - parse_url should not be used to validate a URL.
Unfortunately, it seems that filter_var('example.com', FILTER_VALIDATE_URL)
does not perform any better.
Both parse_url()
and filter_var()
will pass malformed URLs such as http://...
Therefore in this case - regex is the better method.
REPLACE INTO
pros:
cons:
too slow.
auto-increment key will CHANGE(increase by 1) if there is entry matches unique key
or primary key
, because it deletes the old entry then insert new one.
INSERT IGNORE
pros:
cons:
auto-increment key will not change if there is entry matches unique key
or primary key
but auto-increment index will increase by 1
some other errors/warnings will be ignored such as data conversion error.
INSERT ... ON DUPLICATE KEY UPDATE
pros:
cons:
looks relatively complex if you just want to insert not update.
auto-increment key will not change if there is entry matches unique key
or primary key
but auto-increment index will increase by 1
unique key
or primary key
?As mentioned in the comment below by @toien: "auto-increment column will be effected depends on innodb_autoinc_lock_mode
config after version 5.1" if you are using innodb
as your engine, but this also effects concurrency, so it needs to be well considered before used. So far I'm not seeing any better solution.
jQuery .height
will return you the height of the element. It doesn't need CSS definition as it determines the computed height.
You can use .height()
, .innerHeight()
or outerHeight()
based on what you need.
.height()
- returns the height of element excludes padding, border and margin.
.innerHeight()
- returns the height of element includes padding but excludes border and margin.
.outerHeight()
- returns the height of the div including border but excludes margin.
.outerHeight(true)
- returns the height of the div including margin.
Check below code snippet for live demo. :)
$(function() {_x000D_
var $heightTest = $('#heightTest');_x000D_
$heightTest.html('Div style set as "height: 180px; padding: 10px; margin: 10px; border: 2px solid blue;"')_x000D_
.append('<p>Height (.height() returns) : ' + $heightTest.height() + ' [Just Height]</p>')_x000D_
.append('<p>Inner Height (.innerHeight() returns): ' + $heightTest.innerHeight() + ' [Height + Padding (without border)]</p>')_x000D_
.append('<p>Outer Height (.outerHeight() returns): ' + $heightTest.outerHeight() + ' [Height + Padding + Border]</p>')_x000D_
.append('<p>Outer Height (.outerHeight(true) returns): ' + $heightTest.outerHeight(true) + ' [Height + Padding + Border + Margin]</p>')_x000D_
});
_x000D_
div { font-size: 0.9em; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="heightTest" style="height: 150px; padding: 10px; margin: 10px; border: 2px solid blue; overflow: hidden; ">_x000D_
</div>
_x000D_
It's pretty simple. Pay attention and you'll get it right away! :)
You will create a html array, which will be then sent to php array. Your html code will look like this:
<input type="checkbox" name="check_list[1]" alt="Checkbox" value="checked">
<input type="checkbox" name="check_list[2]" alt="Checkbox" value="checked">
<input type="checkbox" name="check_list[3]" alt="Checkbox" value="checked">
Where [1] [2] [3]
are the ID
s of your messages, meaning that you will echo
your $row['Report ID']
in their place.
Then, when you submit the form, your PHP array will look like this:
print_r($check_list)
[1] => checked
[3] => checked
Depending on which were checked and which were not.
I'm sure you can continue from this point forward.
Jerryf's answer is fine, except for one flaw.
The onload event should be set before the src. Sometimes the src can be loaded instantly and never fire the onload event.
(Like Totty.js pointed out.)
var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");
var image = new Image();
image.onload = function() {
ctx.drawImage(image, 0, 0);
};
image.src = "data:image/ png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
You can think of an iframe as an embedded browser window that you can put on an HTML page to show another URL inside it. This URL can be totally distinct from your web site/app.
You can put an iframe in any HTML page, so you could put one inside a contentplaceholder in a webform that has a Masterpage and it will appear with whatever URL you load into it (via Javascript, or C# if you turn your iframe into a server-side control (runat='server'
) on the final HTML page that your webform produces when requested.
And you can load a URL into your iframe that is a .aspx
page.
But - iframes have nothing to do with the ASP.net mechanism. They are HTML elements that can be made to run server-side, but they are essentially 'dumb' and unmanaged/unconnected to the ASP.Net mechanisms - don't confuse a Contentplaceholder with an iframe.
Incidentally, the use of iframes is still contentious - do you really need to use one? Can you afford the negative trade-offs associated with them e.g. lack of navigation history ...?
public static byte[] serialize(Object obj) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(out);
os.writeObject(obj);
return out.toByteArray();
}
public static Object deserialize(byte[] data) throws IOException, ClassNotFoundException {
ByteArrayInputStream in = new ByteArrayInputStream(data);
ObjectInputStream is = new ObjectInputStream(in);
return is.readObject();
}
I encountered the same error message but don't have any access to the table like "dba_free_space" because I am not a dba. I use some previous answers to check available space and I still have a lot of space. However, after reducing the full table scan as many as possible. The problem is solved. My guess is that Oracle uses temp table to store the full table scan data. It the data size exceeds the limit, it will show the error. Hope this helps someone with the same issue
I’ve been going back and forth between
1.
<a href="tel:5551231234">
2.
<meta name="format-detection" content="telephone=no">
Trying to make the same code work for desktop and iPhone. The problem was that if the first option is used and you click it from a desktop browser it gives an error message, and if the second one is used it disables the tab-to-call functionality on iPhone iOS5.
So I tried and tried and it turned out that iPhone treats the phone number as a special type of link that can be formatted with CSS as one. I wrapped the number in an address tag (it would work with any other HTML tag, just try avoiding <a>
tag) and styled it in CSS as
.myDiv address a {color:#FFF; font-style: normal; text-decoration:none;}
and it worked - in a desktop browser showed a plain text and in a Safari mobile showed as a link with the Call/Cancel window popping up on tab and without the default blue color and underlining.
Just be careful with the css rules applied to the number especially when using padding/margin.
Like this:
std::string s("Test string");
std::string::iterator it = s.begin();
//Use the iterator...
++it;
//...
std::cout << "index is: " << std::distance(s.begin(), it) << std::endl;
I have made somthink like this for one of my website accualy in developpement.
I have used StepCarousel for the caroussel because it's the only one I found that can accept different image size in the same carrousel.
In addition to this to add the touch swipe effect, I have used jquery.touchswipe plugin;
And stepcarousel move panel rigth or left with a fonction so I can make :
$("#slider-actu").touchwipe({
wipeLeft: function() {stepcarousel.stepBy('slider-actu', 3);},
wipeRight: function() {stepcarousel.stepBy('slider-actu', -3);},
min_move_x: 20
});
You can view the actual render at this page
Hope that help you.
shape()
consists of array having two arguments rows and columns.
if you search shape[0]
then it will gave you the number of rows.
shape[1]
will gave you number of columns.
Here's simple solution for those who want a quick filter against an object:
<select>
<option ng-repeat="card in deck.Cards | filter: {Type: 'Face'}">{{card.Name}}</option>
</select>
The array filter lets you mimic the object you are trying to filter. In the above case, the following classes would work just fine:
var card = function(name, type) {
var _name = name;
var _type = type;
return {
Name: _name,
Type: _type
};
};
And where the deck might look like:
var deck = function() {
var _cards = [new card('Jack', 'Face'),
new card('7', 'Numeral')];
return {
Cards: _cards
};
};
And if you want to filter multiple properties of the object just separate field names by a comma:
<select>
<option ng-repeat="card in deck.Cards | filter: {Type: 'Face', Name: 'Jack'}">{{card.Name}}</option>
</select>
EDIT: Here's a working plnkr that provides an example of single and multiple property filters:
In my case this issue caused because my local machine used to the one MySQL service installed earlier at 3006 port. Thus I modified both my.ini (C:\xampp\mysql\bin\my.ini) and php.ini (C:\xampp\php\php.ini) files replaced port 3006 to 3008
After that I've created a new service running the command described above by Tommer:
sc.exe create "mysqlweb" binPath= "C:\xampp\mysql\bin\mysqld.exe --defaults-file=c:\xampp\mysql\bin\my.ini mysqlweb"
may be you can write like this:
#graphic {
background-image: url(image.jpg);
background-position: 0 -50px;
width: 200px;
height: 100px;
}
Here is a really simple implementation of an assert function. It takes a value and a description of what you are testing.
function assert(value, description) {
var result = value ? "pass" : "fail";
console.log(result + ' - ' + description);
};
If the value evaluates to true it passes.
assert (1===1, 'testing if 1=1');
If it returns false it fails.
assert (1===2, 'testing if 1=1');
For those lost souls on google, using numpy.expand_dims
then numpy.repeat
will work, and will also work in higher dimensional cases (i.e. multiplying a shape (10, 12, 3) by a (10, 12)).
>>> import numpy
>>> a = numpy.array([[1,2,3],[4,5,6],[7,8,9]])
>>> b = numpy.array([0,1,2])
>>> b0 = numpy.expand_dims(b, axis = 0)
>>> b0 = numpy.repeat(b0, a.shape[0], axis = 0)
>>> b1 = numpy.expand_dims(b, axis = 1)
>>> b1 = numpy.repeat(b1, a.shape[1], axis = 1)
>>> a*b0
array([[ 0, 2, 6],
[ 0, 5, 12],
[ 0, 8, 18]])
>>> a*b1
array([[ 0, 0, 0],
[ 4, 5, 6],
[14, 16, 18]])
Below Python packages are to be downloaded and installed to their default locations.
1.1. Python-2.7.x.
1.2. Numpy.
1.3. Matplotlib (Matplotlib is optional, but recommended since we use it a lot in our tutorials).
Install all packages into their default locations. Python will be installed to C:/Python27/.
After installation, open Python IDLE. Enter import numpy and make sure Numpy is working fine.
Download latest OpenCV release from sourceforge site and double-click to extract it.
Goto opencv/build/python/2.7 folder.
Copy cv2.pyd to C:/Python27/lib/site-packeges.
Open Python IDLE and type following codes in Python terminal.
import cv2 print cv2.version If the results are printed out without any errors, congratulations !!! You have installed OpenCV-Python successfully.
I have quickly made a function that can achieve this, it may not be the best way to do this but it simply works and should be cross browser, please also know that i am NOT a expert in JavaScript so any tips are great :)
function createElement(){
var element = document.createElement(arguments[0]),
text = arguments[1],
attr = arguments[2],
append = arguments[3],
appendTo = arguments[4];
for(var key = 0; key < Object.keys(attr).length ; key++){
var name = Object.keys(attr)[key],
value = attr[name],
tempAttr = document.createAttribute(name);
tempAttr.value = value;
element.setAttributeNode(tempAttr)
}
if(append){
for(var _key = 0; _key < append.length; _key++) {
element.appendChild(append[_key]);
}
}
if(text) element.appendChild(document.createTextNode(text));
if(appendTo){
var target = appendTo === 'body' ? document.body : document.getElementById(appendTo);
target.appendChild(element)
}
return element;
}
lets see how we make this
<select name="drop1" id="Select1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
here's how it works
var options = [
createElement('option', 'Volvo', {value: 'volvo'}),
createElement('option', 'Saab', {value: 'saab'}),
createElement('option', 'Mercedes', {value: 'mercedes'}),
createElement('option', 'Audi', {value: 'audi'})
];
createElement('select', null, // 'select' = name of element to create, null = no text to insert
{id: 'Select1', name: 'drop1'}, // Attributes to attach
[options[0], options[1], options[2], options[3]], // append all 4 elements
'body' // append final element to body - this also takes a element by id without the #
);
this is the params
createElement('tagName', 'Text to Insert', {any: 'attribute', here: 'like', id: 'mainContainer'}, [elements, to, append, to, this, element], 'body || container = where to append this element');
This function would suit if you have to append many element, if there is any way to improve this answer please let me know.
edit:
Here is a working demo
This can be highly customized to suit your project!
As Hogan notes above, use an AND
instead of &
. See this tutorial for more info.
A quick search on the conda official docs will help you to find what each flag does.
So far:
-y
: Do not ask for confirmation.-f
: I think it should be --file
, so it read package versions from the given file.-q
: Do not display progress bar.-c
: Additional channel to search for packages. These are URLs searched in the orderTo avoid reflection you could set up a Dictionary with your propery names as keys and functions in the dictionary value part that return the corresponding values from the properties that you request.
Java 8 has a new concept called “Effectively final” variable. It means that a non-final local variable whose value never changes after initialization is called “Effectively Final”.
This concept was introduced because prior to Java 8, we could not use a non-final local variable in an anonymous class. If you wanna have access to a local variable in anonymous class, you have to make it final.
When lambda was introduced, this restriction was eased. Hence to the need to make local variable final if it’s not changed once it is initialized as lambda in itself is nothing but an anonymous class.
Java 8 realized the pain of declaring local variable final every time a developer used lambda, introduced this concept, and made it unnecessary to make local variables final. So if you see the rule for anonymous classes has not changed, it’s just you don’t have to write the final
keyword every time when using lambdas.
I found a good explanation here
This article explains in detail how to find the reason for last startup/shutdown. In my case, this was due to windows SCCM pushing updates even though I had it disabled locally. Visit the article for full details with pictures. For reference, here are the steps copy/pasted from the website:
Press the Windows + R keys to open the Run dialog, type
eventvwr.msc
, and press Enter.If prompted by UAC, then click/tap on Yes (Windows 7/8) or Continue (Vista).
In the left pane of Event Viewer, double click/tap on Windows Logs to expand it, click on System to select it, then right click on System, and click/tap on Filter Current Log.
Do either step 5 or 6 below for what shutdown events you would like to see.
To See the Dates and Times of All User Shut Downs of the Computer
A) In Event sources, click/tap on the drop down arrow and check the
USER32
box.B) In the All Event IDs field, type
1074
, then click/tap on OK.C) This will give you a list of power off (shutdown) and restart Shutdown Type of events at the top of the middle pane in Event Viewer.
D) You can scroll through these listed events to find the events with power off as the Shutdown Type. You will notice the date and time, and what user was responsible for shutting down the computer per power off event listed.
E) Go to step 7.
To See the Dates and Times of All Unexpected Shut Downs of the Computer
A) In the All Event IDs field, type
6008
, then click/tap on OK.B) This will give you a list of unexpected shutdown events at the top of the middle pane in Event Viewer. You can scroll through these listed events to see the date and time of each one.
Sorry that was a typo. You can either add node_modules to the end of your user's global path variable, or maybe check the permissions associated with that folder (node _modules). The error doesn't seem like the last case, but I've encountered problems similar to yours. I find the first solution enough for most cases. Just go to environment variables and add the path to node_modules to the last part of your user's path variable. Note I'm saying user and not system.
Just add a semicolon to the end of the variable declaration and add the static path to your node_module folder. ( Ex c:\path\to\node_module)
Alternatively you could:
In your CMD
PATH=%PATH%;C:\\path\to\node_module
EDIT
The last solution will work as long as you don't close your CMD. So, use the first solution for a permanent change.
Absolutely not. Misusing them though... that is bad.
Mindlessly removing them for the sake of is just that... mindless. Unless you know the advanatages and disadvantages, it is best to steer clear and do as you have been taught/learned, but there is nothing implicitly wrong with global variables. When you understand the pros and cons better make your own decision.
I tried this for to clear Image and DrawableCache in ImageView
ImgView.setImageBitmap(null);
ImgView.destroyDrawingCache();
I hope this works for you !
I was solved this problem too: Just reinstall node to LTS version by nvm:
nvm install --lts
nvm use --lts
Then rm -rf node_modules
And npm i
you can also use: s.lower() in str.lower()
Based on Stack Overflow questions Unix cut, remove first token and https://stackoverflow.com/a/15903654/781312:
(octal=$(echo -n ? | od -t o1 | head -1 | cut -d' ' -f2- | sed -e 's#\([0-9]\+\) *#\\0\1#g')
echo Octal representation is following $octal
echo -e "$octal")
Output is the following.
Octal representation is following \0342\0230\0240
?
You can't, and you shouldn't. That's what polymorphism is for, so that each object has its own way of doing some "base" things.
First of all you can do it with left:50% to center it relative to parent div but for that you need to learn CSS positioning.
One possible solution from many is to do something like
div.parent { text-align:center; } //will center align every thing in this div as well as in the children element
div.parent div { text-align:left;} //to restore so every thing would start from left
if your your div to be centered is positioned relatively, you can just do
.mydiv { position:relative; margin:0 auto; }
If you are writing a scraper and really don't care about the SSL certificate you can set it global:
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
DO NOT USE IN PRODUCTION
If you parse the JSON with eval
, you're allowing the string being parsed to contain absolutely anything, so instead of just being a set of data, you could find yourself executing function calls, or whatever.
Also, JSON's parse
accepts an aditional parameter, reviver, that lets you specify how to deal with certain values, such as datetimes (more info and example in the inline documentation here)
I don't think you can design the if-then-else construct without taking the design for other constructs into account. I think it's a good principle that each expression should be an element, and its subexpressions should be child elements. There are then questions about whether the name of an element should reflect the type of expression it is, or its role relative to the parent. Or you can do both:
<if>
<condition>
<equals>
<number>2</number>
<number>3</number>
<equals>
<condition>
<then>
<string>Mary</string>
</then>
<else>
<concat>
<string>John</string>
<string>Smith</string>
</concat>
</else>
</if>
But you can sometimes get away with a design that omits the role-names (condition, then else) and relies on positional significance of elements relative to their parent. It depends a bit on how much you want to keep it concise.
To get this to work I had to combine many of the above answers, to anyone who this might help here is my much simpler process.
If you have Windows 10 just start typing "edit environmental..." and it'll pop up right away. Click path and Edit… then paste the ;C:\Program Files\Git\bin\git.exe;C:\Program Files\Git\cmd
at the end of the path already there, don't forget the ; to separate your new github path from the current path.
You do not need the guid but if you want to know how to find it open bash, type git --man-path
You can do it using xml as well:
<field name="acmeOne" type="string" column="acmeOne" length="36">
<options>
<option name="comment">Your SQL field comment goes here.</option>
<option name="default">Default Value</option>
</options>
</field>
If you pass a variable data
(dictionary type) as context to a template, then you code should be:
{% for key, value in data.items %}
<p>{{ key }} : {{ value }}</p>
{% endfor %}
I'm using node modules copy-to module to create a single file to require all the files in our NodeJS-based system.
The code for our utility file looks like this:
/**
* Module dependencies.
*/
var copy = require('copy-to');
copy(require('./module1'))
.and(require('./module2'))
.and(require('./module3'))
.to(module.exports);
In all of the files, most functions are written as exports, like so:
exports.function1 = function () { // function contents };
exports.function2 = function () { // function contents };
exports.function3 = function () { // function contents };
So, then to use any function from a file, you just call:
var utility = require('./utility');
var response = utility.function2(); // or whatever the name of the function is
Solve jQuery $.cookie is not a function this Problem jquery cdn update in solve this problem
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30=" crossorigin="anonymous"></script>
This will remove all listeners from children but will be slow for large pages. Brutally simple to write.
element.outerHTML = element.outerHTML;
I believe that you are looking for the java.lang.BigDecimal class.
Your first problem is that you are passing -3 to the 2nd parameter of Columns.Add. It needs to be -2 for it to auto-size the column. Source: http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.columns.aspx (look at the comments on the code example at the bottom)
private void initListView()
{
// Add columns
lvRegAnimals.Columns.Add("Id", -2,HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Name", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Age", -2, HorizontalAlignment.Left);
}
You can also use the other overload, Add(string). E.g:
lvRegAnimals.Columns.Add("Id");
lvRegAnimals.Columns.Add("Name");
lvRegAnimals.Columns.Add("Age");
Reference for more overloads: http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.columnheadercollection.aspx
Second, to add items to the ListView, you need to create instances of ListViewItem and add them to the listView's Items collection. You will need to use the string[] constructor.
var item1 = new ListViewItem(new[] {"id123", "Tom", "24"});
var item2 = new ListViewItem(new[] {person.Id, person.Name, person.Age});
lvRegAnimals.Items.Add(item1);
lvRegAnimals.Items.Add(item2);
You can also store objects in the item's Tag property.
item2.Tag = person;
And then you can extract it
var person = item2.Tag as Person;
Let me know if you have any questions and I hope this helps!
This should be (condition)? True statement : False statement
Leave out the "if"
You suggested "Catching any unexpected errors and return some error code signaling "unexpected situation" " but couldn't find an appropriate error code.
Guess what: That's what 5xx is there for.
you can use this code inside col-md-3 , col-md-9
.col-side-right{
flex: 0 0 20% !important;
max-width: 20%;
}
.col-side-left{
flex: 0 0 80%;
max-width: 80%;
}
Typically you'll need cookies to log into a site, which means cookielib, urllib and urllib2. Here's a class which I wrote back when I was playing Facebook web games:
import cookielib
import urllib
import urllib2
# set these to whatever your fb account is
fb_username = "[email protected]"
fb_password = "secretpassword"
class WebGamePlayer(object):
def __init__(self, login, password):
""" Start up... """
self.login = login
self.password = password
self.cj = cookielib.CookieJar()
self.opener = urllib2.build_opener(
urllib2.HTTPRedirectHandler(),
urllib2.HTTPHandler(debuglevel=0),
urllib2.HTTPSHandler(debuglevel=0),
urllib2.HTTPCookieProcessor(self.cj)
)
self.opener.addheaders = [
('User-agent', ('Mozilla/4.0 (compatible; MSIE 6.0; '
'Windows NT 5.2; .NET CLR 1.1.4322)'))
]
# need this twice - once to set cookies, once to log in...
self.loginToFacebook()
self.loginToFacebook()
def loginToFacebook(self):
"""
Handle login. This should populate our cookie jar.
"""
login_data = urllib.urlencode({
'email' : self.login,
'pass' : self.password,
})
response = self.opener.open("https://login.facebook.com/login.php", login_data)
return ''.join(response.readlines())
You won't necessarily need the HTTPS or Redirect handlers, but they don't hurt, and it makes the opener much more robust. You also might not need cookies, but it's hard to tell just from the form that you've posted. I suspect that you might, purely from the 'Remember me' input that's been commented out.
Yes, use getScript instead of document.write - it will even allow for a callback once the file loads.
You might want to check if TinyMCE is defined, though, before including it (for subsequent calls to 'Add Comment') so the code might look something like this:
$('#add_comment').click(function() {
if(typeof TinyMCE == "undefined") {
$.getScript('tinymce.js', function() {
TinyMCE.init();
});
}
});
Assuming you only have to call init
on it once, that is. If not, you can figure it out from here :)
For Android API level 13 and you need to use this:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int maxX = size.x;
int maxY = size.y;
Then (0,0) is top left corner and (maxX,maxY) is bottom right corner of the screen.
The 'getWidth()' for screen size is deprecated since API 13
Furthermore getwidth() and getHeight() are methods of android.view.View class in android.So when your java class extends View class there is no windowManager overheads.
int maxX=getwidht();
int maxY=getHeight();
as simple as that.
You can split on an empty string:
var chars = "overpopulation".split('');
If you just want to access a string in an array-like fashion, you can do that without split
:
var s = "overpopulation";
for (var i = 0; i < s.length; i++) {
console.log(s.charAt(i));
}
You can also access each character with its index using normal array syntax. Note, however, that strings are immutable, which means you can't set the value of a character using this method, and that it isn't supported by IE7 (if that still matters to you).
var s = "overpopulation";
console.log(s[3]); // logs 'r'
I had a similar problem with height except my chart was inside a bootstrap modal popup, which I'm already controlling the size of with css. However, for some reason when the window was resized horizontally the height of the chart container would expand indefinitely. If you were to drag the window back and forth it would expand vertically indefinitely. I also don't like hard-coded height/width solutions.
So, if you're doing this in a modal, combine this solution with a window resize event.
// from link
$('#ChartModal').on('show.bs.modal', function() {
$('.chart-container').css('visibility', 'hidden');
});
$('#ChartModal').on('shown.bs.modal.', function() {
$('.chart-container').css('visibility', 'initial');
$('#chartbox').highcharts().reflow()
//added
ratio = $('.chart-container').width() / $('.chart-container').height();
});
Where "ratio" becomes a height/width aspect ratio, that will you resize when the bootstrap modal resizes. This measurement is only taken when he modal is opened. I'm storing ratio as a global but that's probably not best practice.
$(window).on('resize', function() {
//chart-container is only visible when the modal is visible.
if ( $('.chart-container').is(':visible') ) {
$('#chartbox').highcharts().setSize(
$('.chart-container').width(),
($('.chart-container').width() / ratio),
doAnimation = true );
}
});
So with this, you can drag your screen to the side (resizing it) and your chart will maintain its aspect ratio.
Widescreen
vs smaller
(still fiddling around with vw units, so everything in the back is too small to read lol!)
Another way to do this without revert (traces of undo):
Don't do it if someone else has pushed other commits
Create a backup of your branch, being in your branch my-branch
. So in case something goes wrong, you can restart the process without losing any work done.
git checkout -b my-branch-temp
Go back to your branch.
git checkout my-branch
Reset, to discard your last commit (to undo it):
git reset --hard HEAD^
Remove the branch on remote (ex. origin
remote).
git push origin :my-branch
Repush your branch (without the unwanted commit) to the remote.
git push origin my-branch
Done!
I hope that helps! ;)
You can make master
point at 1258f0d0aae
this way:
git checkout master
git reset --hard 1258f0d0aae
But you have to be careful about doing this. It may well rewrite the history of that branch. That would create problems if you have published it and other people are working on the branch.
Also, the git reset --hard
command will throw away any uncommitted changes (i.e. those just in your working tree or the index).
You can also force an update to a branch with:
git branch -f master 1258f0d0aae
... but git won't let you do that if you're on master
at the time.
You want to check the result of scanf() to make sure there was a successful conversion; if there wasn't, then one of three things is true:
Example:
int moreData = 1;
...
printf("Input no: ");
fflush(stdout);
/**
* Loop while moreData is true
*/
while (moreData)
{
errno = 0;
int itemsRead = scanf("%f", &input);
if (itemsRead == 1)
{
printf("Output: %f\n", input);
printf("Input no: ");
fflush(stdout);
}
else
{
if (feof(stdin))
{
printf("Hit EOF on stdin; exiting\n");
moreData = 0;
}
else if (ferror(stdin))
{
/**
* I *think* scanf() sets errno; if not, replace
* the line below with a regular printf() and
* a generic "read error" message.
*/
perror("error during read");
moreData = 0;
}
else
{
printf("Bad character stuck in input stream; clearing to end of line\n");
while (getchar() != '\n')
; /* empty loop */
printf("Input no: ");
fflush(stdout);
}
}
You can use:
UPDATE s SET
s.Field1 = q.Field1,
s.Field2 = q.Field2,
(list of fields...)
FROM (
SELECT Field1, Field2, (list of fields...)
FROM ProfilerTest.dbo.BookingDetails
WHERE MyID=@MyID
) q
WHERE s.MyID2=@ MyID2
Create an AJAX postback method which writes a CSV file to your webserver and returns the url.. Set a hidden IFrame in the browser to the location of the CSV file on the server.
Your user will then be presented with the CSV download link.
$day_number = date('N', $date);
This will return a 1 for Monday to 7 for Sunday, for the date that is stored in $date. Omitting the second argument will cause date() to return the number for the current day.
I used the following to upgrade git on mac.
hansi$ brew install git
hansi$ git --version
git version 2.19.0
hansi$ brew install git
Warning: git 2.25.1 is already installed, it's just not linked
You can use `brew link git` to link this version.
hansi$ brew link git
Linking /usr/local/Cellar/git/2.25.1...
Error: Could not symlink bin/git
Target /usr/local/bin/git
already exists. You may want to remove it:
rm '/usr/local/bin/git'
To force the link and overwrite all conflicting files:
brew link --overwrite git
To list all files that would be deleted:
brew link --overwrite --dry-run git
hansi$ brew link --overwrite git
Linking /usr/local/Cellar/git/2.25.1... 205 symlinks created
hansi$ git --version
git version 2.25.1
Try this:
Pattern p = Pattern.compile(?<=\\<(any_tag)\\>)(\\s*.*\\s*)(?=\\<\\/(any_tag)\\>);
Matcher m = p.matcher(anyString);
For example:
String str = "<TR> <TD>1Q Ene</TD> <TD>3.08%</TD> </TR>";
Pattern p = Pattern.compile("(?<=\\<TD\\>)(\\s*.*\\s*)(?=\\<\\/TD\\>)");
Matcher m = p.matcher(str);
while(m.find()){
Log.e("Regex"," Regex result: " + m.group())
}
Output:
10 Ene
3.08%
Check out the contents of your array with
echo '<pre>' . print_r( $arr, TRUE ) . '</pre>';
1) Setting the first Panel:
JFrame frame=new JFrame();
frame.getContentPane().add(new JPanel());
2)Replacing the panel:
frame.getContentPane().removeAll();
frame.getContentPane().add(new JPanel());
Also notice that you must do this in the Event's Thread, to ensure this use the SwingUtilities.invokeLater or the SwingWorker
My approach is to store the PID to a file in /tmp, and to find the right process using the -S
option for ssh
. That might be a misuse but works for me.
#!/bin/bash
TARGET_REDIS=${1:-redis.someserver.com}
PROXY="proxy.somewhere.com"
LOCAL_PORT=${2:-6379}
if [ "$1" == "stop" ] ; then
kill `cat /tmp/sshTunel${LOCAL_PORT}-pid`
exit
fi
set -x
ssh -f -i ~/.ssh/aws.pem centos@$PROXY -L $LOCAL_PORT:$TARGET_REDIS:6379 -N -S /tmp/sshTunel$LOCAL_PORT ## AWS DocService dev, DNS alias
# SSH_PID=$! ## Only works with &
SSH_PID=`ps aux | grep sshTunel${LOCAL_PORT} | grep -v grep | awk '{print $2}'`
echo $SSH_PID > /tmp/sshTunel${LOCAL_PORT}-pid
Better approach might be to query for the SSH_PID
right before killing it, since the file might be stale and it would kill a wrong process.
Project Rebuild solved my problem.
In Android studio in the toolbar.. Build>Rebuild Project.
I had exactly the same problem and found the solution eventually. My query runs like:
$result = mysqli_query($link,'SELECT * FROM clients WHERE ' . $sql_where . ' AND ' . $sql_where2 . ' ORDER BY acconame ASC ');
In order to display the sql command, all I had to do was to create a variable ($resultstring) with the exact same content as my query and then echo it, like this:<?php echo $resultstring = 'SELECT * FROM clients WHERE ' . $sql_where . ' AND ' . $sql_where2 . ' ORDER BY acconame ASC '; ?>
It works!
I think this post by Rex St John is very useful for unit testing with android studio.
(source: rexstjohn.com)
In addition to the ioctl() method Filip demonstrated you can use getifaddrs(). There is an example program at the bottom of the man page.
Firstly, your "messy way" is ok, there's nothing wrong with using indices into the dataframe, and this will not be too slow. iterrows() itself isn't terribly fast.
A version of your first idea that would work would be:
row_iterator = df.iterrows()
_, last = row_iterator.next() # take first item from row_iterator
for i, row in row_iterator:
print(row['value'])
print(last['value'])
last = row
The second method could do something similar, to save one index into the dataframe:
last = df.irow(0)
for i in range(1, df.shape[0]):
print(last)
print(df.irow(i))
last = df.irow(i)
When speed is critical you can always try both and time the code.
You could use @JsonIgnoreProperties(value = { "handler", "hibernateLazyInitializer" })
annotation on your class "Director"
Simple: e.g. if div id 'mydiv'
jQuery.fancybox.open({href: "#mydiv"});
This also makes JS code functional which is inside div.
USE Database_Name
select name,recovery_model_desc from sys.databases
ALTER DATABASE Database_Name SET RECOVERY simple
DBCC SHRINKFILE (Database_Name_log , 1)
I got same issue in Visual Studio 2017 and TFS 2017. DefaultCollection must be mapped first to you local path. Somehow this step was skipped and I got only MyFirstProject mapped.
All you need to do is:
- 1. Go to your TFS web page and remove the project from the server.
- 2. Remove the project from your local "Worksapces"
- 3. Go to "Manage Connections" which will refresh your Home page in TeamExplorer.
- 4. You will get Configuration page which will allow you to setup root path to your DefaultCollection.
- 5. You should get message that it been done successfully. Now you can create your project.
It's important to map root of your collection to your workspace first and then map a new project.
log4j2 has a very flexible configuration system (which IMHO is more a distraction than a help), you can even use JSON. See https://logging.apache.org/log4j/2.x/manual/configuration.html for a reference.
Personally, I just recently started using log4j2, but I'm tending toward the "strict XML" configuration (that is, using attributes instead of element names), which can be schema-validated.
Here is my simple example using autoconfiguration and strict mode, using a "Property" for setting the filename:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration monitorinterval="30" status="info" strict="true">
<Properties>
<Property name="filename">log/CelsiusConverter.log</Property>
</Properties>
<Appenders>
<Appender type="Console" name="Console">
<Layout type="PatternLayout" pattern="%d %p [%t] %m%n" />
</Appender>
<Appender type="Console" name="FLOW">
<Layout type="PatternLayout" pattern="%C{1}.%M %m %ex%n" />
</Appender>
<Appender type="File" name="File" fileName="${filename}">
<Layout type="PatternLayout" pattern="%d %p %C{1.} [%t] %m%n" />
</Appender>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="File" />
<AppenderRef ref="Console" />
<!-- Use FLOW to trace down exact method sending the msg -->
<!-- <AppenderRef ref="FLOW" /> -->
</Root>
</Loggers>
</Configuration>
I had the same problem with Apache and PHP 5.5.
In php.ini
, I had the following lines:
error_reporting E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT
display_errors Off
instead of the following:
error_reporting=E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT
display_errors=Off
(the =
sign was missing)
Example for OUT : Variable gets value initialized after going into the method. Later the same value is returned to the main method.
namespace outreftry
{
class outref
{
static void Main(string[] args)
{
yyy a = new yyy(); ;
// u can try giving int i=100 but is useless as that value is not passed into
// the method. Only variable goes into the method and gets changed its
// value and comes out.
int i;
a.abc(out i);
System.Console.WriteLine(i);
}
}
class yyy
{
public void abc(out int i)
{
i = 10;
}
}
}
Output:
10
===============================================
Example for Ref : Variable should be initialized before going into the method. Later same value or modified value will be returned to the main method.
namespace outreftry
{
class outref
{
static void Main(string[] args)
{
yyy a = new yyy(); ;
int i = 0;
a.abc(ref i);
System.Console.WriteLine(i);
}
}
class yyy
{
public void abc(ref int i)
{
System.Console.WriteLine(i);
i = 10;
}
}
}
Output:
0 10
=================================
Hope its clear now.
If DB is SQL Server then
select Convert(varchar(10),CONVERT(date,YourDateColumn,106),103)
When using aggregate functions to filter, you must use a HAVING statement.
SELECT *
FROM tblMoney
HAVING Sum(CASH) > 500
You could use On Error Resume Next
then there is no need to loop through all the sheets in the workbook.
With On Error Resume Next
the errors are not propagated, but are suppressed instead. So here when the sheets does't exist or when for any reason can't be deleted, nothing happens. It is like when you would say : delete this sheets, and if it fails I don't care. Excel is supposed to find the sheet, you will not do any searching.
Note: When the workbook would contain only those two sheets, then only the first sheet will be deleted.
Dim book
Dim sht as Worksheet
set book= Workbooks("SomeBook.xlsx")
On Error Resume Next
Application.DisplayAlerts=False
Set sht = book.Worksheets("ID Sheet")
sht.Delete
Set sht = book.Worksheets("Summary")
sht.Delete
Application.DisplayAlerts=True
On Error GoTo 0
You can stick optional whitespace characters \s*
in between every other character in your regex. Although granted, it will get a bit lengthy.
/cats/
-> /c\s*a\s*t\s*s/
You can run:
ps -ft pts/6 -t pts/9 -t pts/10
This would produce an output similar to:
UID PID PPID C STIME TTY TIME CMD
Vidya 772 2701 0 15:26 pts/6 00:00:00 bash
Vidya 773 2701 0 16:26 pts/9 00:00:00 bash
Vidya 774 2701 0 17:26 pts/10 00:00:00 bash
Grab the PID
from the result.
Use the PIDs to kill the processes:
kill <PID1> <PID2> <PID3> ...
For the above example:
kill 772 773 774
If the process doesn't gracefully terminate, just as a last option you can forcefully kill by sending a SIGKILL
kill -9 <PID>
You forgot to put z as an bind variable.
The following EXECUTE command runs a PL/SQL statement that references a stored procedure:
SQL> EXECUTE -
> :Z := EMP_SALE.HIRE('JACK','MANAGER','JONES',2990,'SALES')
Note that the value returned by the stored procedure is being return into :Z
If you have php installed on your local machine try:
$ php -a
Interactive shell
php > phpinfo();
If you want more granularity and better decription, you could use NotImplementedException from commons-lang
Warning: Available before versions 2.6 and after versions 3.2, only.
1) Add On Error Resume Next
at top of the page
2) Add following code at bottom of the page
If Err.Number <> 0 Then
Response.Write (Err.Description)
Response.End
End If
On Error GoTo 0
You need to set with only C:\Program Files\Java\jdk1.8.0_12.
And check with using new cmd. It will be updated
one liner to download latest maven artifact without mvn:
curl -O -J -L "https://repository.sonatype.org/service/local/artifact/maven/content?r=central-proxy&g=io.staticcdn.sdk&a=staticcdn-sdk-standalone-optimizer&e=zip&v=LATEST"
If you can use repeated letters, you can use the *
operator:
>>> 'a'*5
'aaaaa'
I had a similar issue trying to fix the item size to fit the background image width. This worked (at least with Firefox 35) for me :
.navcontainer-top li
{
display: inline-block;
background: url("../images/nav-button.png") no-repeat;
width: 117px;
height: 26px;
}
On Windows it's holding down Alt while box selecting. Once you have your selection then attempt your edit.
The best way is to use spyOnProperty
. It expects 3 parameters and you need to pass get
or set
as a third param.
const div = fixture.debugElement.query(By.css('.ellipsis-overflow'));
// now mock properties
spyOnProperty(div.nativeElement, 'clientWidth', 'get').and.returnValue(1400);
spyOnProperty(div.nativeElement, 'scrollWidth', 'get').and.returnValue(2400);
Here I am setting the get
of clientWidth
of div.nativeElement
object.
To adapt @luke flournoy's brilliant answer - and if you're not using th
in your table, here's all the CSS you need to make a rounded table:
.my_table{
border-collapse: separate;
border-spacing: 0;
border: 1px solid grey;
border-radius: 10px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
}
.my_table tr:first-of-type {
border-top-left-radius: 10px;
}
.my_table tr:first-of-type td:last-of-type {
border-top-right-radius: 10px;
}
.my_table tr:last-of-type td:first-of-type {
border-bottom-left-radius: 10px;
}
.my_table tr:last-of-type td:last-of-type {
border-bottom-right-radius: 10px;
}
If you want to have text in the edit text and remove it like you say, try:
final EditText text_box = (EditText) findViewById(R.id.input_box);
text_box.setOnFocusChangeListener(new OnFocusChangeListener()
{
@Override
public void onFocusChange(View v, boolean hasFocus)
{
if (hasFocus==true)
{
if (text_box.getText().toString().compareTo("Enter Text")==0)
{
text_box.setText("");
}
}
}
});
Try following command if you using npm 5 and node 8
npm update --save
You may find an answer with this example : errorbar_demo_features.py
"""
Demo of errorbar function with different ways of specifying error bars.
Errors can be specified as a constant value (as shown in `errorbar_demo.py`),
or as demonstrated in this example, they can be specified by an N x 1 or 2 x N,
where N is the number of data points.
N x 1:
Error varies for each point, but the error values are symmetric (i.e. the
lower and upper values are equal).
2 x N:
Error varies for each point, and the lower and upper limits (in that order)
are different (asymmetric case)
In addition, this example demonstrates how to use log scale with errorbar.
"""
import numpy as np
import matplotlib.pyplot as plt
# example data
x = np.arange(0.1, 4, 0.5)
y = np.exp(-x)
# example error bar values that vary with x-position
error = 0.1 + 0.2 * x
# error bar values w/ different -/+ errors
lower_error = 0.4 * error
upper_error = error
asymmetric_error = [lower_error, upper_error]
fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)
ax0.errorbar(x, y, yerr=error, fmt='-o')
ax0.set_title('variable, symmetric error')
ax1.errorbar(x, y, xerr=asymmetric_error, fmt='o')
ax1.set_title('variable, asymmetric error')
ax1.set_yscale('log')
plt.show()
Which plots this:
There are three things to consider here:
Don't assume that the sd card is mounted at /sdcard
(May be true in the default case, but better not to hard code.). You can get the location of sdcard by querying the system:
Environment.getExternalStorageDirectory();
You have to inform Android that your application needs to write to external storage by adding a uses-permission entry in the AndroidManifest.xml file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
If this directory already exists, then mkdir is going to return false. So check for the existence of the directory, and then try creating it if it does not exist. In your component, use something like:
File folder = new File(Environment.getExternalStorageDirectory() + "/map");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
// Do something on success
} else {
// Do something else on failure
}
If you're using Entity Framework, you can extend the default timeout (to give a long-running query more time to complete) by doing:
myDbContext.Database.CommandTimeout = 300;
Where myDbContext
is your DbContext instance, and 300
is the timeout value in seconds.
(Syntax current as of Entity Framework 6.)
arrays:
malloc
);sizeof
(hence the common idiom sizeof(arr)/sizeof(*arr)
, that however fails silently when used inadvertently on a pointer);std::vector
:
&vec[0]
is guaranteed to work as expected);begin()
/end()
methods, the usual STL typedef
s, ...)Also consider the "modern alternative" to arrays - std::array
; I already described in another answer the difference between std::vector
and std::array
, you may want to have a look at it.
If a method only accesses local variables, it's thread safe. Is that it?
Absolultely not. You can write a program with only a single local variable accessed from a single thread that is nevertheless not threadsafe:
https://stackoverflow.com/a/8883117/88656
Does that apply for static methods as well?
Absolutely not.
One answer, provided by @Cybis, was: "Local variables cannot be shared among threads because each thread gets its own stack."
Absolutely not. The distinguishing characteristic of a local variable is that it is only visible from within the local scope, not that it is allocated on the temporary pool. It is perfectly legal and possible to access the same local variable from two different threads. You can do so by using anonymous methods, lambdas, iterator blocks or async methods.
Is that the case for static methods as well?
Absolutely not.
If a method is passed a reference object, does that break thread safety?
Maybe.
I've done some research, and there is a lot out there about certain cases, but I was hoping to be able to define, by using just a few rules, guidelines to follow to make sure a method is thread safe.
You are going to have to learn to live with disappointment. This is a very difficult subject.
So, I guess my ultimate question is: "Is there a short list of rules that define a thread-safe method?
Nope. As you saw from my example earlier an empty method can be non-thread-safe. You might as well ask "is there a short list of rules that ensures a method is correct". No, there is not. Thread safety is nothing more than an extremely complicated kind of correctness.
Moreover, the fact that you are asking the question indicates your fundamental misunderstanding about thread safety. Thread safety is a global, not a local property of a program. The reason why it is so hard to get right is because you must have a complete knowledge of the threading behaviour of the entire program in order to ensure its safety.
Again, look at my example: every method is trivial. It is the way that the methods interact with each other at a "global" level that makes the program deadlock. You can't look at every method and check it off as "safe" and then expect that the whole program is safe, any more than you can conclude that because your house is made of 100% non-hollow bricks that the house is also non-hollow. The hollowness of a house is a global property of the whole thing, not an aggregate of the properties of its parts.
https://www.tutorialrepublic.com/codelab.php?topic=faq&file=jquery-show-hide-div-using-select-box It's working well in my case
$(document).ready(function(){_x000D_
$("select").change(function(){_x000D_
$(this).find("option:selected").each(function(){_x000D_
var optionValue = $(this).attr("value");_x000D_
if(optionValue){_x000D_
$(".box").not("." + optionValue).hide();_x000D_
$("." + optionValue).show();_x000D_
} else{_x000D_
$(".box").hide();_x000D_
}_x000D_
});_x000D_
}).change();_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>jQuery Show Hide Elements Using Select Box</title>_x000D_
<style>_x000D_
.box{_x000D_
color: #fff;_x000D_
padding: 50px;_x000D_
display: none;_x000D_
margin-top: 10px;_x000D_
}_x000D_
.red{ background: #ff0000; }_x000D_
.green{ background: #228B22; }_x000D_
.blue{ background: #0000ff; }_x000D_
</style>_x000D_
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div>_x000D_
<select>_x000D_
<option>Choose Color</option>_x000D_
<option value="red">Red</option>_x000D_
<option value="green">Green</option>_x000D_
<option value="blue">Blue</option>_x000D_
</select>_x000D_
</div>_x000D_
<div class="red box">You have selected <strong>red option</strong> so i am here</div>_x000D_
<div class="green box">You have selected <strong>green option</strong> so i am here</div>_x000D_
<div class="blue box">You have selected <strong>blue option</strong> so i am here</div>_x000D_
</body>_x000D_
</html>
_x000D_
I'm not exactly sure where my problem was, but I believe it was because I was using the same global packages from both npm and Yarn.
I uninstalled all the npm global packages, then when using yarn commands once again, the problem was gone.
To see global packages installed...
for npm:
npm ls -g --depth=0
for Yarn:
yarn global list
I then uninstalled each package I saw in the npm listing, using:
npm uninstall -g <package-name>
Just an information: let us all remember that the Image
class is actually an abstract class and referencing a variable of this with a BufferedImage only stores or returns any Object's memory adress.
Also, wherefore, static java.awt.image.imageIO
's read()
method returns a BufferedImage
object, therefore no doubt that using operator/expression instanceof BufferedImage
on that object will return true
.
In fact, being abstract, Image
class has such method signatures as:
public abstract Graphics getGraphics()
public abstract ImageProducer getSource()
among others.
I emphasize, an actual Image
variable only holds memory adress of a concrete Image-subclass object, almost like pointers in C, C++, Ada, etc.
If you're introduced or advanced in those languages, and also of Java interface instances like Runnable
, javax.sound.Clip
, AWT's Shape
, etc.. . Take note that Image
has: public abstract Image getScaledInstance(...)
- you get the point. (Of course, scaling in 2D Graphics programming is interchangeable to resizing, for which precision is desirable).
But in an impossible case when herein ImageIO method return ! (instanceof BufferedImage)
just create a new BufferedImage
object with this ImgObjNotInstncfBufImg
apassed to one of its constructor argument. Then, at (rational) will manipulate this in the logic of your code.
Anyways, the Affine Transform class is appropriate for transforming Shapes and Images to thier scaled, rotated, relocated, etc forms, so I recommend you to study about using an "affine transform".
Take note that you can manipulate the actual pixels in such Image's Raster - well another technical 2D Graphics jargon which must be referenced from a technical glossary - which perhaps a excercised skill in Java ways of binary blitwise operations will be needed, in types of Image buffers that store individual color attributes in a compact in of 32-bytes - 7-bits each for the alpha and RGB values.
I suspect your gonna use it in layering images. So, FINALLY, the rational is that you only reference BufferedImage
with the abstract Image, and if ever your Image
object isn't a BufferedImage
one yet, then you can just make an image out of this related-but-non-BufferedImage-instance without having to worry about any conversion, casting, autoboxing or whatever; manipulating a BufferedImage really means manipulating also the underlying root Image data-bearing object that it points to.
Okay, finished; I think I certainly extracted and splintered out what deadlock you may have thought you are facing to. As I have said abstract classes in java, and also interfaces, are very much the equivaleng of the low-level, more-close-to-hardware operators called pointers in other languages.
Swift 5 version of Christopher's answer with extra usage sample
import UIKit
private class InsetTextField: UITextField {
var insets: UIEdgeInsets
init(insets: UIEdgeInsets) {
self.insets = insets
super.init(frame: .zero)
}
required init(coder aDecoder: NSCoder) {
fatalError("not intended for use from a NIB")
}
// placeholder position
override func textRect(forBounds bounds: CGRect) -> CGRect {
return super.textRect(forBounds: bounds.inset(by: insets))
}
// text position
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return super.editingRect(forBounds: bounds.inset(by: insets))
}
}
extension UITextField {
class func textFieldWithInsets(insets: UIEdgeInsets) -> UITextField {
return InsetTextField(insets: insets)
}
}
Usage: -
class ViewController: UIViewController {
private let passwordTextField: UITextField = {
let textField = UITextField.textFieldWithInsets(insets: UIEdgeInsets(top: 10, left: 15, bottom: 10, right: 15))
// ---
return textField
}()
}
I faced similar issue, and what I understand from Grega's answer is
object NOTworking extends App {
new testing().doIT
}
//adding extends Serializable wont help
class testing {
val list = List(1,2,3)
val rddList = Spark.ctx.parallelize(list)
def doIT = {
//again calling the fucntion someFunc
val after = rddList.map(someFunc(_))
//this will crash (spark lazy)
after.collect().map(println(_))
}
def someFunc(a:Int) = a+1
}
your doIT method is trying to serialize someFunc(_) method, but as method are not serializable, it tries to serialize class testing which is again not serializable.
So make your code work, you should define someFunc inside doIT method. For example:
def doIT = {
def someFunc(a:Int) = a+1
//function definition
}
val after = rddList.map(someFunc(_))
after.collect().map(println(_))
}
And if there are multiple functions coming into picture, then all those functions should be available to the parent context.
You might try this way:
fprintf('%s: (%i,%i,%i)\r\n','Answer',1,2,3)
I hope this helps.
public static string TruncateLongString(this string str, int maxLength)
{
return str.Length <= maxLength ? str : str.Remove(maxLength);
}
Nobody seems to have mentioned the -t option but that the easiest:
pip install -t <direct directory> <package>
//How decodeURIComponent Works
function proURIDecoder(val)
{
val=val.replace(/\+/g, '%20');
var str=val.split("%");
var cval=str[0];
for (var i=1;i<str.length;i++)
{
cval+=String.fromCharCode(parseInt(str[i].substring(0,2),16))+str[i].substring(2);
}
return cval;
}
document.write(proURIDecoder(window.location.href));