Empty lists evaluate to False in boolean contexts (such as if some_list:
).
mongod
defaults the database location to /data/db/
.
If you run ps -xa | grep mongod
and you don't see a --dbpath
which explicitly tells mongod
to look at that parameter for the db location and you don't have a dbpath
in your mongodb.conf
, then the default location will be: /data/db/
and you should look there.
What's the first part of your Subversion repository URL?
I can't guarantee the first four since it's possible to reconfigure everything to use different ports, of if you go through a proxy of some sort.
If you're using a VPN, you may have to configure your VPN client to reroute these to their correct ports. A lot of places don't configure their correctly VPNs to do this type of proxying. It's either because they have some sort of anal-retentive IT person who's being overly security conscious, or because they simply don't know any better. Even worse, they'll give you a client where this stuff can't be reconfigured.
The only way around that is to log into a local machine over the VPN, and then do everything from that system.
Did you try to chomp the $str1
and $str2
?
I found a similar issue with using (another) $str1
eq 'Y' and it only went away when I first did:
chomp($str1);
if ($str1 eq 'Y') {
....
}
works after that.
Hope that helps.
This one looks a bit nicer:
var rgb = $('#selector').css('backgroundColor').match(/\d+/g);
var r = parseInt(rgb[0], 10);
var g = parseInt(rgb[1], 10);
var b = parseInt(rgb[2], 10);
var hex = '#'+ r.toString(16) + g.toString(16) + b.toString(16);
a more succinct one-liner:
var rgb = $('#selector').css('backgroundColor').match(/\d+/g);
var hex = '#'+ Number(rgb[0]).toString(16) + Number(rgb[1]).toString(16) + Number(rgb[2]).toString(16);
forcing jQuery to always return hex:
$.cssHooks.backgroundColor = {
get: function(elem) {
if (elem.currentStyle)
var bg = elem.currentStyle["backgroundColor"];
else if (window.getComputedStyle) {
var bg = document.defaultView.getComputedStyle(elem,
null).getPropertyValue("background-color");
}
if (bg.search("rgb") == -1) {
return bg;
} else {
bg = bg.match(/\d+/g);
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(bg[0]) + hex(bg[1]) + hex(bg[2]);
}
}
}
Use the .replace
[MDN] function to replace the lowercase letters that begin a word with the capital letter.
var str = "hello world";_x000D_
str = str.toLowerCase().replace(/\b[a-z]/g, function(letter) {_x000D_
return letter.toUpperCase();_x000D_
});_x000D_
alert(str); //Displays "Hello World"
_x000D_
Edit: If you are dealing with word characters other than just a-z, then the following (more complicated) regular expression might better suit your purposes.
var str = "???? ????????? björn über ñaque a?fa";_x000D_
str = str.toLowerCase().replace(/^[\u00C0-\u1FFF\u2C00-\uD7FF\w]|\s[\u00C0-\u1FFF\u2C00-\uD7FF\w]/g, function(letter) {_x000D_
return letter.toUpperCase();_x000D_
});_x000D_
alert(str); //Displays "???? ????????? Björn Über Ñaque ??fa"
_x000D_
Because ... it (MILLISECONDS
) is a static field (hiding in an enumeration, but that's what it is) ... however it is being invoked upon an instance of the given type (but see below as this isn't really true1).
javac will "accept" that, but it should really be MyUnits.MILLISECONDS
(or non-prefixed in the applicable scope).
1 Actually, javac "rewrites" the code to the preferred form -- if m
happened to be null
it would not throw an NPE at run-time -- it is never actually invoked upon the instance).
Happy coding.
I'm not really seeing how the question title fits in with the rest :-) More accurate and specialized titles increase the likely hood the question/answers can benefit other programmers.
If your list of weighted choices is relatively static, and you want frequent sampling, you can do one O(N) preprocessing step, and then do the selection in O(1), using the functions in this related answer.
# run only when `choices` changes.
preprocessed_data = prep(weight for _,weight in choices)
# O(1) selection
value = choices[sample(preprocessed_data)][0]
I wanted to log all messages to root logger, and to have a separate log with errors, here is how it can be done:
<log4net>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="allMessages.log" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level %logger - %message%newline" />
</layout>
</appender>
<appender name="ErrorsFileAppender" type="log4net.Appender.FileAppender">
<file value="errorsLog.log" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level %logger - %message%newline" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="ERROR" />
<levelMax value="FATAL" />
</filter>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="FileAppender" />
<appender-ref ref="ErrorsFileAppender" />
</root>
</log4net>
Notice the use of filter element.
Since you probably want to keep 2FA enabled for your account, you can set up a ssh key and that way you won't need to type your Github credentials every time you want to push work to Github.
You can find all the ssh setup steps in the documentation. First, make sure you don't currently have any ssh keys (id_rsa.pub, etc.) with $ ls -al ~/.ssh
I faced to the same problem. I solved it by
HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\InstallPath
and edit the default key with the output of
C:\> where python.exe
command.HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\InstallPath\InstallGroup
and edit the default key with Python 3.4
Note: My python version is 3.4 and you need to replace 3.4 with your python version.
Normally you can find Registry entries for Python in HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\<version>
. You just need to copy those entries to HKEY_CURRENT_USER\Software\Python\PythonCore\<version>
I had this error because I have an old version of the DLL in the GAC of my server. So make sure everything is referenced correctly and that the assembly/GAC is up to date with the good dll.
The TextView resource id it needs is for a TextView layout file, so it won't be in the same activity.
You can create it by going to File > New > XML > XML Layout File, and enter the widget type, which is 'TextView' in the root tag field.
Source: https://www.kompulsa.com/the-simplest-way-to-implement-an-android-listview/
I solved my problem by running below command
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
The complete example with an array. Replace "constructArrayType()" by "constructCollectionType()" or any other type you need.
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
public class Sorting {
private String property;
private String direction;
public Sorting() {
}
public Sorting(String property, String direction) {
this.property = property;
this.direction = direction;
}
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
public String getDirection() {
return direction;
}
public void setDirection(String direction) {
this.direction = direction;
}
public static void main(String[] args) throws JsonParseException, IOException {
final String json = "[{\"property\":\"title1\", \"direction\":\"ASC\"}, {\"property\":\"title2\", \"direction\":\"DESC\"}]";
ObjectMapper mapper = new ObjectMapper();
Sorting[] sortings = mapper.readValue(json, TypeFactory.defaultInstance().constructArrayType(Sorting.class));
System.out.println(sortings);
}
}
Check out this snippet:
Private Sub openDialog()
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
' Set the title of the dialog box.
.Title = "Please select the file."
' Clear out the current filters, and add our own.
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls"
.Filters.Add "All Files", "*.*"
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox
End If
End With
End Sub
I think this is what you are asking for.
The Python package drawnow allows to update a plot in real time in a non blocking way.
It also works with a webcam and OpenCV for example to plot measures for each frame.
See the original post.
First we need to parse the JSON object and then we can add an item.
var str = '{"theTeam":[{"teamId":"1","status":"pending"},
{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(str);
obj['theTeam'].push({"teamId":"4","status":"pending"});
str = JSON.stringify(obj);
Finally we JSON.stringify the obj back to JSON
Use this:
string mystr = "PER 343573";
int number = Convert.ToInt32(mystr.Replace("PER ",""));
Loading the file from: {project}/src/main/webapp/WEB-INF/spring-dispatcher-servlet.xml
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring-dispatcher-servlet.xml" })
@WebAppConfiguration
public class TestClass {
@Test
public void test() {
// test definition here..
}
}
%~dp0 - return the path from where script executed
But, important to know also below one:
%CD% - return the current path in runtime, for example if you get into other folders using "cd folder1", and then "cd folder2", it will return the full path until folder2 and not the original path where script located
Use a seperate column to indicate the join condition
SELECT t.importid,
case
when t.importid = g.home
then 'home'
else 'away'
end as join_condition,
g.network,
g.date_start
FROM game g
INNER JOIN team t ON (t.importid = g.home OR t.importid = g.away)
ORDER BY date_start DESC
LIMIT 7
Just a note: for Anaconda install packages command:
It's not a matter of deep copy or shallow copy, none of what you're doing is deep copy.
Here:
>>> new = original
you're creating a new reference to the the list/dict referenced by original.
while here:
>>> new = original.copy()
>>> # or
>>> new = list(original) # dict(original)
you're creating a new list/dict which is filled with a copy of the references of objects contained in the original container.
You don't need both hibernate.cfg.xml
and persistence.xml
in this case. Have you tried removing hibernate.cfg.xml
and mapping everything in persistence.xml
only?
But as the other answer also pointed out, this is not okay like this:
@Id
@JoinColumn(name = "categoria")
private String id;
Didn't you want to use @Column
instead?
.NET can do it with its System.Speech namespace.
You would have to convert to .wav first or capture the audio live from the mic.
Details on implementation can be found here: Transcribing Audio with .NET
As I can see, you are comparing the message with the empty string using ==.
Its very hard to write the full code, but I can tell the flow of code - first, create db class & method inide that which will return the connection. second, create a servelet(ex-login.java) & import that db class onto that servlet. third, create instance of imported db class with the help of new operator & call the connection method of that db class. fourth, creaet prepared statement & execute statement & put this code in try catch block for exception handling.Use if-else condition in the try block to navigate your login page based on success or failure.
I hope, it will help you. If any problem, then please revert.
Nikhil Pahariya
The object your method decompressGZIP()
needs is a byte[]
.
So the basic, technical answer to the question you have asked is:
byte[] b = string.getBytes();
byte[] b = string.getBytes(Charset.forName("UTF-8"));
byte[] b = string.getBytes(StandardCharsets.UTF_8); // Java 7+ only
However the problem you appear to be wrestling with is that this doesn't display very well. Calling toString()
will just give you the default Object.toString()
which is the class name + memory address. In your result [B@38ee9f13
, the [B
means byte[]
and 38ee9f13
is the memory address, separated by an @
.
For display purposes you can use:
Arrays.toString(bytes);
But this will just display as a sequence of comma-separated integers, which may or may not be what you want.
To get a readable String
back from a byte[]
, use:
String string = new String(byte[] bytes, Charset charset);
The reason the Charset
version is favoured, is that all String
objects in Java are stored internally as UTF-16. When converting to a byte[]
you will get a different breakdown of bytes for the given glyphs of that String
, depending upon the chosen charset.
In Python2, input
is evaluated, input()
is equivalent to eval(raw_input())
. When you enter klj, Python tries to evaluate that name and raises an error because that name is not defined.
Use raw_input
to get a string from the user in Python2.
Demo 1: klj
is not defined:
>>> input()
klj
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'klj' is not defined
Demo 2: klj
is defined:
>>> klj = 'hi'
>>> input()
klj
'hi'
Demo 3: getting a string with raw_input
:
>>> raw_input()
klj
'klj'
You can't just fire up Python and check things, Django doesn't know what project you want to work on. You have to do one of these things:
python manage.py shell
django-admin.py shell --settings=mysite.settings
(or whatever settings module you use)DJANGO_SETTINGS_MODULE
environment variable in your OS to mysite.settings
(This is removed in Django 1.6) Use setup_environ
in the python interpreter:
from django.core.management import setup_environ
from mysite import settings
setup_environ(settings)
Naturally, the first way is the easiest.
I think its good to keep the Label and not to use placeholder as mentioned above. Its good for UX as explain here: https://www.smashingmagazine.com/2018/03/ux-contact-forms-essentials-conversions/
Here example with Label inside Input fields: codepen.io/jdax/pen/mEBJNa
As mentioned, for efficiency reasons sequential spaces are consolidated into one space the browser actually displays. Remember what the ML in HTML stand for. It's a Mark-up Language, designed to control how text is displayed.. not whitespace :p
Still, you can pretend the browser respects tabs since all the TAB does is prepend 4 spaces, and that's easy with CSS. either in line like ...
<div style="padding-left:4.00em;">Indenented text </div>
Or as a regular class in a style sheet
.tabbed {padding-left:4.00em;}
Then the HTML might look like
<p>regular paragraph regular paragraph regular paragraph</p>
<p class="tabbed">Indented text Indented text Indented text</p>
<p>regular paragraph regular paragraph regular paragraph</p>
If you are using tcsh, then edit your ~/.cshrc
file to include the lines:
setenv CLICOLOR 1
setenv LSCOLORS dxfxcxdxbxegedabagacad
Where, like Martin says, LSCOLORS specifies the color scheme you want to use.
To generate the LSCOLORS you want to use, checkout this site
There are two ways, depending on your original timestamp:
mktime()
and timegm()
for everything related to Python's style guide: i'd recommend you read PEP8.
To answer your question:
Function names should be lowercase, with words separated by underscores as necessary to improve readability.
I have a Nexus 4 and own a Thinkpad L430 Windows 8.1
My errors: "Waiting for device. USB device not found"
I went to: Device Manager > View > Drop to "Acer Device" > Right click on Acer Composite ADB Interface > Update it
Afterward, Reboot/Restart your computer. Once it turned on Plug Your USB Device onto the computer.
Go to: Setting > Enable "Developer options" > Check the "USB debugging" option > Check "Allow mock locations" > Check "Verify apps over USB".
Swipe down from the drop down menu of your phone where it Shows the USB Connection Icon. Tap on USB Computer Connection > Select the Check box "Camera (PTP)"
Run your Android Studio App and it should work
I'm using the following method based on @Watki02's answer:
That way you can keep your visual studio instance as your own user whilst debugging from the other.
SQL Server does not track the order of inserted rows, so there is no reliable way to get that information given your current table structure. Even if employee_id
is an IDENTITY
column, it is not 100% foolproof to rely on that for order of insertion (since you can fill gaps and even create duplicate ID values using SET IDENTITY_INSERT ON
). If employee_id
is an IDENTITY
column and you are sure that rows aren't manually inserted out of order, you should be able to use this variation of your query to select the data in sequence, newest first:
SELECT
ROW_NUMBER() OVER (ORDER BY EMPLOYEE_ID DESC) AS ID,
EMPLOYEE_ID,
EMPLOYEE_NAME
FROM dbo.CSBCA1_5_FPCIC_2012_EES207201222743
ORDER BY ID;
You can make a change to your table to track this information for new rows, but you won't be able to derive it for your existing data (they will all me marked as inserted at the time you make this change).
ALTER TABLE dbo.CSBCA1_5_FPCIC_2012_EES207201222743
-- wow, who named this?
ADD CreatedDate DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;
Note that this may break existing code that just does INSERT INTO dbo.whatever SELECT/VALUES()
- e.g. you may have to revisit your code and define a proper, explicit column list.
You can put a shadow behind the text, which can often help readability. Try experimenting with 50% translucent black shadows on your green text. Details on how to do this are over here: Android - shadow on text?
To really add a stroke around the text, you need to do something a bit more involved, like this: How do you draw text with a border on a MapView in Android?
Alternative: Use a generic HTTP handler (.ashx) and use your favorite json library to manually serialize and deserialize your JSON.
I've found that complete control over the handling of a request and generating a response beats anything else .NET offers for simple, RESTful web services.
Why not just
$q->where("a = 1");
$q->andWhere("b = 1 OR b = 2");
$q->andWhere("c = 1 OR d = 2");
EDIT: You can also use the Expr class (Doctrine2).
This is long detailed explanation. I hope this will help the beginners. I will make it very simple.
First, let's create a class
<?php
class Class1
{
}
You can omit the php closing tag ?>
if you are using php code only.
Now let's add properties and a method inside Class1
.
<?php
class Class1
{
public $property1 = "I am property 1";
public $property2 = "I am property 2";
public function Method1()
{
return "I am Method 1";
}
}
The property is just a simple variable , but we give it the name property cuz its inside a class.
The method is just a simple function , but we say method cuz its also inside a class.
The public
keyword mean that the method or a property can be accessed anywhere in the script.
Now, how we can use the properties and the method inside Class1
?
The answer is creating an instance or an object, think of an object as a copy of the class.
<?php
class Class1
{
public $property1 = "I am property 1";
public $property2 = "I am property 2";
public function Method1()
{
return "I am Method 1";
}
}
$object1 = new Class1;
var_dump($object1);
We created an object, which is $object1
, which is a copy of Class1
with all its contents. And we dumped all the contents of $object1
using var_dump()
.
This will give you
object(Class1)#1 (2) { ["property1"]=> string(15) "I am property 1" ["property2"]=> string(15) "I am property 2" }
So all the contents of Class1
are in $object1
, except Method1
, i don't know why methods doesn't show while dumping objects.
Now what if we want to access $property1
only. Its simple , we do var_dump($object1->property1);
, we just added ->property1
, we pointed to it.
we can also access Method1()
, we do var_dump($object1->Method1());
.
Now suppose i want to access $property1
from inside Method1()
, i will do this
<?php
class Class1
{
public $property1 = "I am property 1";
public $property2 = "I am property 2";
public function Method1()
{
$object2 = new Class1;
return $object2->property1;
}
}
$object1 = new Class1;
var_dump($object1->Method1());
we created $object2 = new Class1;
which is a new copy of Class1
or we can say an instance. Then we pointed to property1
from $object2
return $object2->property1;
This will print string(15) "I am property 1"
in the browser.
Now instead of doing this inside Method1()
$object2 = new Class1;
return $object2->property1;
We do this
return $this->property1;
The $this
object is used inside the class to refer to the class itself.
It is an alternative for creating new object and then returning it like this
$object2 = new Class1;
return $object2->property1;
Another example
<?php
class Class1
{
public $property1 = 119;
public $property2 = 666;
public $result;
public function Method1()
{
$this->result = $this->property1 + $this->property2;
return $this->result;
}
}
$object1 = new Class1;
var_dump($object1->Method1());
We created 2 properties containing integers and then we added them and put the result in $this->result
.
Do not forget that
$this->property1
= $property1
= 119
they have that same value .. etc
I hope that explains the idea.
This series of videos will help you a lot in OOP
https://www.youtube.com/playlist?list=PLe30vg_FG4OSEHH6bRF8FrA7wmoAMUZLv
Spring is a collection of best-practise API patterns, you can write up a shopping list of them as long as your arm. The way that the API is designed encourages you (but doesn't force you) to follow these patterns, and half the time you follow them without knowing you are doing so.
You cannot move the mousepointer with javascript.
Just think about the implications for a second, if you could ;)
Use keydown
, not keypress
for non-printable keys such as arrow keys:
function checkKey(e) {
e = e || window.event;
alert(e.keyCode);
}
document.onkeydown = checkKey;
The best JavaScript key event reference I've found (beating the pants off quirksmode, for example) is here: http://unixpapa.com/js/key.html
Postman for Linux Version 6.7.1 - Ubuntu 18.04 - linux 4.15.0-43-generic / x64
I had the same problem and by chance I replaced http://localhost
with http://127.0.0.1
and everything worked.
My etc/hosts
had the proper entries for localhost
and https://localhost
requests always worked as expected.
I have no clue why changing localhost
for http
with 127.0.0.1
solved the issue.
AFAIK there isn't a standard "reverse_iterator" sort of thing in the standard library that supports the for-each syntax which is already a syntactic sugar they brought late into the language.
You could do something like for(Item element: myList.clone().reverse()) and pay the associated price.
This also seems fairly consistent with the apparent phenomenon of not giving you convenient ways to do expensive operations - since a list, by definition, could have O(N) random access complexity (you could implement the interface with a single-link), reverse iteration could end up being O(N^2). Of course, if you have an ArrayList, you don't pay that price.
You can also save as a file: rdd.saveAsTextFile("alicia.txt")
B is not statistically significant. The data is not capable of drawing inferences from it. C does influence B probabilities
df = pd.DataFrame({"A": [10,20,30,40,50], "B": [20, 30, 10, 40, 50], "C": [32, 234, 23, 23, 42523]})
avg_c=df['C'].mean()
sumC=df['C'].apply(lambda x: x if x<avg_c else 0).sum()
countC=df['C'].apply(lambda x: 1 if x<avg_c else None).count()
avg_c2=sumC/countC
df['C']=df['C'].apply(lambda x: avg_c2 if x >avg_c else x)
print(df)
model_ols = smf.ols("A ~ B+C",data=df).fit()
print(model_ols.summary())
df[['B','C']].plot()
plt.show()
df2=pd.DataFrame()
df2['B']=np.linspace(10,50,10)
df2['C']=30
df3=pd.DataFrame()
df3['B']=np.linspace(10,50,10)
df3['C']=100
predB=model_ols.predict(df2)
predC=model_ols.predict(df3)
plt.plot(df2['B'],predB,label='predict B C=30')
plt.plot(df3['B'],predC,label='predict B C=100')
plt.legend()
plt.show()
print("A change in the probability of C affects the probability of B")
intercept=model_ols.params.loc['Intercept']
B_slope=model_ols.params.loc['B']
C_slope=model_ols.params.loc['C']
#Intercept 11.874252
#B 0.760859
#C -0.060257
print("Intercept {}\n B slope{}\n C slope{}\n".format(intercept,B_slope,C_slope))
#lower_conf,upper_conf=np.exp(model_ols.conf_int())
#print(lower_conf,upper_conf)
#print((1-(lower_conf/upper_conf))*100)
model_cov=model_ols.cov_params()
std_errorB = np.sqrt(model_cov.loc['B', 'B'])
std_errorC = np.sqrt(model_cov.loc['C', 'C'])
print('SE: ', round(std_errorB, 4),round(std_errorC, 4))
#check for statistically significant
print("B z value {} C z value {}".format((B_slope/std_errorB),(C_slope/std_errorC)))
print("B feature is more statistically significant than C")
Output:
A change in the probability of C affects the probability of B
Intercept 11.874251554067563
B slope0.7608594144571961
C slope-0.060256845997223814
Standard Error: 0.4519 0.0793
B z value 1.683510336937001 C z value -0.7601036314930376
B feature is more statistically significant than C
z>2 is statistically significant
Last function should be sort
, not limit
.
Example:
db.testcollection.find().limit(3).sort({timestamp:-1});
as I expected, yeah, it's because the whole DOM element is being pushed down. You have multiple options. You can put the buttons in separate divs, and float
them so that they don't affect each other. the simpler solution is to just set the :active
button to position:relative;
and use top
instead of margin or line-height. example fiddle: http://jsfiddle.net/5CZRP/
In the earlier versions of MySQL ( < 5.7.5 ) the only way to set
'innodb_buffer_pool_size'
variable was by writing it to my.cnf (for linux) and my.ini (for windows) under [mysqld] section :
[mysqld]
innodb_buffer_pool_size = 2147483648
You need to restart your mysql server to have it's effect in action.
As of MySQL 5.7.5, the innodb_buffer_pool_size configuration option can be set dynamically using a SET statement, allowing you to resize the buffer pool without restarting the server. For example:
mysql> SET GLOBAL innodb_buffer_pool_size=402653184;
Reference : https://dev.mysql.com/doc/refman/5.7/en/innodb-buffer-pool-resize.html
Just Do,
CTRL + X
CTRL + C
It will ask you to save file, Press Y, then you are done.
I think you want something along the line of:
Parent:
<Editor name={this.state.fileData} />
Editor:
var Editor = React.createClass({
displayName: 'Editor',
propTypes: {
name: React.PropTypes.string.isRequired
},
getInitialState: function() {
return {
value: this.props.name
};
},
handleChange: function(event) {
this.setState({value: event.target.value});
},
render: function() {
return (
<form id="noter-save-form" method="POST">
<textarea id="noter-text-area" name="textarea" value={this.state.value} onChange={this.handleChange} />
<input type="submit" value="Save" />
</form>
);
}
});
This is basically a direct copy of the example provided on https://facebook.github.io/react/docs/forms.html
Update for React 16.8:
import React, { useState } from 'react';
const Editor = (props) => {
const [value, setValue] = useState(props.name);
const handleChange = (event) => {
setValue(event.target.value);
};
return (
<form id="noter-save-form" method="POST">
<textarea id="noter-text-area" name="textarea" value={value} onChange={handleChange} />
<input type="submit" value="Save" />
</form>
);
}
Editor.propTypes = {
name: PropTypes.string.isRequired
};
It is worth noting that the accepted answer will round small floats down to zero.
>>> import numpy as np
>>> arr = np.asarray([2.92290007e+00, -1.57376965e-03, 4.82011728e-08, 1.92896977e-12])
>>> print(arr)
[ 2.92290007e+00 -1.57376965e-03 4.82011728e-08 1.92896977e-12]
>>> np.round(arr, 2)
array([ 2.92, -0. , 0. , 0. ])
You can use set_printoptions
and a custom formatter to fix this and get a more numpy-esque printout with fewer decimal places:
>>> np.set_printoptions(formatter={'float': "{0:0.2e}".format})
>>> print(arr)
[2.92e+00 -1.57e-03 4.82e-08 1.93e-12]
This way, you get the full versatility of format
and maintain the full precision of numpy's datatypes.
Also note that this only affects printing, not the actual precision of the stored values used for computation.
You could copy down a formula like the following in a new column...
=IF(ISNUMBER(FIND("-",A1)),1,0)
... then sort on that column, highlight all the rows where the value is 1 and delete them.
You can Try with
#python3
import hashlib
rawdata = "put your data here"
sha = hashlib.sha256(str(rawdata).encode("utf-8")).hexdigest() #For Sha256 hash
print(sha)
mdpass = hashlib.md5(str(sha).encode("utf-8")).hexdigest() #For MD5 hash
print(mdpass)
I found this link while looking for something slightly different, how to start appending array objects to an empty numpy array, but tried all the solutions on this page to no avail.
Then I found this question and answer: How to add a new row to an empty numpy array
The gist here:
The way to "start" the array that you want is:
arr = np.empty((0,3), int)
Then you can use concatenate to add rows like so:
arr = np.concatenate( ( arr, [[x, y, z]] ) , axis=0)
See also https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html
Using Windows Scheduled Tasks:
In the batch file
"C:\Program Files\Microsoft SQL Server\100\Tools\Binn\SQLCMD.EXE" -S
(local)\SQLExpress -i D:\dbbackups\SQLExpressBackups.sql
In SQLExpressBackups.sql
BACKUP DATABASE MyDataBase1 TO DISK = N'D:\DBbackups\MyDataBase1.bak'
WITH NOFORMAT, INIT, NAME = N'MyDataBase1 Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10
BACKUP DATABASE MyDataBase2 TO DISK = N'D:\DBbackups\MyDataBase2.bak'
WITH NOFORMAT, INIT, NAME = N'MyDataBase2 Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10
GO
Your path
is not within the assets folder. Either you enumerate files within the assets folder by means of AssetManager.list()
or you enumerate files on your SD card by means of File.list()
I got openCV installed smoothly in my mac by:
$ brew install opencv
$ brew link --overwrite --dry-run opencv // to force linking
$ pip3 install opencv-contrib-python
I got it at windows 10 using:
c:\> pip3 install opencv-python
c:\> pip3 install opencv-contrib-python
Then I got it tested by
$ python3
Python 3.7.3 (default, Mar 27 2019, 09:23:15)
[Clang 10.0.1 (clang-1001.0.46.3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> cv2.__version__
'4.1.0'
>>> exit()
display:none
will hide the element and collapse the space is was taking up, whereas visibility:hidden
will hide the element and preserve the elements space. display:none also effects some of the properties available from javascript in older versions of IE and Safari.
As Eric Wendelin mentioned, you can do something like this:
str1 = "pattern"
var re = new RegExp(str1, "g");
"pattern matching .".replace(re, "regex");
This yields "regex matching ."
. However, it will fail if str1 is "."
. You'd expect the result to be "pattern matching regex"
, replacing the period with "regex"
, but it'll turn out to be...
regexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregex
This is because, although "."
is a String, in the RegExp constructor it's still interpreted as a regular expression, meaning any non-line-break character, meaning every character in the string. For this purpose, the following function may be useful:
RegExp.quote = function(str) {
return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
};
Then you can do:
str1 = "."
var re = new RegExp(RegExp.quote(str1), "g");
"pattern matching .".replace(re, "regex");
yielding "pattern matching regex"
.
Yes it is possible
You can do this using only
HTML
You need to set default select optiondisabled=""
andselected=""
and select tagrequired=""
. Browser doesn't allow user to submit the form without selecting an option.
<form action="" method="POST">
<select name="in-op" required="">
<option disabled="" selected="">Select Option</option>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
<input type="submit" value="Submit">
</form>
(Mar 2017) The accepted answer is not the best solution. It relies on manual translation using Apps Script, and the code may not be resilient, requiring maintenance. If your legacy system autogenerates CSV files, it's best they go into another folder for temporary processing (importing [uploading to Google Drive & converting] to Google Sheets files).
My thought is to let the Drive API do all the heavy-lifting. The Google Drive API team released v3 at the end of 2015, and in that release, insert()
changed names to create()
so as to better reflect the file operation. There's also no more convert flag -- you just specify MIMEtypes... imagine that!
The documentation has also been improved: there's now a special guide devoted to uploads (simple, multipart, and resumable) that comes with sample code in Java, Python, PHP, C#/.NET, Ruby, JavaScript/Node.js, and iOS/Obj-C that imports CSV files into Google Sheets format as desired.
Below is one alternate Python solution for short files ("simple upload") where you don't need the apiclient.http.MediaFileUpload
class. This snippet assumes your auth code works where your service endpoint is DRIVE
with a minimum auth scope of https://www.googleapis.com/auth/drive.file
.
# filenames & MIMEtypes
DST_FILENAME = 'inventory'
SRC_FILENAME = DST_FILENAME + '.csv'
SHT_MIMETYPE = 'application/vnd.google-apps.spreadsheet'
CSV_MIMETYPE = 'text/csv'
# Import CSV file to Google Drive as a Google Sheets file
METADATA = {'name': DST_FILENAME, 'mimeType': SHT_MIMETYPE}
rsp = DRIVE.files().create(body=METADATA, media_body=SRC_FILENAME).execute()
if rsp:
print('Imported %r to %r (as %s)' % (SRC_FILENAME, DST_FILENAME, rsp['mimeType']))
Better yet, rather than uploading to My Drive
, you'd upload to one (or more) specific folder(s), meaning you'd add the parent folder ID(s) to METADATA
. (Also see the code sample on this page.) Finally, there's no native .gsheet "file" -- that file just has a link to the online Sheet, so what's above is what you want to do.
If not using Python, you can use the snippet above as pseudocode to port to your system language. Regardless, there's much less code to maintain because there's no CSV parsing. The only thing remaining is to blow away the CSV file temp folder your legacy system wrote to.
lapply
is probably a better choice than apply
here, as apply first coerces your data.frame to an array which means all the columns must have the same type. Depending on your context, this could have unintended consequences.
The pattern is:
df[cols] <- lapply(df[cols], FUN)
The 'cols' vector can be variable names or indices. I prefer to use names whenever possible (it's robust to column reordering). So in your case this might be:
wifi[4:9] <- lapply(wifi[4:9], A)
An example of using column names:
wifi <- data.frame(A=1:4, B=runif(4), C=5:8)
wifi[c("B", "C")] <- lapply(wifi[c("B", "C")], function(x) -1 * x)
I resolved the same issue with a recursive chown on the parent folder:
sudo chown -R postgres:postgres /home/my_user/export_folder
(my export being in /home/my_user/export_folder/export_1.csv
)
If you used a raw socket (SOCK_RAW
) and re-implemented TCP in userland, I think the answer is limited in this case only by the number of (local address, source port, destination address, destination port)
tuples (~2^64 per local address).
It would of course take a lot of memory to keep the state of all those connections, and I think you would have to set up some iptables rules to keep the kernel TCP stack from getting upset &/or responding on your behalf.
Algorithm to use for checking well balanced parenthesis -
Now traverse the string expression input.
If the current character is an opening bracket ( '{', '(', '[' ) then push it to the parenStack.
If the current character is a closing bracket ( '}', ')', ']' ) then pop from parenStack and if the popped character is equal to the matching starting bracket in matchingParenMap then continue looping else return false.
After complete traversal if no opening brackets are left in parenStack it means it is a well balanced expression.
I have explained the code snippet of the algorithm used on my blog. Check link - http://hetalrachh.home.blog/2019/12/25/stack-data-structure/
Same problem, solved with a simple code refactoring. The problem is sometime present when a required field is null, before do anithing, try to refactor your code. A better workflow can solve the problem.
{% load static %}
Please add this template tag on top of the HTML or base HTML file
This works great for me and I'm doing more, writing less with jQuery's example modified.
I defined the select object on my page, just like the jQuery ex. I took the text and pushed it to an array. Then I use the array as my source to my input autocomplete. tadaa.
$(function() {
var mySource = [];
$("#mySelect").children("option").map(function() {
mySource.push($(this).text());
});
$("#myInput").autocomplete({
source: mySource,
minLength: 3
});
}
You can disable FK and CHECK constraints only in SQL 2005+. See ALTER TABLE
ALTER TABLE foo NOCHECK CONSTRAINT ALL
or
ALTER TABLE foo NOCHECK CONSTRAINT CK_foo_column
Primary keys and unique constraints can not be disabled, but this should be OK if I've understood you correctly.
With Spring 3.0.4.RELEASE and higher you can use
<mvc:resources mapping="/resources/**" location="/public-resources/"/>
As seen in Spring Reference.
The width will be rounded to an integer number of pixels.
I don't know if every browser will round it the same way though. They all seem to have a different strategy when rounding sub-pixel percentages. If you're interested in the details of sub-pixel rounding in different browsers, there's an excellent article on ElastiCSS.
edit: I tested @Skilldrick's demo in some browsers for the sake of curiosity. When using fractional pixel values (not percentages, they work as suggested in the article I linked) IE9p7 and FF4b7 seem to round to the nearest pixel, while Opera 11b, Chrome 9.0.587.0 and Safari 5.0.3 truncate the decimal places. Not that I hoped that they had something in common after all...
I would choose Sequelize because of it's excellent documentation. It's just a honest opinion (I never really used MySQL with Node that much).
A dynamic way to do that with MULTIPLE keys:
Object.defineProperty(Array.prototype, 'orderBy', {
value: function(sorts) {
sorts.map(sort => {
sort.uniques = Array.from(
new Set(this.map(obj => obj[sort.key]))
);
sort.uniques = sort.uniques.sort((a, b) => {
if (typeof a == 'string') {
return sort.inverse ? b.localeCompare(a) : a.localeCompare(b);
}
else if (typeof a == 'number') {
return sort.inverse ? (a < b) : (a > b ? 1 : 0);
}
else if (typeof a == 'boolean') {
let x = sort.inverse ? (a === b) ? 0 : a? -1 : 1 : (a === b) ? 0 : a? 1 : -1;
return x;
}
return 0;
});
});
const weightOfObject = (obj) => {
let weight = "";
sorts.map(sort => {
let zeropad = `${sort.uniques.length}`.length;
weight += sort.uniques.indexOf(obj[sort.key]).toString().padStart(zeropad, '0');
});
//obj.weight = weight; // if you need to see weights
return weight;
}
this.sort((a, b) => {
return weightOfObject(a).localeCompare( weightOfObject(b) );
});
return this;
}
});
Use:
// works with string, number and boolean
let sortered = your_array.orderBy([
{key: "type", inverse: false},
{key: "title", inverse: false},
{key: "spot", inverse: false},
{key: "internal", inverse: true}
]);
There are at least six additional ways to iterate over a set. The following are known to me:
Method 1
// Obsolete Collection
Enumeration e = new Vector(movies).elements();
while (e.hasMoreElements()) {
System.out.println(e.nextElement());
}
Method 2
for (String movie : movies) {
System.out.println(movie);
}
Method 3
String[] movieArray = movies.toArray(new String[movies.size()]);
for (int i = 0; i < movieArray.length; i++) {
System.out.println(movieArray[i]);
}
Method 4
// Supported in Java 8 and above
movies.stream().forEach((movie) -> {
System.out.println(movie);
});
Method 5
// Supported in Java 8 and above
movies.stream().forEach(movie -> System.out.println(movie));
Method 6
// Supported in Java 8 and above
movies.stream().forEach(System.out::println);
This is the HashSet
which I used for my examples:
Set<String> movies = new HashSet<>();
movies.add("Avatar");
movies.add("The Lord of the Rings");
movies.add("Titanic");
The Excel number for a modern date is most easily calculated as the number of days since 12/30/1899 on the Gregorian calendar.
Excel treats the mythical date 01/00/1900 (i.e., 12/31/1899) as corresponding to 0, and incorrectly treats year 1900 as a leap year. So for dates before 03/01/1900, the Excel number is effectively the number of days after 12/31/1899.
However, Excel will not format any number below 0 (-1 gives you ##########) and so this only matters for "01/00/1900" to 02/28/1900, making it easier to just use the 12/30/1899 date as a base.
A complete function in DB2 SQL that accounts for the leap year 1900 error:
SELECT
DAYS(INPUT_DATE)
- DAYS(DATE('1899-12-30'))
- CASE
WHEN INPUT_DATE < DATE('1900-03-01')
THEN 1
ELSE 0
END
As others have said, it's an initialisation list. You can use it for two things:
For case #1, I assume you understand inheritance (if that's not the case, let me know in the comments). So you are simply calling the constructor of your base class.
For case #2, the question may be asked: "Why not just initialise it in the body of the constructor?" The importance of the initialisation lists is particularly evident for const
members. For instance, take a look at this situation, where I want to initialise m_val
based on the constructor parameter:
class Demo
{
Demo(int& val)
{
m_val = val;
}
private:
const int& m_val;
};
By the C++ specification, this is illegal. We cannot change the value of a const
variable in the constructor, because it is marked as const. So you can use the initialisation list:
class Demo
{
Demo(int& val) : m_val(val)
{
}
private:
const int& m_val;
};
That is the only time that you can change a const member variable. And as Michael noted in the comments section, it is also the only way to initialise a reference that is a class member.
Outside of using it to initialise const
member variables, it seems to have been generally accepted as "the way" of initialising variables, so it's clear to other programmers reading your code.
You need to do encode
on tmp[0]
, not on tmp
.
tmp
is not a string. It contains a (Unicode) string.
Try running type(tmp)
and print dir(tmp)
to see it for yourself.
You can un-check the build automatically in Project menu and then build by hand by type Ctrl + B, or clicking an icon the appears to the right of the printer icon.
As of .NET Core 2.0, there is an override that takes a string.
So now you can do "THExxQUICKxxBROWNxxFOX".Split("xx")
.
As a counter point to the general thrust of the other answers. See The Many Benefits of Money…Data Type! in SQLCAT's Guide to Relational Engine
Specifically I would point out the following
Working on customer implementations, we found some interesting performance numbers concerning the money data type. For example, when Analysis Services was set to the currency data type (from double) to match the SQL Server money data type, there was a 13% improvement in processing speed (rows/sec). To get faster performance within SQL Server Integration Services (SSIS) to load 1.18 TB in under thirty minutes, as noted in SSIS 2008 - world record ETL performance, it was observed that changing the four decimal(9,2) columns with a size of 5 bytes in the TPC-H LINEITEM table to money (8 bytes) improved bulk inserting speed by 20% ... The reason for the performance improvement is because of SQL Server’s Tabular Data Stream (TDS) protocol, which has the key design principle to transfer data in compact binary form and as close as possible to the internal storage format of SQL Server. Empirically, this was observed during the SSIS 2008 - world record ETL performance test using Kernrate; the protocol dropped significantly when the data type was switched to money from decimal. This makes the transfer of data as efficient as possible. A complex data type needs additional parsing and CPU cycles to handle than a fixed-width type.
So the answer to the question is "it depends". You need to be more careful with certain arithmetical operations to preserve precision but you may find that performance considerations make this worthwhile.
Use !(window.ActiveXObject) && "ActiveXObject" in window
to detect IE11 explicitly.
To detect any IE (pre-Edge, "Trident") version, use "ActiveXObject" in window
instead.
Since delegates are a 1-to-1 relationship and I might want to use it elsewhere for other reasons, I like to restrict textfield length adding this code within their setup:
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
setup()
}
required override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
func setup() {
// your setup...
setMaxLength()
}
let maxLength = 10
private func setMaxLength() {
addTarget(self, action: #selector(textfieldChanged(_:)), for: UIControlEvents.editingChanged)
}
@objc private func textfieldChanged(_ textField: UITextField) {
guard let text = text else { return }
let trimmed = text.characters.prefix(maxLength)
self.text = String(trimmed)
}
Imagine you end up with double dashes, and want to replace them with a single character and not doubles of the replace character. You can just use array split and array filter and array join.
var str = "This-is---a--news-----item----";
Then to replace all dashes with single spaces, you could do this:
var newStr = str.split('-').filter(function(item) {
item = item ? item.replace(/-/g, ''): item
return item;
}).join(' ');
Now if the string contains double dashes, like '----' then array split will produce an element with 3 dashes in it (because it split on the first dash). So by using this line:
item = item ? item.replace(/-/g, ''): item
The filter method removes those extra dashes so the element will be ignored on the filter iteration. The above line also accounts for if item is already an empty element so it doesn't crash on item.replace.
Then when your string join runs on the filtered elements, you end up with this output:
"This is a news item"
Now if you were using something like knockout.js where you can have computer observables. You could create a computed observable to always calculate "newStr" when "str" changes so you'd always have a version of the string with no dashes even if you change the value of the original input string. Basically they are bound together. I'm sure other JS frameworks can do similar things.
Just tried this solution, we don't have to even write int.
int[][] twoDim = { { 1, 2 }, { 3, 7 }, { 8, 9 }, { 4, 2 }, { 5, 3 } };
Arrays.sort(twoDim, (a1,a2) -> a2[0] - a1[0]);
This thing will also work, it automatically detects the type of string.
I just had this problem with Jenkins.
The solution was to copy the certificate and paste it into the system keychain otherwise Jenkins couldn't read the certificate.
You need to access the layout via it's layout resource, not an id resource which is not guaranteed unique. The resource reference should look like R.layout.my_cool_layout where your above XML layout is stored in res/layout/my_cool_layout.xml.
make sure that your composer is up to date. write in the cmd
composer create-project –-prefer-dist laravel/laravel NameOfProject "Version"
Are you looking for exit
?
This is the best bash guide around. http://tldp.org/LDP/abs/html/
In context:
if jarsigner -verbose -keystore $keyst -keystore $pass $jar_file $kalias
then
echo $jar_file signed sucessfully
else
echo ERROR: Failed to sign $jar_file. Please recheck the variables 1>&2
exit 1 # terminate and indicate error
fi
...
I believe this should work:
login_div.Attributes.Add("style","display:none");
Try + (instancetype)appearance of UITableView:
Objective-C:
[[UITableView appearance] setSeparatorColor:[UIColor blackColor]]; // set your desired colour in place of "[UIColor blackColor]"
Swift 3.0:
UITableView.appearance().separatorColor = UIColor.black // set your desired colour in place of "UIColor.black"
Note: Change will reflect to all tables used in application.
This should answer:
How To: Configure MachineKey in ASP.NET 2.0 - Web Farm Deployment Considerations
Web Farm Deployment Considerations
If you deploy your application in a Web farm, you must ensure that the configuration files on each server share the same value for validationKey and decryptionKey, which are used for hashing and decryption respectively. This is required because you cannot guarantee which server will handle successive requests.
With manually generated key values, the settings should be similar to the following example.
<machineKey validationKey="21F090935F6E49C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D7 AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281B" decryptionKey="ABAA84D7EC4BB56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719F" validation="SHA1" decryption="AES" />
If you want to isolate your application from other applications on the same server, place the in the Web.config file for each application on each server in the farm. Ensure that you use separate key values for each application, but duplicate each application's keys across all servers in the farm.
In short, to set up the machine key refer the following link: Setting Up a Machine Key - Orchard Documentation.
Setting Up the Machine Key Using IIS Manager
If you have access to the IIS management console for the server where Orchard is installed, it is the easiest way to set-up a machine key.
Start the management console and then select the web site. Open the machine key configuration:
The machine key control panel has the following settings:
Uncheck "Automatically generate at runtime" for both the validation key and the decryption key.
Click "Generate Keys" under "Actions" on the right side of the panel.
Click "Apply".
and add the following line to the web.config
file in all the webservers
under system.web
tag if it does not exist.
<machineKey
validationKey="21F0SAMPLEKEY9C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D7
AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281B"
decryptionKey="ABAASAMPLEKEY56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719F"
validation="SHA1"
decryption="AES"
/>
Please make sure that you have a permanent backup of the machine keys and web.config
file
Try this code
Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
Microsoft.Office.Interop.Excel.Range oRng;
object misvalue = System.Reflection.Missing.Value;
try
{
//Start Excel and get Application object.
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
//Get a new workbook.
oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
//Add table headers going cell by cell.
oSheet.Cells[1, 1] = "First Name";
oSheet.Cells[1, 2] = "Last Name";
oSheet.Cells[1, 3] = "Full Name";
oSheet.Cells[1, 4] = "Salary";
//Format A1:D1 as bold, vertical alignment = center.
oSheet.get_Range("A1", "D1").Font.Bold = true;
oSheet.get_Range("A1", "D1").VerticalAlignment =
Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
// Create an array to multiple values at once.
string[,] saNames = new string[5, 2];
saNames[0, 0] = "John";
saNames[0, 1] = "Smith";
saNames[1, 0] = "Tom";
saNames[4, 1] = "Johnson";
//Fill A2:B6 with an array of values (First and Last Names).
oSheet.get_Range("A2", "B6").Value2 = saNames;
//Fill C2:C6 with a relative formula (=A2 & " " & B2).
oRng = oSheet.get_Range("C2", "C6");
oRng.Formula = "=A2 & \" \" & B2";
//Fill D2:D6 with a formula(=RAND()*100000) and apply format.
oRng = oSheet.get_Range("D2", "D6");
oRng.Formula = "=RAND()*100000";
oRng.NumberFormat = "$0.00";
//AutoFit columns A:D.
oRng = oSheet.get_Range("A1", "D1");
oRng.EntireColumn.AutoFit();
oXL.Visible = false;
oXL.UserControl = false;
oWB.SaveAs("c:\\test\\test505.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
oWB.Close();
oXL.Quit();
//...
The right answer (using Python 2.7 and later, since check_output()
was introduced then) is:
py2output = subprocess.check_output(['python','py2.py','-i', 'test.txt'])
To demonstrate, here are my two programs:
py2.py:
import sys
print sys.argv
py3.py:
import subprocess
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'])
print('py2 said:', py2output)
Running it:
$ python3 py3.py
py2 said: b"['py2.py', '-i', 'test.txt']\n"
Here's what's wrong with each of your versions:
py2output = subprocess.check_output([str('python py2.py '),'-i', 'test.txt'])
First, str('python py2.py')
is exactly the same thing as 'python py2.py'
—you're taking a str
, and calling str
to convert it to an str
. This makes the code harder to read, longer, and even slower, without adding any benefit.
More seriously, python py2.py
can't be a single argument, unless you're actually trying to run a program named, say, /usr/bin/python\ py2.py
. Which you're not; you're trying to run, say, /usr/bin/python
with first argument py2.py
. So, you need to make them separate elements in the list.
Your second version fixes that, but you're missing the '
before test.txt'
. This should give you a SyntaxError
, probably saying EOL while scanning string literal
.
Meanwhile, I'm not sure how you found documentation but couldn't find any examples with arguments. The very first example is:
>>> subprocess.check_output(["echo", "Hello World!"])
b'Hello World!\n'
That calls the "echo"
command with an additional argument, "Hello World!"
.
Also:
-i is a positional argument for argparse, test.txt is what the -i is
I'm pretty sure -i
is not a positional argument, but an optional argument. Otherwise, the second half of the sentence makes no sense.
"==" always compare the memory location or object references of the values. equals method always compare the values. But equals also indirectly uses the "==" operator to compare the values.
Integer uses Integer cache to store the values from -128 to +127. If == operator is used to check for any values between -128 to 127 then it returns true. for other than these values it returns false .
Refer the link for some additional info
// The below C++ function checks for a palindrome and
// returns true if it is a palindrome and returns false otherwise
bool checkPalindrome ( string s )
{
// This calculates the length of the string
int n = s.length();
// the for loop iterates until the first half of the string
// and checks first element with the last element,
// second element with second last element and so on.
// if those two characters are not same, hence we return false because
// this string is not a palindrome
for ( int i = 0; i <= n/2; i++ )
{
if ( s[i] != s[n-1-i] )
return false;
}
// if the above for loop executes completely ,
// this implies that the string is palindrome,
// hence we return true and exit
return true;
}
So I was having this problem, none of the other remedies worked. The error message was opaque, but checking dmesg was key:
[ 10.118255] NVRM: API mismatch: the client has the version 410.79, but
NVRM: this kernel module has the version 384.130. Please
NVRM: make sure that this kernel module and all NVIDIA driver
NVRM: components have the same version.
However I had completely removed the 384 version, and removed any remaining kernel drivers nvidia-384*
. But even after reboot, I was still getting this. Seeing this meant that the kernel was still compiled to reference 384, but was only finding 410. So I recompiled my kernel:
# uname -a # find the kernel it's using
Linux blah 4.13.0-43-generic #48~16.04.1-Ubuntu SMP Thu May 17 12:56:46 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
# update-initramfs -c -k 4.13.0-43-generic #recompile it
# reboot
And then it worked.
After removing 384, I still had 384 files in: /var/lib/dkms/nvidia-XXX/XXX.YY/4.13.0-43-generic/x86_64/module /lib/modules/4.13.0-43-generic/kernel/drivers
I recommend using the locate
command (not installed by default) rather than searching the filesystem every time.
It is probably not sorted at all and uses the order at which entries appear in the filesystem, i.e. the one you get when using ls -U
. (At least on my machine this produces the same order as listing glob
matches).
You can also use firstOrCreate
OR firstOrNew
// Retrieve the Post by the attributes, or create it if it doesn't exist...
$post = Post::firstOrCreate(['id' => 3]);
// OR
// Retrieve the Post by the attributes, or instantiate a new instance...
$post = Post::firstOrNew(['id' => 3]);
// update record
$post->title = "Updated title";
$post->save();
Hope it will help you :)
Please check the following things first.
While generating the Edmx you would have given a name to you connection string. that gets into the app config of the project with the Entity.
Have you copied the same connection string to your main Config file. Also the Name should be same as which you have given while generating the EDMX file.
If you have this problem when using an instaled version, when using setup.py
, make sure your module is included inside packages
setup(name='Your program',
version='0.7.0',
description='Your desccription',
packages=['foo', 'foo.bar'], # add `foo.bar` here
The best thing I've found for diagnosing things like this is the service trace viewer. It's pretty simple to set up (assuming you can edit the configs):
http://msdn.microsoft.com/en-us/library/ms732023.aspx
Hope this helps.
The approach recommended by the ASP.Net Core team is to use the new policy design which is fully documented here. The basic idea behind the new approach is to use the new [Authorize] attribute to designate a "policy" (e.g. [Authorize( Policy = "YouNeedToBe18ToDoThis")]
where the policy is registered in the application's Startup.cs to execute some block of code (i.e. ensure the user has an age claim where the age is 18 or older).
The policy design is a great addition to the framework and the ASP.Net Security Core team should be commended for its introduction. That said, it isn't well-suited for all cases. The shortcoming of this approach is that it fails to provide a convenient solution for the most common need of simply asserting that a given controller or action requires a given claim type. In the case where an application may have hundreds of discrete permissions governing CRUD operations on individual REST resources ("CanCreateOrder", "CanReadOrder", "CanUpdateOrder", "CanDeleteOrder", etc.), the new approach either requires repetitive one-to-one mappings between a policy name and a claim name (e.g. options.AddPolicy("CanUpdateOrder", policy => policy.RequireClaim(MyClaimTypes.Permission, "CanUpdateOrder));
), or writing some code to perform these registrations at run time (e.g. read all claim types from a database and perform the aforementioned call in a loop). The problem with this approach for the majority of cases is that it's unnecessary overhead.
While the ASP.Net Core Security team recommends never creating your own solution, in some cases this may be the most prudent option with which to start.
The following is an implementation which uses the IAuthorizationFilter to provide a simple way to express a claim requirement for a given controller or action:
public class ClaimRequirementAttribute : TypeFilterAttribute
{
public ClaimRequirementAttribute(string claimType, string claimValue) : base(typeof(ClaimRequirementFilter))
{
Arguments = new object[] {new Claim(claimType, claimValue) };
}
}
public class ClaimRequirementFilter : IAuthorizationFilter
{
readonly Claim _claim;
public ClaimRequirementFilter(Claim claim)
{
_claim = claim;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
var hasClaim = context.HttpContext.User.Claims.Any(c => c.Type == _claim.Type && c.Value == _claim.Value);
if (!hasClaim)
{
context.Result = new ForbidResult();
}
}
}
[Route("api/resource")]
public class MyController : Controller
{
[ClaimRequirement(MyClaimTypes.Permission, "CanReadResource")]
[HttpGet]
public IActionResult GetResource()
{
return Ok();
}
}
As Already mentioned we have two ways!
And it's done interactively! And take effect immediately!
CTRL + A followed by : And we type scrollback 1000000
And hit ENTER
You detach from the screen and come back! It will be always the same.
You open another new screen! And the value is reset again to default! So it's not a global setting!
Which is done by adding defscrollback 1000000
to .screenrc
(in home)
defscrollback
and not scrollback
(def stand for default)
What you need to know is if the file is not created ! You create it !
> cd ~ && vim .screenrc
And you add defscrollback 1000000
to it!
Or in one command
> echo "defscrollback 1000000" >> .screenrc
(if not created already)
When you add the default to .screenrc
! The already running screen at re-attach will not take effect! The .screenrc
run at the screen creation! And it make sense! Just as with a normal console and shell launch!
And all the new created screens will have the set value!
To check type CTRL + A followed by i
And The result will be as
Importantly the buffer size is the number after the + sign
(in the illustration i set it to 1 000 000)
Note too that when you change it interactively! The effect is immediate and take over the default value!
CTRL+ A followed by ESC (to enter the copy mode).
Then navigate with Up,Down or PgUp PgDown
And ESC again to quit that mode.
(Extra info: to copy hit ENTER to start selecting! Then ENTER again to copy! Simple and cool)
Now the buffer is bigger!
And that's sum it up for the important details!
You can rename/remove master on remote, but this will be an issue if lots of people have based their work on the remote master branch and have pulled that branch in their local repo.
That might not be the case here since everyone seems to be working on branch 'seotweaks
'.
In that case you can:
git remote --show may not work.
(Make a git remote show
to check how your remote is declared within your local repo. I will assume 'origin
')
(Regarding GitHub, house9 comments: "I had to do one additional step, click the 'Admin
' button on GitHub and set the 'Default Branch
' to something other than 'master
', then put it back afterwards")
git branch -m master master-old # rename master on local
git push origin :master # delete master on remote
git push origin master-old # create master-old on remote
git checkout -b master seotweaks # create a new local master on top of seotweaks
git push origin master # create master on remote
But again:
reset --hard
their local master to the remote/master branch they will fetch, and forget about their current master.I have fixed this problem when calling a MVC3 Controller. I added:
Response.AddHeader("Access-Control-Allow-Origin", "*");
before my
return Json(model, JsonRequestBehavior.AllowGet);
And also my $.ajax
was complaining that it does not accept Content-type header in my ajax call, so I commented it out as I know its JSON being passed to the Action.
Hope that helps.
The debug
module can be used to analyze variables. Be careful running the following command. In our setup it generates 444709 lines with 16MB:
ansible -m debug -a 'var=hostvars' localhost
I am not sure but it might be necessary to enable facts caching.
If you need just one host use the host name as a key for the hostvars
hash:
ansible -m debug -a 'var=hostvars.localhost' localhost
In addition to the Eclipse solutions and the tool mentioned in another answer, consider flip. It can 'flip' either way between normal and Windows linebreaks, and does nice things like preserve the file's timestamp and other stats.
You can use it like this to solve your problem:
find . -type f -not -path './.git/*' -exec flip -u {} \;
(I put in a clause to ignore your .git directory, in case you use git, but since flip ignores binary files by default, you mightn't need this.)
You can simply use Python standard library. Make a shallow copy of the original image as follows:
import copy
original_img = cv2.imread("foo.jpg")
clone_img = copy.copy(original_img)
That is because imgButton is null. Try this instead:
findViewById(R.id.imgButton).setBackgroundResource(R.drawable.ic_action_search);
or much easier to read:
imgButton = (Button) findViewById(R.id.imgButton);
imgButton.setOnClickListener(imgButtonHandler);
then in onClick: imgButton.setBackgroundResource(R.drawable.ic_action_search);
You need to install Xcode from App Store.
Then start Xcode, go to Xcode->Preferences->Downloads
and install component named "Command Line Tools".
After that all the relevant tools will be placed in /usr/bin folder and you will be able to use it just as it was in 10.6.
The file you give is a shell script, not an awk program. So, try sh my.awk
.
If you want to use awk -f my.awk life.csv > life_out.cs
, then remove awk -F , '
and the last line from the file and add FS=","
in BEGIN
.
Try closing and reopening the file, then press Ctrl+F11
.
Verify that the name of the file you are running is the same as the name of the project you are working in, and that the name of the public class in that file is the same as the name of the project you are working in as well.
Otherwise, restart Eclipse. Let me know if this solves the problem! Otherwise, comment, and I'll try and help.
Simply use \1
instead of $1
:
In [1]: import re
In [2]: method = 'images/:id/huge'
In [3]: re.sub(r'(:[a-z]+)', r'<span>\1</span>', method)
Out[3]: 'images/<span>:id</span>/huge'
Also note the use of raw strings (r'...'
) for regular expressions. It is not mandatory but removes the need to escape backslashes, arguably making the code slightly more readable.
<?php
$thumbs_dir = 'E:/xampp/htdocs/uploads/thumbs/';
$videos = array();
if (isset($_POST["name"])) {
if (!preg_match('/data:([^;]*);base64,(.*)/', $_POST['data'], $matches)) {
die("error");
}
$data = $matches[2];
$data = str_replace(' ', '+', $data);
$data = base64_decode($data);
$file = 'text.jpg';
$dataname = file_put_contents($thumbs_dir . $file, $data);
}
?>
//jscode
<script type="text/javascript">
var videos = <?= json_encode($videos); ?>;
var video = document.getElementById('video');
video.addEventListener('canplay', function () {
this.currentTime = this.duration / 2;
}, false);
var seek = true;
video.addEventListener('seeked', function () {
if (seek) {
getThumb();
}
}, false);
function getThumb() {
seek = false;
var filename = video.src;
var w = video.videoWidth;//video.videoWidth * scaleFactor;
var h = video.videoHeight;//video.videoHeight * scaleFactor;
var canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
var ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, w, h);
var data = canvas.toDataURL("image/jpg");
var xmlhttp = new XMLHttpRequest;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
}
}
xmlhttp.open("POST", location.href, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send('name=' + encodeURIComponent(filename) + '&data=' + data);
}
function failed(e) {
// video playback failed - show a message saying why
switch (e.target.error.code) {
case e.target.error.MEDIA_ERR_ABORTED:
console.log('You aborted the video playback.');
break;
case e.target.error.MEDIA_ERR_NETWORK:
console.log('A network error caused the video download to fail part-way.');
break;
case e.target.error.MEDIA_ERR_DECODE:
console.log('The video playback was aborted due to a corruption problem or because the video used features your browser did not support.');
break;
case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
console.log('The video could not be loaded, either because the server or network failed or because the format is not supported.');
break;
default:
console.log('An unknown error occurred.');
break;
}
}
</script>
//Html
<div>
<video id="video" src="1499752288.mp4" autoplay="true" onerror="failed(event)" controls="controls" preload="none"></video>
</div>
Simple answer in Python: If you need to create a large real text file I just used a simple while
loop and was able to create a 5 GB file in about 20 seconds. I know it's crude, but it is fast enough.
outfile = open("outfile.log", "a+")
def write(outfile):
outfile.write("hello world hello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello world"+"\n")
return
i=0
while i < 1000000:
write(outfile)
i += 1
outfile.close()
div {
display: flex;
justify-content: space-between;
}
_x000D_
<div>
<p>Item one</p>
<a>Item two</a>
</div>
_x000D_
There is a rule in C++, for every new there is a delete.
new is never called. So the address that cout prints is the address of the memory location of myVar, or the value assigned to myPointer in this case. By writing:
myPointer = &myVar;
you say:
myPointer = The address of where the data in myVar is stored
It returns an address that points to a memory location that has been deleted. Because first you create the pointer and assign its value to myPointer, second you delete it, third you print it. So unless you assign another value to myPointer, the deleted address will remain.
NULL equals 0, you delete 0, so you delete nothing. And it's logic that it prints 0 because you did:
myPointer = NULL;
which equals:
myPointer = 0;
using jquery, you may want to get only to those with a '#'
$('a[href=#]').click(function(){return false;});
if you use the newest jquery (1.3.x), there's no need to bind it again when the page changes:
$('a[href=#]').live('click', function(){return false;});
To find all local IPv4 addresses:
IPAddress[] ipv4Addresses = Array.FindAll(
Dns.GetHostEntry(string.Empty).AddressList,
a => a.AddressFamily == AddressFamily.InterNetwork);
or use Array.Find
or Array.FindLast
if you just want one.
Batch file for setting a new dns server
@echo off
rem usage: setdns <dnsserver> <interface>
rem default dsnserver is dhcp
rem default interface is Wi-Fi
set dnsserver="%1"
if %dnsserver%=="" set dnsserver="dhcp"
set interface="%2"
if %interface%=="" set interface="Wi-Fi"
echo Showing current DNS setting for interface a%interface%
netsh interface ipv4 show dnsserver %interface%
echo Changing dnsserver on interface %interface% to %dnsserver%
if %dnsserver% == "dhcp" netsh interface ipv4 set dnsserver %interface% %dnsserver%
if NOT %dnsserver% == "dhcp" netsh interface ipv4 add dnsserver %interface% address=%dnsserver% index=1
echo Showing new DNS setting for interface %interface%
netsh interface ipv4 show dnsserver %interface%
You can use the break keyword.
Actually, a new technique came out recently. This article will answer your questions: http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement
.hide-text {
text-indent: 100%;
white-space: nowrap;
overflow: hidden;
}
It is accessible, an has better performance than -99999px.
Update: As @deathlock mentions in the comment area, the author of the fix above (Scott Kellum), has suggested using a transparent font: http://scottkellum.com/2013/10/25/the-new-kellum-method.html.
Two options, that have different uses:
HTML:
<a class="example" href="http://www.example.com">example</a>
CSS:
.example { text-align: center; }
Or:
.example { display:block; width:100px; margin:0 auto;}
OP here, I have learned a lot more about node since I first asked this question. Though Dmitry's answer was very helpful, what ultimately did it for me is to install node with the correct permissions.
I highly recommend not installing node using any package managers, but rather to compile it yourself so that it resides in a local directory with normal permissions.
This article provides a very clear step-by-step instruction of how to do so:
redis-cli -h <host> -p <port> flushall
It will remove all data from client connected(with host and port)
If you're using SSMS (or old school Enterprise Manager) to edit the table directly, press CTRL+0 to add a null.
setting the font size might not be practical though, since setting
ctx.font = ''
will use the one defined by CSS as well as any embedded font tags. If you use the CSS font you have no idea what the height is from a programmatic way, using the measureText method, which is very short sighted. On another note though, IE8 DOES return the width and height.
use a double %%
FOR MVC
-- WEB.CONFIG CODE IN APP SETTING --
<add key="PhaseLevel" value="1" />
-- ON VIEWS suppose you want to show or hide something based on web.config Value--
-- WRITE THIS ON TOP OF YOUR PAGE--
@{
var phase = System.Configuration.ConfigurationManager.AppSettings["PhaseLevel"].ToString();
}
-- USE ABOVE VALUE WHERE YOU WANT TO SHOW OR HIDE.
@if (phase != "1")
{
@Html.Partial("~/Views/Shared/_LeftSideBarPartial.cshtml")
}
For Amazon AWS codecommit
users,
aws codecommit update-repository-name --old-name MyDemoRepo --new-name MyRenamedDemoRepo
Reference: here
What no TryParse? Safe LINQ version that filters out invalid ints (for C# 6.0 and below):
List<int> ints = strings
.Select(s => { int i; return int.TryParse(s, out i) ? i : (int?)null; })
.Where(i => i.HasValue)
.Select(i => i.Value)
.ToList();
credit to Olivier Jacot-Descombes for the idea and the C# 7.0 version.
I don't yet have a large enough reputation score to add a comment where it would be most helpful, but this is in relation to those asking about a .Net 4.5 solution.
You can use the mouse X and Y co-ordinates and the ListView method GetItemAt to find the item which has been clicked on.
private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
ListViewItem item = myListView.GetItemAt(e.X, e.Y)
// Do something here
}
Just to help if anyone stumble on this question like me, if you want to use if in PostgreSQL, you use "CASE"
select
case
when stage = 1 then 'running'
when stage = 2 then 'done'
when stage = 3 then 'stopped'
else
'not running'
end as run_status from processes
Maybe you're trying to uninstall an app that is a phone administrator.
To be able to uninstall it, go to Seetings > Security > Phone Administrators. If the app is listed, uncheck it and confirm the operation.
After that, you should be able to uninstall it using the App settings area or adb.
If you want to recursively apply this change to all files in a directoy, you can use the Find > Find in Files... modal:
Edit I didn't highlight it in the image, but you have to click the .* button on the left to have Sublime interpret the Find field as a regex /Edit
Edit 2 I neglected to add a start of string anchor to the regex. I'm correcting that below, and will update the image when I get a chance /Edit
The regex in the Find field ^[^\S\t\n\r]{4}
will match white space characters in groups of 4 (excluding tabs and newline characters). The replace field \t
indicates you would like to replace them with tabs.
If you click the button to the right of the Where field, you'll see options that will help you target your search, replace. Add Folder
option will let you select the folder you'd like to recursively search from. The Add Include Filter
option will let you restrict the search to files of a certain extension.
it's simple only you have do is to give
background: rgba(0,0,0,0.3)
& for IE use this filter
background: transparent;
zoom: 1;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#4C000000,endColorstr=#4C000000); /* IE 6 & 7 */
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#4C000000,endColorstr=#4C000000)"; /* IE8 */
you can generate your rgba filter from here http://kimili.com/journal/rgba-hsla-css-generator-for-internet-explorer/
There is another answer here that also fits the authors request: 'compile-time' way to get all property names defined interface
If you use the plugin ts-transformer-keys and an Interface to your class you can get all the keys for the class.
But if you're using Angular or React then in some scenarios there is additional configuration necessary (webpack and typescript) to get it working: https://github.com/kimamula/ts-transformer-keys/issues/4
The problem with standard pings is they're ICMP, which a lot of places don't let through for security and traffic reasons. That might explain the failure.
Ruby prior to 1.9 had a TCP-based ping.rb
, which will run with Ruby 1.9+. All you have to do is copy it from the 1.8.7 installation to somewhere else. I just confirmed that it would run by pinging my home router.
Instead of using -c, just pipe it to wc -l.
grep string * | wc -l
This will list each occurrence on a single line and then count the number of lines.
This will miss instances where the string occurs 2+ times on one line, though.
That would be the modulo operator, which produces the remainder of the division of two numbers.
Your additional threads must be initiated from the same app that is called by the WSGI server.
The example below creates a background thread that executes every 5 seconds and manipulates data structures that are also available to Flask routed functions.
import threading
import atexit
from flask import Flask
POOL_TIME = 5 #Seconds
# variables that are accessible from anywhere
commonDataStruct = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
yourThread = threading.Thread()
def create_app():
app = Flask(__name__)
def interrupt():
global yourThread
yourThread.cancel()
def doStuff():
global commonDataStruct
global yourThread
with dataLock:
# Do your stuff with commonDataStruct Here
# Set the next thread to happen
yourThread = threading.Timer(POOL_TIME, doStuff, ())
yourThread.start()
def doStuffStart():
# Do initialisation stuff here
global yourThread
# Create your thread
yourThread = threading.Timer(POOL_TIME, doStuff, ())
yourThread.start()
# Initiate
doStuffStart()
# When you kill Flask (SIGTERM), clear the trigger for the next thread
atexit.register(interrupt)
return app
app = create_app()
Call it from Gunicorn with something like this:
gunicorn -b 0.0.0.0:5000 --log-config log.conf --pid=app.pid myfile:app
in html/js context, on modern browsers, with other iterable objects than Arrays we could also use [Iterable].entries():
for(let [index, element] of document.querySelectorAll('div').entries()) {
element.innerHTML = '#' + index
}
It's due to the fact that you have one long word without spaces. You can use the word-wrap
property to cause the text to break:
#w74 { word-wrap: break-word; }
It has fairly good browser support, too. See documentation about it here.
To expand upon nosklo's explanation:
a = {}
b = ['some', 'list']
a[b] = 'some' # this won't work
a[tuple(b)] = 'some' # this will, same as a['some', 'list']
In Bash shell:
#!/bin/sh
COUNTER=1
while [ $COUNTER -lt 254 ]
do
ping 192.168.1.$COUNTER -c 1
COUNTER=$(( $COUNTER + 1 ))
done
I added the spring folder to the build path and, after clean&build, it worked.
Here is a simple example that should let you keep going add somethink that would act as a placeholder to your winform can be TableLayoutPanel
and then just add controls to it
for ( int i = 0; i < COUNT; i++ ) {
Label lblTitle = new Label();
lblTitle.Text = i+"Your Text";
youlayOut.Controls.Add( lblTitle, 0, i );
TextBox txtValue = new TextBox();
youlayOut.Controls.Add( txtValue, 2, i );
}
Another simple and complete example of turning the recursive function into iterative one using the stack.
#include <iostream>
#include <stack>
using namespace std;
int GCD(int a, int b) { return b == 0 ? a : GCD(b, a % b); }
struct Par
{
int a, b;
Par() : Par(0, 0) {}
Par(int _a, int _b) : a(_a), b(_b) {}
};
int GCDIter(int a, int b)
{
stack<Par> rcstack;
if (b == 0)
return a;
rcstack.push(Par(b, a % b));
Par p;
while (!rcstack.empty())
{
p = rcstack.top();
rcstack.pop();
if (p.b == 0)
continue;
rcstack.push(Par(p.b, p.a % p.b));
}
return p.a;
}
int main()
{
//cout << GCD(24, 36) << endl;
cout << GCDIter(81, 36) << endl;
cin.get();
return 0;
}
<select name="city">
<option value ="0">What is your city</option>
<option value ="1">Sydney</option>
<option value ="2">Melbourne</option>
<option value ="3">Cromwell</option>
<option value ="4">Queenstown</option>
</select>
You can use the unique id for the value instead
Just paste the below formula in any of the cells, it will render the path of the file:
=LEFT(CELL("filename"),FIND("]",CELL("filename"),1))
The above formula works in any version of Excel.
You can pass an ArrayList<E>
the same way, if the E
type is Serializable
.
You would call the putExtra (String name, Serializable value)
of Intent
to store, and getSerializableExtra (String name)
for retrieval.
Example:
ArrayList<String> myList = new ArrayList<String>();
intent.putExtra("mylist", myList);
In the other Activity:
ArrayList<String> myList = (ArrayList<String>) getIntent().getSerializableExtra("mylist");
Consider using the following which its far better than the accepted answer
DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate == null
? DateTime.Now : (DateTime)_objHotelPackageOrder.UpdatedDate;
$('#div_id').css({marginTop: '-=15px'});
This will alter the css for the element with the id "div_id"
To get the effect you want I recommend adding the code above to a callback function in your animation (that way the div will be moved up after the animation is complete):
$('#div_id').animate({...}, function () {
$('#div_id').css({marginTop: '-=15px'});
});
And of course you could animate the change in margin like so:
$('#div_id').animate({marginTop: '-=15px'});
Here are the docs for .css()
in jQuery: http://api.jquery.com/css/
And here are the docs for .animate()
in jQuery: http://api.jquery.com/animate/
If you have multiple inputs as text in a form or a table that you need to iterate through, I did this:
var $list = $("#tableOrForm :input[type='text']");
$list.each(function(){
// Go on with your code.
});
What I did was I checked each input to see if the type is set to "text", then it'll grab that element and store it in the jQuery list. Then, it would iterate through that list. You can set a temp variable for the current iteration like this:
var $currentItem = $(this);
This will set the current item to the current iteration of your for each loop. Then you can do whatever you want with the temp variable.
Hope this helps anyone!
You can use SHOW
:
SHOW max_connections;
This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf
as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf
in your current session:
RESET max_connections;
However, not applicable to this particular setting. The manual:
This parameter can only be set at server start.
To see all settings:
SHOW ALL;
There is also pg_settings
:
The view
pg_settings
provides access to run-time parameters of the server. It is essentially an alternative interface to theSHOW
andSET
commands. It also provides access to some facts about each parameter that are not directly available fromSHOW
, such as minimum and maximum values.
For your original request:
SELECT *
FROM pg_settings
WHERE name = 'max_connections';
Finally, there is current_setting()
, which can be nested in DML statements:
SELECT current_setting('max_connections');
Related:
In the upcoming Python 3.10
release schedule
, with the new pairwise
function it's possible to slide through pairs of elements and thus map on rolling pairs:
from itertools import pairwise
[y-x for (x, y) in pairwise([1, 3, 6, 7])]
# [2, 3, 1]
The intermediate result being:
pairwise([1, 3, 6, 7])
# [(1, 3), (3, 6), (6, 7)]
Not the most pretty code, but the following will pick an appropriate font size for a JLabel
called label
such that the text inside will fit the interior as much as possible without overflowing the label:
Font labelFont = label.getFont();
String labelText = label.getText();
int stringWidth = label.getFontMetrics(labelFont).stringWidth(labelText);
int componentWidth = label.getWidth();
// Find out how much the font can grow in width.
double widthRatio = (double)componentWidth / (double)stringWidth;
int newFontSize = (int)(labelFont.getSize() * widthRatio);
int componentHeight = label.getHeight();
// Pick a new font size so it will not be larger than the height of label.
int fontSizeToUse = Math.min(newFontSize, componentHeight);
// Set the label's font size to the newly determined size.
label.setFont(new Font(labelFont.getName(), Font.PLAIN, fontSizeToUse));
Basically, the code looks at how much space the text in the JLabel
takes up by using the FontMetrics
object, and then uses that information to determine the largest font size that can be used without overflowing the text from the JLabel
.
The above code can be inserted into perhaps the paint
method of the JFrame
which holds the JLabel
, or some method which will be invoked when the font size needs to be changed.
The following is an screenshot of the above code in action:
(source: coobird.net)
Just for the hell of it I've done a bit of hacking on a script that does things purely textually, purely in Bash. I hope I caught all the edge cases.
Note that the ${var//pat/repl}
that I mentioned in the other answer doesn't work since you can't make it replace only the shortest possible match, which is a problem for replacing /foo/../
as e.g. /*/../
will take everything before it, not just a single entry. And since these patterns aren't really regexes I don't see how that can be made to work. So here's the nicely convoluted solution I came up with, enjoy. ;)
By the way, let me know if you find any unhandled edge cases.
#!/bin/bash
canonicalize_path() {
local path="$1"
OIFS="$IFS"
IFS=$'/'
read -a parts < <(echo "$path")
IFS="$OIFS"
local i=${#parts[@]}
local j=0
local back=0
local -a rev_canon
while (($i > 0)); do
((i--))
case "${parts[$i]}" in
""|.) ;;
..) ((back++));;
*) if (($back > 0)); then
((back--))
else
rev_canon[j]="${parts[$i]}"
((j++))
fi;;
esac
done
while (($j > 0)); do
((j--))
echo -n "/${rev_canon[$j]}"
done
echo
}
canonicalize_path "/.././..////../foo/./bar//foo/bar/.././bar/../foo/bar/./../..//../foo///bar/"
I also had the same issue, trying to run a unit test calling code that uses readEntity
. Can't use getEntity
in production code because that just returns a ByteInputStream
and not the content of the body and there is no way I am adding production code that is hit only in unit tests.
My solution was to create a response and then use a Mockito spy to mock out the readEntity
method:
Response error = Response.serverError().build();
Response mockResponse = spy(error);
doReturn("{jsonbody}").when(mockResponse).readEntity(String.class);
Note that you can't use the when(mockResponse.readEntity(String.class)
option because that throws the same IllegalStateException
.
Hope this helps!
Still I wonder if there's a more convenient way of finding index of en element without caching (or there's a good caching technique that will boost up the performance).
You can use binary search (if your array is ordered and the values you store in the array are comparable in some way). For that to work you need to be able to tell the binary search whether it should be looking "to the left" or "to the right" of the current element. But I believe there is nothing wrong with storing the index
at insertion time and then using it if you are getting the element from the same array.
In my case deleting the .gradle folder worked for me.
You should try
if (row.Table.Columns.Contains("US_OTHERFRIEND"))
I don't believe that row has a columns property itself.
Insert the image inside a with position: relative;
and overflow: hidden;
HTML
<div><img src="#"></div>
CSS
div {
position: relative;
overflow: hidden;
}
img {
filter: blur(5px);
-webkit-filter: blur(5px);
-moz-filter: blur(5px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
}
This also works on variable sizes elements, like dynamic div's.
Extend LinearLayout/RelativeLayout and use it straight on the XML
package com.pkg_name ;
...imports...
public class LinearLayoutOutlined extends LinearLayout {
Paint paint;
public LinearLayoutOutlined(Context context) {
super(context);
// TODO Auto-generated constructor stub
setWillNotDraw(false) ;
paint = new Paint();
}
public LinearLayoutOutlined(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
setWillNotDraw(false) ;
paint = new Paint();
}
@Override
protected void onDraw(Canvas canvas) {
/*
Paint fillPaint = paint;
fillPaint.setARGB(255, 0, 255, 0);
fillPaint.setStyle(Paint.Style.FILL);
canvas.drawPaint(fillPaint) ;
*/
Paint strokePaint = paint;
strokePaint.setARGB(255, 255, 0, 0);
strokePaint.setStyle(Paint.Style.STROKE);
strokePaint.setStrokeWidth(2);
Rect r = canvas.getClipBounds() ;
Rect outline = new Rect( 1,1,r.right-1, r.bottom-1) ;
canvas.drawRect(outline, strokePaint) ;
}
}
<?xml version="1.0" encoding="utf-8"?>
<com.pkg_name.LinearLayoutOutlined
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width=...
android:layout_height=...
>
... your widgets here ...
</com.pkg_name.LinearLayoutOutlined>
does the later approach save computation time and memory?
There is no big difference between those two examples that you provided. The first example cuts the video sequentially, in 2 steps, while the second example does it at the same time (using threads). No particular speed-up will be noticeable. You can read more about creating multiple outputs with FFmpeg
Further more, what you can use (in recent FFmpeg) is the stream segmenter muxer which can:
output streams to a number of separate files of nearly fixed duration. Output filename pattern can be set in a fashion similar to image2.
Check ur code signing section.make sure that the code signing is iPhoneDeveloper code signe
I've compared the different options for speed and found that – much to my surprise – all options (except diag
) are equally fast. I personally use
A * b[:, None]
(or (A.T * b).T
) because it's short.
Code to reproduce the plot:
import numpy
import perfplot
def newaxis(data):
A, b = data
return A * b[:, numpy.newaxis]
def none(data):
A, b = data
return A * b[:, None]
def double_transpose(data):
A, b = data
return (A.T * b).T
def double_transpose_contiguous(data):
A, b = data
return numpy.ascontiguousarray((A.T * b).T)
def diag_dot(data):
A, b = data
return numpy.dot(numpy.diag(b), A)
def einsum(data):
A, b = data
return numpy.einsum("ij,i->ij", A, b)
perfplot.save(
"p.png",
setup=lambda n: (numpy.random.rand(n, n), numpy.random.rand(n)),
kernels=[
newaxis,
none,
double_transpose,
double_transpose_contiguous,
diag_dot,
einsum,
],
n_range=[2 ** k for k in range(13)],
xlabel="len(A), len(b)",
)
cd to the directory that contains the script, or put it in a bin folder that is in your $PATH
then type
./scriptname.sh
if in the same directory or
scriptname.sh
if it's in the bin folder.
Try this
TextWatcher changeText = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
tv3.setText(et.getText().toString());
tv3.post(new Runnable() {
@Override
public void run() {
while(tv3.getLineCount() >= 3){
tv3.setTextSize((tv3.getTextSize())-1);
}
}
});
}
@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override public void afterTextChanged(Editable s) { }
};
You can use scalar multiplication to modify each element in your vector.
> r <- 0:10
> r <- r * 2
> r
[1] 0 2 4 6 8 10 12 14 16 18 20
or
> r <- 0:10 * 2
> r
[1] 0 2 4 6 8 10 12 14 16 18 20
In my case, I wanted to add UIImage
to the right and UILabel
to the left. Maybe I can achieve that by writing code (like the above mentioned), but I prefer not to write code and get it done by using the storyboard
as much as possible. So this is how did it:
First, write down something in your label box and select an image that you want to show:
And that will create a button looking like this:
Next, look for Semantic
and select Force Right-to-Left (If you don't specify anything, then it will show the image to the left and label to the right like the above image):
Finally, you'll see UIImage
to the right and UILabel
to the left:
To add space between a label and an image, go to the Size inspector and change those values depending on your requirement:
That's it!
Try putting \
at the end of each line before copying it.
Example:
echo "Hello world" && \
script_b.sh
echo $?
The exit code ($?
) is now the full sequence of commands, and not just the last command.
I am using Debian 8 live off a USB. I was locked out of the system after 10 min of inactivity. The password that was required to log back in to the system for the user was:
login : Debian Live User
password : live
I hope this helps
Notice that "cex" does change things when the plot is made with text. For example, the plot of an agglomerative hierarchical clustering:
library(cluster)
data(votes.repub)
agn1 <- agnes(votes.repub, metric = "manhattan", stand = TRUE)
plot(agn1, which.plots=2)
will produce a plot with normal sized text:
and plot(agn1, which.plots=2, cex=0.5)
will produce this one:
Try using a simple HttpResponseMessage
with its Content
property set to a StreamContent
:
// using System.IO;
// using System.Net.Http;
// using System.Net.Http.Headers;
public HttpResponseMessage Post(string version, string environment,
string filetype)
{
var path = @"C:\Temp\test.exe";
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}
A few things to note about the stream
used:
You must not call stream.Dispose()
, since Web API still needs to be able to access it when it processes the controller method's result
to send data back to the client. Therefore, do not use a using (var stream = …)
block. Web API will dispose the stream for you.
Make sure that the stream has its current position set to 0 (i.e. the beginning of the stream's data). In the above example, this is a given since you've only just opened the file. However, in other scenarios (such as when you first write some binary data to a MemoryStream
), make sure to stream.Seek(0, SeekOrigin.Begin);
or set stream.Position = 0;
With file streams, explicitly specifying FileAccess.Read
permission can help prevent access rights issues on web servers; IIS application pool accounts are often given only read / list / execute access rights to the wwwroot.
pointer1 = pointer2
, you give pointer1 the address of pointer2.but! if you do that within a function, and you want the result to persist after the function is done, you need do some extra work. you need a new pointer3 just to point to pointer1. pass pointer3 to the function.
here is an example. look at the output below first, to understand.
#include <stdio.h>
int main()
{
int c = 1;
int d = 2;
int e = 3;
int * a = &c;
int * b = &d;
int * f = &e;
int ** pp = &a; // pointer to pointer 'a'
printf("\n a's value: %x \n", a);
printf("\n b's value: %x \n", b);
printf("\n f's value: %x \n", f);
printf("\n can we change a?, lets see \n");
printf("\n a = b \n");
a = b;
printf("\n a's value is now: %x, same as 'b'... it seems we can, but can we do it in a function? lets see... \n", a);
printf("\n cant_change(a, f); \n");
cant_change(a, f);
printf("\n a's value is now: %x, Doh! same as 'b'... that function tricked us. \n", a);
printf("\n NOW! lets see if a pointer to a pointer solution can help us... remember that 'pp' point to 'a' \n");
printf("\n change(pp, f); \n");
change(pp, f);
printf("\n a's value is now: %x, YEAH! same as 'f'... that function ROCKS!!!. \n", a);
return 0;
}
void cant_change(int * x, int * z){
x = z;
printf("\n ----> value of 'a' is: %x inside function, same as 'f', BUT will it be the same outside of this function? lets see\n", x);
}
void change(int ** x, int * z){
*x = z;
printf("\n ----> value of 'a' is: %x inside function, same as 'f', BUT will it be the same outside of this function? lets see\n", *x);
}
Here is the output: (read this first)
a's value: bf94c204
b's value: bf94c208
f's value: bf94c20c
can we change a?, lets see
a = b
a's value is now: bf94c208, same as 'b'... it seems we can, but can we do it in a function? lets see...
cant_change(a, f);
----> value of 'a' is: bf94c20c inside function, same as 'f', BUT will it be the same outside of this function? lets see
a's value is now: bf94c208, Doh! same as 'b'... that function tricked us.
NOW! lets see if a pointer to a pointer solution can help us... remember that 'pp' point to 'a'
change(pp, f);
----> value of 'a' is: bf94c20c inside function, same as 'f', BUT will it be the same outside of this function? lets see
a's value is now: bf94c20c, YEAH! same as 'f'... that function ROCKS!!!.
Based on twitter scroll trouble (http://ejohn.org/blog/learning-from-twitter/).
Here is my solution, throttling the js scroll event (usefull for mobile devices)
JS:
$(function() {
var $document, didScroll, offset;
offset = $('.menu').position().top;
$document = $(document);
didScroll = false;
$(window).on('scroll touchmove', function() {
return didScroll = true;
});
return setInterval(function() {
if (didScroll) {
$('.menu').toggleClass('fixed', $document.scrollTop() > offset);
return didScroll = false;
}
}, 250);
});
CSS:
.menu {
background: pink;
top: 5px;
}
.fixed {
width: 100%;
position: fixed;
top: 0;
}
HTML:
<div class="menu">MENU FIXED ON TOP</div>
Here is how the default implementation (ASP.NET Framework or ASP.NET Core) works. It uses a Key Derivation Function with random salt to produce the hash. The salt is included as part of the output of the KDF. Thus, each time you "hash" the same password you will get different hashes. To verify the hash the output is split back to the salt and the rest, and the KDF is run again on the password with the specified salt. If the result matches to the rest of the initial output the hash is verified.
Hashing:
public static string HashPassword(string password)
{
byte[] salt;
byte[] buffer2;
if (password == null)
{
throw new ArgumentNullException("password");
}
using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, 0x10, 0x3e8))
{
salt = bytes.Salt;
buffer2 = bytes.GetBytes(0x20);
}
byte[] dst = new byte[0x31];
Buffer.BlockCopy(salt, 0, dst, 1, 0x10);
Buffer.BlockCopy(buffer2, 0, dst, 0x11, 0x20);
return Convert.ToBase64String(dst);
}
Verifying:
public static bool VerifyHashedPassword(string hashedPassword, string password)
{
byte[] buffer4;
if (hashedPassword == null)
{
return false;
}
if (password == null)
{
throw new ArgumentNullException("password");
}
byte[] src = Convert.FromBase64String(hashedPassword);
if ((src.Length != 0x31) || (src[0] != 0))
{
return false;
}
byte[] dst = new byte[0x10];
Buffer.BlockCopy(src, 1, dst, 0, 0x10);
byte[] buffer3 = new byte[0x20];
Buffer.BlockCopy(src, 0x11, buffer3, 0, 0x20);
using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, dst, 0x3e8))
{
buffer4 = bytes.GetBytes(0x20);
}
return ByteArraysEqual(buffer3, buffer4);
}
I think that you have Spring Security on your class path and then spring security is automatically configured with a default user and generated password
Please look into your pom.xml file for:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
If you have that in your pom than you should have a log console message like this:
Using default security password: ce6c3d39-8f20-4a41-8e01-803166bb99b6
And in the browser prompt you will import the user user
and the password printed in the console.
Or if you want to configure spring security you can take a look at Spring Boot secured example
It is explained in the Spring Boot Reference documentation in the Security section, it indicates:
The default AuthenticationManager has a single user (‘user’ username and random password, printed at `INFO` level when the application starts up)
Using default security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35
We have Collection as below:
Syntax:
{{(Collection/array/list | filter:{Value : (object value)})[0].KeyName}}
Example:
{{(Collectionstatus | filter:{Value:dt.Status})[0].KeyName}}
-OR-
Syntax:
ng-bind="(input | filter)"
Example:
ng-bind="(Collectionstatus | filter:{Value:dt.Status})[0].KeyName"
Position your <div>
absolutely at the bottom and don't forget to give div.A
a position: relative
- http://jsfiddle.net/TTaMx/
.A {
position: relative;
margin: 40px 0;
height: 40px;
width: 200px;
background: #eee;
}
.A:after {
content: " ";
display: block;
background: #c00;
height: 29px;
width: 100%;
position: absolute;
bottom: -29px;
}?
You should look into Video For Everyone:
Video for Everybody is very simply a chunk of HTML code that embeds a video into a website using the HTML5 element which offers native playback in Firefox 3.5 and Safari 3 & 4 and an increasing number of other browsers.
The video is played by the browser itself. It loads quickly and doesn’t threaten to crash your browser.
In other browsers that do not support , it falls back to QuickTime.
If QuickTime is not installed, Adobe Flash is used. You can host locally or embed any Flash file, such as a YouTube video.
The only downside, is that you have to have 2/3 versions of the same video stored, but you can serve to every existing device/browser that supports video (i.e.: the iPhone).
<video width="640" height="360" poster="__POSTER__.jpg" controls="controls">
<source src="__VIDEO__.mp4" type="video/mp4" />
<source src="__VIDEO__.webm" type="video/webm" />
<source src="__VIDEO__.ogv" type="video/ogg" /><!--[if gt IE 6]>
<object width="640" height="375" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"><!
[endif]--><!--[if !IE]><!-->
<object width="640" height="375" type="video/quicktime" data="__VIDEO__.mp4"><!--<![endif]-->
<param name="src" value="__VIDEO__.mp4" />
<param name="autoplay" value="false" />
<param name="showlogo" value="false" />
<object width="640" height="380" type="application/x-shockwave-flash"
data="__FLASH__.swf?image=__POSTER__.jpg&file=__VIDEO__.mp4">
<param name="movie" value="__FLASH__.swf?image=__POSTER__.jpg&file=__VIDEO__.mp4" />
<img src="__POSTER__.jpg" width="640" height="360" />
<p>
<strong>No video playback capabilities detected.</strong>
Why not try to download the file instead?<br />
<a href="__VIDEO__.mp4">MPEG4 / H.264 “.mp4” (Windows / Mac)</a> |
<a href="__VIDEO__.ogv">Ogg Theora & Vorbis “.ogv” (Linux)</a>
</p>
</object><!--[if gt IE 6]><!-->
</object><!--<![endif]-->
</video>
There is an updated version that is a bit more readable:
<!-- "Video For Everybody" v0.4.1 by Kroc Camen of Camen Design <camendesign.com/code/video_for_everybody>
=================================================================================================================== -->
<!-- first try HTML5 playback: if serving as XML, expand `controls` to `controls="controls"` and autoplay likewise -->
<!-- warning: playback does not work on iPad/iPhone if you include the poster attribute! fixed in iOS4.0 -->
<video width="640" height="360" controls preload="none">
<!-- MP4 must be first for iPad! -->
<source src="__VIDEO__.MP4" type="video/mp4" /><!-- WebKit video -->
<source src="__VIDEO__.webm" type="video/webm" /><!-- Chrome / Newest versions of Firefox and Opera -->
<source src="__VIDEO__.OGV" type="video/ogg" /><!-- Firefox / Opera -->
<!-- fallback to Flash: -->
<object width="640" height="384" type="application/x-shockwave-flash" data="__FLASH__.SWF">
<!-- Firefox uses the `data` attribute above, IE/Safari uses the param below -->
<param name="movie" value="__FLASH__.SWF" />
<param name="flashvars" value="image=__POSTER__.JPG&file=__VIDEO__.MP4" />
<!-- fallback image. note the title field below, put the title of the video there -->
<img src="__VIDEO__.JPG" width="640" height="360" alt="__TITLE__"
title="No video playback capabilities, please download the video below" />
</object>
</video>
<!-- you *must* offer a download link as they may be able to play the file locally. customise this bit all you want -->
<p> <strong>Download Video:</strong>
Closed Format: <a href="__VIDEO__.MP4">"MP4"</a>
Open Format: <a href="__VIDEO__.OGV">"OGG"</a>
</p>
With your requirements you don't need BEGIN END
and IF
with unnecessary SELECT
in your trigger. So you can simplify it to this
CREATE TRIGGER occupy_trig AFTER INSERT ON occupiedroom
FOR EACH ROW
UPDATE BookingRequest
SET status = 1
WHERE idRequest = NEW.idRequest;
Use something like the following on the server side:
http.createServer(function (request, response) {
if (request.headers['x-requested-with'] == 'XMLHttpRequest') {
// handle async request
var u = url.parse(request.url, true); //not needed
response.writeHead(200, {'content-type':'text/json'})
response.end(JSON.stringify(some_array.slice(1, 10))) //send elements 1 to 10
} else {
// handle sync request (by server index.html)
if (request.url == '/') {
response.writeHead(200, {'content-type': 'text/html'})
util.pump(fs.createReadStream('index.html'), response)
}
else
{
// 404 error
}
}
}).listen(31337)
T-SQL
/*
Stored Procedure GetstudentnameInOutputVariable is modified to collect the
email address of the student with the help of the Alert Keyword
*/
CREATE PROCEDURE GetstudentnameInOutputVariable
(
@studentid INT, --Input parameter , Studentid of the student
@studentname VARCHAR (200) OUT, -- Output parameter to collect the student name
@StudentEmail VARCHAR (200)OUT -- Output Parameter to collect the student email
)
AS
BEGIN
SELECT @studentname= Firstname+' '+Lastname,
@StudentEmail=email FROM tbl_Students WHERE studentid=@studentid
END
The reason is simple, your call to ConfigurationSettings.AppSettings
is not returning the required config file. Please try any of the following ways:
ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location).AppSettings["StartingMonthColumn"]
Hope this helps
ALTER TABLE `{$installer->getTable('sales/quote_payment')}`
ADD `custom_field_one` VARCHAR( 255 ) NOT NULL,
ADD `custom_field_two` VARCHAR( 255 ) NOT NULL;
Add backtick i.e. " ` " properly. Write your getTable name and column name between backtick.
UPDATE: As Joel Coehoorn and others suggest, starting at .NET Framework 4.0, you can just check Environment.Is64BitOperatingSystem
.
IntPtr.Size won't return the correct value if running in 32-bit .NET Framework 2.0 on 64-bit Windows (it would return 32-bit).
As Microsoft's Raymond Chen describes, you have to first check if running in a 64-bit process (I think in .NET you can do so by checking IntPtr.Size), and if you are running in a 32-bit process, you still have to call the Win API function IsWow64Process. If this returns true, you are running in a 32-bit process on 64-bit Windows.
Microsoft's Raymond Chen: How to detect programmatically whether you are running on 64-bit Windows
My solution:
static bool is64BitProcess = (IntPtr.Size == 8);
static bool is64BitOperatingSystem = is64BitProcess || InternalCheckIsWow64();
[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsWow64Process(
[In] IntPtr hProcess,
[Out] out bool wow64Process
);
public static bool InternalCheckIsWow64()
{
if ((Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor >= 1) ||
Environment.OSVersion.Version.Major >= 6)
{
using (Process p = Process.GetCurrentProcess())
{
bool retVal;
if (!IsWow64Process(p.Handle, out retVal))
{
return false;
}
return retVal;
}
}
else
{
return false;
}
}
The following code shows how you can use toolhelp and OpenProcess to get a handle to the process. Error handling removed for brevity.
HANDLE GetProcessByName(PCSTR name)
{
DWORD pid = 0;
// Create toolhelp snapshot.
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 process;
ZeroMemory(&process, sizeof(process));
process.dwSize = sizeof(process);
// Walkthrough all processes.
if (Process32First(snapshot, &process))
{
do
{
// Compare process.szExeFile based on format of name, i.e., trim file path
// trim .exe if necessary, etc.
if (string(process.szExeFile) == string(name))
{
pid = process.th32ProcessID;
break;
}
} while (Process32Next(snapshot, &process));
}
CloseHandle(snapshot);
if (pid != 0)
{
return OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
}
// Not found
return NULL;
}
There are basically two most popular answers. The first one basically says
Optimistic needs a three-tier architectures where you do not necessarily maintain a connection to the database for your session whereas Pessimistic Locking is when you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking you need either a direct connection to the database.
optimistic (versioning) is faster because of no locking but (pessimistic) locking performs better when contention is high and it is better to prevent the work rather than discard it and start over.
or
Optimistic locking works best when you have rare collisions
As it is put on this page.
I created my answer to explain how "keep connection" is related to "low collisions".
To understand which strategy is best for you, think not about the Transactions Per Second your DB has but the duration of a single transaction. Normally, you open trasnaction, performa operation and close the transaction. This is a short, classical transaction ANSI had in mind and fine to get away with locking. But, how do you implement a ticket reservation system where many clients reserve the same rooms/seats at the same time?
You browse the offers, fill in the form with lots of available options and current prices. It takes a lot of time and options can become obsolete, all the prices invalid between you started to fill the form and press "I agree" button because there was no lock on the data you have accessed and somebody else, more agile, has intefered changing all the prices and you need to restart with new prices.
You could lock all the options as you read them, instead. This is pessimistic scenario. You see why it sucks. Your system can be brought down by a single clown who simply starts a reservation and goes smoking. Nobody can reserve anything before he finishes. Your cash flow drops to zero. That is why, optimistic reservations are used in reality. Those who dawdle too long have to restart their reservation at higher prices.
In this optimistic approach you have to record all the data that you read (as in mine Repeated Read) and come to the commit point with your version of data (I want to buy shares at the price you displayed in this quote, not current price). At this point, ANSI transaction is created, which locks the DB, checks if nothing is changed and commits/aborts your operation. IMO, this is effective emulation of MVCC, which is also associated with Optimistic CC and also assumes that your transaction restarts in case of abort, that is you will make a new reservation. A transaction here involves a human user decisions.
I am far from understanding how to implement the MVCC manually but I think that long-running transactions with option of restart is the key to understanding the subject. Correct me if I am wrong anywhere. My answer was motivated by this Alex Kuznecov chapter.
In the 'old days' you'd use a table and your menu items would be evenly spaced without having to explicitly state the width for the number of items.
If it wasn't for IE 6 and 7 (if that is of concern) then you can do the same in CSS.
<div class="demo">
<span>Span 1</span>
<span>Span 2</span>
<span>Span 3</span>
</div>
CSS:
div.demo {
display: table;
width: 100%;
table-layout: fixed; /* For cells of equal size */
}
div.demo span {
display: table-cell;
text-align: center;
}
Without having to adjust for the number of items.
Example without table-layout:fixed
- the cells are evenly distributed across the full width, but they are not necessarily of equal size since their width is determined by their contents.
Example with table-layout:fixed
- the cells are of equal size, regardless of their contents. (Thanks to @DavidHerse in comments for this addition.)
If you want the first and last menu elements to be left and right justified, then you can add the following CSS:
div.demo span:first-child {
text-align: left;
}
div.demo span:last-child {
text-align: right;
}
Since some of the other answers include info on rebuilding, and my use case also required a rebuild, I had a better solution (compared to those).
There's still a way to easily target just the one single worker
container that both rebuilds + restarts it in a single line, albeit it's not actually a single command. The best solution for me was simply rebuild and restart:
docker-compose build worker && docker-compose restart worker
This accomplishes both major goals at once for me:
worker
containerHope this helps anyone else getting here.