According to nginx documentation
there is no syntax for NOT matching a regular expression. Instead, match the target regular expression and assign an empty block, then use location / to match anything else
So you could define something like
location ~ (dir1|file2\.php) {
# empty
}
location / {
rewrite ^/(.*) http://example.com/$1 permanent;
}
Make sure the JSON output is in a <pre>
tag.
and
, or
:Let's first define a useful function to determine if something is executed or not. A simple function that accepts an argument, prints a message and returns the input, unchanged.
>>> def fun(i):
... print "executed"
... return i
...
One can observe the Python's short-circuiting behavior of and
, or
operators in the following example:
>>> fun(1)
executed
1
>>> 1 or fun(1) # due to short-circuiting "executed" not printed
1
>>> 1 and fun(1) # fun(1) called and "executed" printed
executed
1
>>> 0 and fun(1) # due to short-circuiting "executed" not printed
0
Note: The following values are considered by the interpreter to mean false:
False None 0 "" () [] {}
any()
, all()
:Python's any()
and all()
functions also support short-circuiting. As shown in the docs; they evaluate each element of a sequence in-order, until finding a result that allows an early exit in the evaluation. Consider examples below to understand both.
The function any()
checks if any element is True. It stops executing as soon as a True is encountered and returns True.
>>> any(fun(i) for i in [1, 2, 3, 4]) # bool(1) = True
executed
True
>>> any(fun(i) for i in [0, 2, 3, 4])
executed # bool(0) = False
executed # bool(2) = True
True
>>> any(fun(i) for i in [0, 0, 3, 4])
executed
executed
executed
True
The function all()
checks all elements are True and stops executing as soon as a False is encountered:
>>> all(fun(i) for i in [0, 0, 3, 4])
executed
False
>>> all(fun(i) for i in [1, 0, 3, 4])
executed
executed
False
Additionally, in Python
Comparisons can be chained arbitrarily; for example,
x < y <= z
is equivalent tox < y and y <= z
, except thaty
is evaluated only once (but in both casesz
is not evaluated at all whenx < y
is found to be false).
>>> 5 > 6 > fun(3) # same as: 5 > 6 and 6 > fun(3)
False # 5 > 6 is False so fun() not called and "executed" NOT printed
>>> 5 < 6 > fun(3) # 5 < 6 is True
executed # fun(3) called and "executed" printed
True
>>> 4 <= 6 > fun(7) # 4 <= 6 is True
executed # fun(3) called and "executed" printed
False
>>> 5 < fun(6) < 3 # only prints "executed" once
executed
False
>>> 5 < fun(6) and fun(6) < 3 # prints "executed" twice, because the second part executes it again
executed
executed
False
Edit:
One more interesting point to note :- Logical and
, or
operators in Python returns an operand's value instead of a Boolean (True
or False
). For example:
Operation
x and y
gives the resultif x is false, then x, else y
Unlike in other languages e.g. &&
, ||
operators in C that return either 0 or 1.
Examples:
>>> 3 and 5 # Second operand evaluated and returned
5
>>> 3 and ()
()
>>> () and 5 # Second operand NOT evaluated as first operand () is false
() # so first operand returned
Similarly or
operator return left most value for which bool(value)
== True
else right most false value (according to short-circuiting behavior), examples:
>>> 2 or 5 # left most operand bool(2) == True
2
>>> 0 or 5 # bool(0) == False and bool(5) == True
5
>>> 0 or ()
()
So, how is this useful? One example is given in Practical Python By Magnus Lie Hetland:
Let’s say a user is supposed to enter his or her name, but may opt to enter nothing, in which case you want to use the default value '<Unknown>'
.
You could use an if statement, but you could also state things very succinctly:
In [171]: name = raw_input('Enter Name: ') or '<Unknown>'
Enter Name:
In [172]: name
Out[172]: '<Unknown>'
In other words, if the return value from raw_input
is true (not an empty string), it is assigned to name (nothing changes); otherwise, the default '<Unknown>'
is assigned to name
.
I tried to make to do the normalization a bit faster:
en, _ = glyphSmart(data)
func glyphSmart(text string) (int, int) {
gc := 0
dummy := 0
for ind, _ := range text {
gc++
dummy = ind
}
dummy = 0
return gc, dummy
}
Yes, it is possible to do with out rebinding by implementing INotifyPropertyChanged Interface.
Pretty Simple example is available here,
http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx
I would not recommend utilizing the Grid system in this instance, as much as simply adding an increased padding for each <h2>
. That being said, the way you would achieve this using col-*-offset-*
would be as follows:
<div class="jumbotron">
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>One</h2>
</div>
<div class="col-md-11 col-md-offset-1">
<h2>Two</h2>
</div>
<div class="col-md-10 col-md-offset-2">
<h2>Three</h2>
</div>
</div>
</div>
</div>
Essentially the first line must span the entire row (so -12). The second line must be offset by 1 column, so you offset by 1 and give it a total width of 11 columns (11+1 = 12) and so forth. Your offset is always enough to ensure that the total column count equals 12.
If you get this error when you try to pipe/redirect output of your script
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)
Just export PYTHONIOENCODING in console and then run your code.
export PYTHONIOENCODING=utf8
Handling key events consistently is not at all easy.
Firstly, there are two different types of codes: keyboard codes (a number representing the key on the keyboard the user pressed) and character codes (a number representing a Unicode character). You can only reliably get character codes in the keypress
event. Do not try to get character codes for keyup
and keydown
events.
Secondly, you get different sets of values in a keypress
event to what you get in a keyup
or keydown
event.
I recommend this page as a useful resource. As a summary:
If you're interested in detecting a user typing a character, use the keypress
event. IE bizarrely only stores the character code in keyCode
while all other browsers store it in which
. Some (but not all) browsers also store it in charCode
and/or keyCode
. An example keypress handler:
function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
alert(charStr);
}
If you're interested in detecting a non-printable key (such as a cursor key), use the keydown
event. Here keyCode
is always the property to use. Note that keyup
events have the same properties.
function(evt) {
evt = evt || window.event;
var keyCode = evt.keyCode;
// Check for left arrow key
if (keyCode == 37) {
alert("Left arrow");
}
}
It also happens if you're trying to access an instance when you have a pointer, and vice versa:
struct foo
{
int x, y, z;
};
struct foo a, *b = &a;
b.x = 12; /* This will generate the error, should be b->x or (*b).x */
As pointed out in a comment, this can be made excruciating if someone goes and typedef
s a pointer, i.e. includes the *
in a typedef, like so:
typedef struct foo* Foo;
Because then you get code that looks like it's dealing with instances, when in fact it's dealing with pointers:
Foo a_foo = get_a_brand_new_foo();
a_foo->field = FANTASTIC_VALUE;
Note how the above looks as if it should be written a_foo.field
, but that would fail since Foo
is a pointer to struct. I strongly recommend against typedef
:ed pointers in C. Pointers are important, don't hide your asterisks. Let them shine.
You can also just do this in all the activities that you dont want to transition from:
@Override
public void onPause() {
super.onPause();
overridePendingTransition(0, 0);
}
I like this approach because you do not have to mess with the style of your activity.
To remove a timezone (tzinfo) from a datetime object:
# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)
If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.
# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')
# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime
# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)
Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime
object to insert into the database. The solution is to convert your datetime.datetime
object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime
objects where one is timezone aware and another is timezone naive.
##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')
arrowDt = arrowObj.to("utc").datetime
# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)
# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()
# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3
# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True
Use
git clone --depth=1 --branch=master git://someserver/somerepo dirformynewrepo
rm -rf ./dirformynewrepo/.git
dirformynewrepo
not a Git repository any more.[self dismissModalViewControllerAnimated:NO];
has been deprecated.
Use [self dismissViewControllerAnimated:NO completion:nil];
instead.
The FolderBrowserDialog class is the best option.
Dude I know totally how you feel, but don't forget about inline styling. It is almost the super saiyan of the CSS specificity
So it should look something like this for you,
<span class="icon-bar" style="background-color: black !important;">
</span>
<span class="icon-bar" style="background-color: black !important;">
</span>
<span class="icon-bar" style="background-color: black !important;">
</span>
Agree with neubert about the DECLARE statements, this will fix syntax error. But I would suggest you to avoid using openning cursors, they may be slow.
For your task: use INSERT...SELECT statement which will help you to copy data from one table to another using only one query.
You may use the typescript getter method for this scenario. Like this
public get height() {
return window.innerHeight;
}
public get width() {
return window.innerWidth;
}
And use that in template like this:
<section [ngClass]="{ 'desktop-view': width >= 768, 'mobile-view': width < 768
}"></section>
Print the value
console.log(this.height, this.width);
You won't need any event handler to check for resizing of window, this method will check for size every time automatically.
Although Bootstrap CDN restored glyphicons to bootstrap.min.css, Bootstrap CDN's Bootswatch css files doesn't include glyphicons.
For example Amelia theme: http://bootswatch.com/amelia/
Default Amelia has glyphicons in this file: http://bootswatch.com/amelia/bootstrap.min.css
But Bootstrap CDN's css file doesn't include glyphicons: http://netdna.bootstrapcdn.com/bootswatch/3.0.0/amelia/bootstrap.min.css
So as @edsioufi mentioned, you should include you should include glphicons css, if you use Bootswatch files from the bootstrap CDN. File: http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css
Not understanding how a DBMS works under the hood.
You cannot properly drive a stick without understanding how a clutch works. And you cannot understand how to use a Database without understanding that you are really just writing to a file on your hard disk.
Specifically:
Do you know what a Clustered Index is? Did you think about it when you designed your schema?
Do you know how to use indexes properly? How to reuse an index? Do you know what a Covering Index is?
So great, you have indexes. How big is 1 row in your index? How big will the index be when you have a lot of data? Will that fit easily into memory? If it won't it's useless as an index.
Have you ever used EXPLAIN in MySQL? Great. Now be honest with yourself: Did you understand even half of what you saw? No, you probably didn't. Fix that.
Do you understand the Query Cache? Do you know what makes a query un-cachable?
Are you using MyISAM? If you NEED full text search, MyISAM's is crap anyway. Use Sphinx. Then switch to Inno.
I think that what you want to do is turn the JSON string back into an object when it arrives back in your XMLHttpRequest - correct?
If so, you need to eval the string to turn it into a JavaScript object - note that this can be unsafe as you're trusting that the JSON string isn't malicious and therefore executing it. Preferably you could use jQuery's parseJSON
Yes there is a way to do it.
First declare a class.
//anyfile.ts
export class Custom
{
name: string,
empoloyeeID: number
}
Then in your component import the class
import {Custom} from '../path/to/anyfile.ts'
.....
export class FormComponent implements OnInit {
name: string;
empoloyeeID : number;
empList: Array<Custom> = [];
constructor() {
}
ngOnInit() {
}
onEmpCreate(){
//console.log(this.name,this.empoloyeeID);
let customObj = new Custom();
customObj.name = "something";
customObj.employeeId = 12;
this.empList.push(customObj);
this.name ="";
this.empoloyeeID = 0;
}
}
Another way would be to interfaces read the documentation once - https://www.typescriptlang.org/docs/handbook/interfaces.html
Also checkout this question, it is very interesting - When to use Interface and Model in TypeScript / Angular2
If you're printing to stdout, it depends on the terminal you're printing to. You can use ansi escape codes on xterms and other similar terminal emulators. Here's a bash code snippet that will print all 255 colors supported by xterm, putty and Konsole:
for ((i=0;i<256;i++)); do echo -en "\e[38;5;"$i"m"$i" "; done
You can use these escape codes in any programming language. It's better to rely on a library that will decide which codes to use depending on architecture and the content of the TERM environment variable.
Here try this it works 100%
<html>
<body>
<script>
var warning = true;
window.onbeforeunload = function() {
if (warning) {
return "You have made changes on this page that you have not yet confirmed. If you navigate away from this page you will lose your unsaved changes";
}
}
$('form').submit(function() {
window.onbeforeunload = null;
});
</script>
</body>
</html>
If your goal is to deploy your Spring Boot application to AWS, Boxfuse gives you a very easy solution.
All you need to do is:
boxfuse run my-spring-boot-app-1.0.jar -env=prod
This will:
All images are generated in seconds and are immutable. They can be run unchanged on VirtualBox (dev) and AWS (test & prod).
All updates are performed as zero-downtime blue/green deployments and you can also enable auto-scaling with just one command.
Boxfuse also understands your Spring Boot config will automatically configure security groups and ELB health checks based upon your application.properties
.
Here is a tutorial to help you get started: https://boxfuse.com/getstarted/springboot
Disclaimer: I am the founder and CEO of Boxfuse
I tried the first solution and it works but the end user can easily identify that the div's are refreshing as it is fadeIn(), without fade in i tried .toggle().toggle() and it works perfect. you can try like this
$("#panel").toggle().toggle();
_x000D_
it works perfectly for me as i'm developing a messenger and need to minimize and maximize the chat box's and this does it best rather than the above code.
Really cheap solution:
urllib.urlopen('http://user:[email protected]/api')
(which you may decide is not suitable for a number of reasons, like security of the url)
>>> import urllib, json
>>> result = urllib.urlopen('https://personal-access-token:[email protected]/repos/:owner/:repo')
>>> r = json.load(result.fp)
>>> result.close()
Try this:
var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));
This should return true
.
UPDATED: Added isNaN
check to handle the case commented by Julian H. Lam
I think that they should perform generally the same, but there are some differences.
START
is generally used to start applications or to start the default application for a given file type. That way if you START http://mywebsite.com
it doesn't do START iexplore.exe http://mywebsite.com
.
START myworddoc.docx
would start Microsoft Word and open myworddoc.docx.CALL myworddoc.docx
does the same thing... however START
provides more options for the window state and things of that nature. It also allows process priority and affinity to be set.
In short, given the additional options provided by start, it should be your tool of choice.
START ["title"] [/D path] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED]
[/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL]
[/NODE <NUMA node>] [/AFFINITY <hex affinity mask>] [/WAIT] [/B]
[command/program] [parameters]
"title" Title to display in window title bar.
path Starting directory.
B Start application without creating a new window. The
application has ^C handling ignored. Unless the application
enables ^C processing, ^Break is the only way to interrupt
the application.
I The new environment will be the original environment passed
to the cmd.exe and not the current environment.
MIN Start window minimized.
MAX Start window maximized.
SEPARATE Start 16-bit Windows program in separate memory space.
SHARED Start 16-bit Windows program in shared memory space.
LOW Start application in the IDLE priority class.
NORMAL Start application in the NORMAL priority class.
HIGH Start application in the HIGH priority class.
REALTIME Start application in the REALTIME priority class.
ABOVENORMAL Start application in the ABOVENORMAL priority class.
BELOWNORMAL Start application in the BELOWNORMAL priority class.
NODE Specifies the preferred Non-Uniform Memory Architecture (NUMA)
node as a decimal integer.
AFFINITY Specifies the processor affinity mask as a hexadecimal number.
The process is restricted to running on these processors.
The affinity mask is interpreted differently when /AFFINITY and
/NODE are combined. Specify the affinity mask as if the NUMA
node's processor mask is right shifted to begin at bit zero.
The process is restricted to running on those processors in
common between the specified affinity mask and the NUMA node.
If no processors are in common, the process is restricted to
running on the specified NUMA node.
WAIT Start application and wait for it to terminate.
Use COALESCE()
instead:
SELECT COALESCE(Field,'Empty') from Table;
It functions much like ISNULL
, although provides more functionality. Coalesce will return the first non null value in the list. Thus:
SELECT COALESCE(null, null, 5);
returns 5, while
SELECT COALESCE(null, 2, 5);
returns 2
Coalesce will take a large number of arguments. There is no documented maximum. I tested it will 100 arguments and it succeeded. This should be plenty for the vast majority of situations.
In case we want to list all documents in Mongoose collection
after update
or delete
We can edit the function to some thing like this:
exports.product_update = function (req, res, next) {
Product.findByIdAndUpdate(req.params.id, {$set: req.body}, function (err, product) {
if (err) return next(err);
Product.find({}).then(function (products) {
res.send(products);
});
//res.send('Product udpated.');
});
};
This will list all documents
on success instead of just showing success message
Before and BeforeClass in JUnit
The function @Before
annotation will be executed before each of test function in the class having @Test
annotation but the function with @BeforeClass
will be execute only one time before all the test functions in the class.
Similarly function with @After
annotation will be executed after each of test function in the class having @Test
annotation but the function with @AfterClass
will be execute only one time after all the test functions in the class.
SampleClass
public class SampleClass {
public String initializeData(){
return "Initialize";
}
public String processDate(){
return "Process";
}
}
SampleTest
public class SampleTest {
private SampleClass sampleClass;
@BeforeClass
public static void beforeClassFunction(){
System.out.println("Before Class");
}
@Before
public void beforeFunction(){
sampleClass=new SampleClass();
System.out.println("Before Function");
}
@After
public void afterFunction(){
System.out.println("After Function");
}
@AfterClass
public static void afterClassFunction(){
System.out.println("After Class");
}
@Test
public void initializeTest(){
Assert.assertEquals("Initailization check", "Initialize", sampleClass.initializeData() );
}
@Test
public void processTest(){
Assert.assertEquals("Process check", "Process", sampleClass.processDate() );
}
}
Output
Before Class
Before Function
After Function
Before Function
After Function
After Class
In Junit 5
@Before = @BeforeEach
@BeforeClass = @BeforeAll
@After = @AfterEach
@AfterClass = @AfterAll
I'd do it like this:
colnames=['TIME', 'X', 'Y', 'Z']
user1 = pd.read_csv('dataset/1.csv', names=colnames, header=None)
A string in C# is always UTF-16, there is no way to "convert" it. The encoding is irrelevant as long as you manipulate the string in memory, it only matters if you write the string to a stream (file, memory stream, network stream...).
If you want to write the string to a XML file, just specify the encoding when you create the XmlWriter
It depends on the semantic of the primary key. If it's just autoincrement, then use something like:
insert into table1 (all columns except pk)
select all_columns_except_pk
from table2;
If PK means something, you need to find a way to determine which record should have priority. You could create a select query to find duplicates first (see answer by cpitis). Then eliminate the ones you don't want to keep and use the above insert to add records that remain.
01. Open the page for which you want to get the information.
02. Clear the address bar [where you type the address of the sites]:
and type or copy/paste from below:
javascript:alert(document.lastModified)
03. Press Enter or Go button.
I was able to fully export my project along with all commits, branches and tags to gitlab via following commands run locally on my computer:
To illustrate my example, I will be using https://github.com/raveren/kint as the source repository that I want to import into gitlab. I created an empty project named
Kint
(under namespaceraveren
) in gitlab beforehand and it told me the http git url of the newly created project there is http://gitlab.example.com/raveren/kint.gitThe commands are OS agnostic.
In a new directory:
git clone --mirror https://github.com/raveren/kint
cd kint.git
git remote add gitlab http://gitlab.example.com/raveren/kint.git
git push gitlab --mirror
Now if you have a locally cloned repository that you want to keep using with the new remote, just run the following commands* there:
git remote remove origin
git remote add origin http://gitlab.example.com/raveren/kint.git
git fetch --all
*This assumes that you did not rename your remote master from origin
, otherwise, change the first two lines to reflect it.
a = "cool"
type(a)
//result 'str'
<class 'str'>
or
do
`dir(a)`
to see the list of inbuilt methods you can have on the variable.
Note that if you still want to exclude a set, including things like slashes and special characters you can do the following:
var outString = sourceString.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');
take special note that in order to also include the "minus" character, you need to escape it with a backslash like the latter group. if you don't it will also select 0-9 which is probably undesired.
You can use PixelRatio
for example:
var React = require('react-native');
var {StyleSheet, PixelRatio} = React;
var FONT_BACK_LABEL = 18;
if (PixelRatio.get() <= 2) {
FONT_BACK_LABEL = 14;
}
var styles = StyleSheet.create({
label: {
fontSize: FONT_BACK_LABEL
}
});
Edit:
Another example:
import { Dimensions, Platform, PixelRatio } from 'react-native';
const {
width: SCREEN_WIDTH,
height: SCREEN_HEIGHT,
} = Dimensions.get('window');
// based on iphone 5s's scale
const scale = SCREEN_WIDTH / 320;
export function normalize(size) {
const newSize = size * scale
if (Platform.OS === 'ios') {
return Math.round(PixelRatio.roundToNearestPixel(newSize))
} else {
return Math.round(PixelRatio.roundToNearestPixel(newSize)) - 2
}
}
Usage:
fontSize: normalize(24)
you can go one step further by allowing sizes to be used on every <Text />
components by pre-defined sized.
Example:
const styles = {
mini: {
fontSize: normalize(12),
},
small: {
fontSize: normalize(15),
},
medium: {
fontSize: normalize(17),
},
large: {
fontSize: normalize(20),
},
xlarge: {
fontSize: normalize(24),
},
};
$(document).ready(function() {
scope.$apply(function() {
applyHeight();
});
});
This also ensures that all the scripts have been loaded before the execution of the statements. If you dont need that you can use
$(window).load(function() {
scope.$apply(function() {
applyHeight();
});
});
find supports wildcard matches, just add a *
:
find / -type d -name "ora10*"
It can also be done using backtracking by maintaining a visited array.
void foo(vector<vector<int> > &s,vector<int> &data,int go,int k,vector<int> &vis,int tot)
{
vis[go]=1;
data.push_back(go);
if(data.size()==k)
{
s.push_back(data);
vis[go]=0;
data.pop_back();
return;
}
for(int i=go+1;i<=tot;++i)
{
if(!vis[i])
{
foo(s,data,i,k,vis,tot);
}
}
vis[go]=0;
data.pop_back();
}
vector<vector<int> > Solution::combine(int n, int k) {
vector<int> data;
vector<int> vis(n+1,0);
vector<vector<int> > sol;
for(int i=1;i<=n;++i)
{
for(int i=1;i<=n;++i) vis[i]=0;
foo(sol,data,i,k,vis,n);
}
return sol;
}
This worked for me:
DELETE from m_productprice
WHERE m_pricelist_version_id='1000020'
AND m_product_id IN (SELECT m_product_id
FROM m_product
WHERE upc = '7094');
I provide this answer here to the old question since no answers tell the fact that the overriding method can throw nothing here's again what the overriding method can throw:
1) throw the same exception
public static class A
{
public void m1()
throws IOException
{
System.out.println("A m1");
}
}
public static class B
extends A
{
@Override
public void m1()
throws IOException
{
System.out.println("B m1");
}
}
2) throw subclass of the overriden method's thrown exception
public static class A
{
public void m2()
throws Exception
{
System.out.println("A m2");
}
}
public static class B
extends A
{
@Override
public void m2()
throws IOException
{
System.out.println("B m2");
}
}
3) throw nothing.
public static class A
{
public void m3()
throws IOException
{
System.out.println("A m3");
}
}
public static class B
extends A
{
@Override
public void m3()
//throws NOTHING
{
System.out.println("B m3");
}
}
4) Having RuntimeExceptions in throws is not required.
There can be RuntimeExceptions in throws or not, compiler won't complain about it. RuntimeExceptions are not checked exceptions. Only checked exceptions are required to appear in throws if not catched.
Single dimensional array decays to a pointer pointer pointing to the first element in the array. While a 2D array decays to a pointer pointing to first row. So, the function prototype should be -
void myFunction(double (*myArray) [10]);
I would prefer std::vector
over raw arrays.
Just give full path to exclusion file: eg..
-- no - - - - -xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt
correct - - - xcopy c:\t1 c:\t2 /EXCLUDE:C:\list-of-excluded-files.txt
In this example the file would be located " C:\list-of-excluded-files.txt "
or...
correct - - - xcopy c:\t1 c:\t2 /EXCLUDE:C:\mybatch\list-of-excluded-files.txt
In this example the file would be located " C:\mybatch\list-of-excluded-files.txt "
Full path fixes syntax error.
It's perfectly possible to update multiple columns in the same statement, and in fact your code is doing it. So why does it seem that "INV_TOTAL is not updating, only the inv_discount"?
Because you're updating INV_TOTAL with INV_DISCOUNT, and the database is going to use the existing value of INV_DISCOUNT and not the one you change it to. So I'm afraid what you need to do is this:
UPDATE INVOICE
SET INV_DISCOUNT = DISC1 * INV_SUBTOTAL
, INV_TOTAL = INV_SUBTOTAL - (DISC1 * INV_SUBTOTAL)
WHERE INV_ID = I_INV_ID;
Perhaps that seems a bit clunky to you. It is, but the problem lies in your data model. Storing derivable values in the table, rather than deriving when needed, rarely leads to elegant SQL.
The following works for me when disabling Findbugs in a child POM:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<executions>
<execution>
<id>ID_AS_IN_PARENT</id> <!-- id is necessary sometimes -->
<phase>none</phase>
</execution>
</executions>
</plugin>
Note: the full definition of the Findbugs plugin is in our parent/super POM, so it'll inherit the version and so-on.
In Maven 3, you'll need to use:
<configuration>
<skip>true</skip>
</configuration>
for the plugin.
type log.txt
But that will give you the whole file. You could change it to:
echo %date%, %time% >> log.txt
echo %date%, %time% > log_last.txt
...
type log_last.txt
to get only the last one.
Based in @Daniel answer I did:
for remote in \`git branch | grep -v master\`
do
git push -u origin $remote
done
Dirty trick: You could as well use lambda expression to pass any code you want including the call with parameters.
this.Include(includes, () =>
{
_context.Cars.Include(<parameters>);
});
The value of a sticky broadcast is the value that was last broadcast and is currently held in the sticky cache. This is not the value of a broadcast that was received right now. I suppose you can say it is like a browser cookie that you can access at any time. The sticky broadcast is now deprecated, per the docs for sticky broadcast methods (e.g.):
This method was deprecated in API level 21. Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.
Try this
'''
This is a multiline
comment. I can type here whatever I want.
'''
Python does have a multiline string/comment syntax in the sense that unless used as docstrings, multiline strings generate no bytecode -- just like #-prepended comments. In effect, it acts exactly like a comment.
On the other hand, if you say this behavior must be documented in the official docs to be a true comment syntax, then yes, you would be right to say it is not guaranteed as part of the language specification.
In any case your editor should also be able to easily comment-out a selected region (by placing a # in front of each line individually). If not, switch to an editor that does.
Programming in Python without certain text editing features can be a painful experience. Finding the right editor (and knowing how to use it) can make a big difference in how the Python programming experience is perceived.
Not only should the editor be able to comment-out selected regions, it should also be able to shift blocks of code to the left and right easily, and should automatically place the cursor at the current indentation level when you press Enter. Code folding can also be useful.
toBe()
versus toEqual()
: toEqual()
checks equivalence. toBe()
, on the other hand, makes sure that they're the exact same object.
I would say use toBe()
when comparing values, and toEqual()
when comparing objects.
When comparing primitive types, toEqual()
and toBe()
will yield the same result. When comparing objects, toBe()
is a stricter comparison, and if it is not the exact same object in memory this will return false. So unless you want to make sure it's the exact same object in memory, use toEqual()
for comparing objects.
Check this link out for more info : http://evanhahn.com/how-do-i-jasmine/
Now when looking at the difference between toBe()
and toEqual()
when it comes to numbers, there shouldn't be any difference so long as your comparison is correct. 5
will always be equivalent to 5
.
A nice place to play around with this to see different outcomes is here
An easy way to look at toBe()
and toEqual()
is to understand what exactly they do in JavaScript. According to Jasmine API, found here:
toEqual() works for simple literals and variables, and should work for objects
toBe() compares with
===
Essentially what that is saying is toEqual()
and toBe()
are similar Javascripts ===
operator except toBe()
is also checking to make sure it is the exact same object, in that for the example below objectOne === objectTwo //returns false
as well. However, toEqual()
will return true in that situation.
Now, you can at least understand why when given:
var objectOne = {
propertyOne: str,
propertyTwo: num
}
var objectTwo = {
propertyOne: str,
propertyTwo: num
}
expect(objectOne).toBe(objectTwo); //returns false
That is because, as stated in this answer to a different, but similar question, the ===
operator actually means that both operands reference the same object, or in case of value types, have the same value.
I struggled with this as well and found a simple pattern to isolate the test context after a cursory read of the @ComponentScan docs.
/**
* Type-safe alternative to {@link #basePackages} for specifying the packages
* to scan for annotated components. The package of each class specified will be scanned.
* Consider creating a special no-op marker class or interface in each package
* that serves no purpose other than being referenced by this attribute.
*/
Class<?>[] basePackageClasses() default {};
("com.example.test")
.Example
IsolatedTest.java
package com.example.test;
@RunWith(SpringJUnit4ClassRunner.class)
@ComponentScan(basePackageClasses = {TestDomain.class})
@SpringApplicationConfiguration(classes = IsolatedTest.Config.class)
public class IsolatedTest {
String expected = "Read the documentation on @ComponentScan";
String actual = "Too lazy when I can just search on Stack Overflow.";
@Test
public void testSomething() throws Exception {
assertEquals(expected, actual);
}
@ComponentScan(basePackageClasses = {TestDomain.class})
public static class Config {
public static void main(String[] args) {
SpringApplication.run(Config.class, args);
}
}
}
...
TestDomain.java
package com.example.test;
public interface TestDomain {
//noop marker
}
Make sure your AUTO_INCREMENT
is not out of range. In that case, set a new value for it with:
ALTER TABLE table_name AUTO_INCREMENT=100 -- Change 100 to the desired number
AUTO_INCREMENT
can contain a number that is bigger than the maximum value allowed by the datatype. This can happen if you filled up a table that you emptied afterward but the AUTO_INCREMENT
stayed the same, but there might be different reasons as well. In this case a new entry's id would be out of range.
If this is the cause of your problem, you can fix it by setting AUTO_INCREMENT
to one bigger than the latest row's id. So if your latest row's id is 100 then:
ALTER TABLE table_name AUTO_INCREMENT=101
If you would like to check AUTO_INCREMENT
's current value, use this command:
SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName'
AND TABLE_NAME = 'TableName';
As explained in Python's super() considered super, one way is to have class eat the arguments it requires, and pass the rest on. Thus, when the call-chain reaches object
, all arguments have been eaten, and object.__init__
will be called without arguments (as it expects). So your code should look like this:
class A(object):
def __init__(self, *args, **kwargs):
print "A"
super(A, self).__init__(*args, **kwargs)
class B(object):
def __init__(self, *args, **kwargs):
print "B"
super(B, self).__init__(*args, **kwargs)
class C(A):
def __init__(self, arg, *args, **kwargs):
print "C","arg=",arg
super(C, self).__init__(*args, **kwargs)
class D(B):
def __init__(self, arg, *args, **kwargs):
print "D", "arg=",arg
super(D, self).__init__(*args, **kwargs)
class E(C,D):
def __init__(self, arg, *args, **kwargs):
print "E", "arg=",arg
super(E, self).__init__(*args, **kwargs)
print "MRO:", [x.__name__ for x in E.__mro__]
E(10, 20, 30)
system_profiler SPHardwareDataType
shows I have 1 processor and 4 cores.
[~] system_profiler SPHardwareDataType
Hardware:
Hardware Overview:
Model Name: MacBook Pro
Model Identifier: MacBookPro9,1
Processor Name: Intel Core i7
Processor Speed: 2.6 GHz
Number of Processors: 1
Total Number of Cores: 4
<snip>
[~]
However, sysctl disagrees:
[~] sysctl -n hw.logicalcpu
8
[~] sysctl -n hw.physicalcpu
4
[~]
But sysctl appears correct, as when I run a program that should take up all CPU slots, I see this program taking close to 800% of CPU time (in top
):
PID COMMAND %CPU
4306 top 5.6
4304 java 745.7
4296 locationd 0.0
You can use Array.Resize()
in .net 3.5 and higher. This method allocates a new array with the specified size, copies elements from the old array to the new one, and then replaces the old array with the new one.
(So you will need the memory available for both arrays as this probably uses Array.Copy
under the covers)
SELECT column FROM
( SELECT column, dbms_random.value FROM table ORDER BY 2 )
where rownum <= 20;
There are different exceptions such as runtime_error
, range_error
, overflow_error
, logic_error
, etc.. You need to pass the string into its constructor, and you can concatenate whatever you want to your message. That's just a string operation.
std::string errorMessage = std::string("Error: on file ")+fileName;
throw std::runtime_error(errorMessage);
You can also use boost::format
like this:
throw std::runtime_error(boost::format("Error processing file %1") % fileName);
This was so much easier importing the registry export than what is stated above. + Simply:
Worked like a champ on Win 7 Pro.
You can use the -quit
option of find
:
find <dir> -maxdepth 1 -type d -name '*foo*' -print -quit
dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))
na.omit(dat)
x1 x2
1 1 100
3 3 300
5 5 500
Use the following code to insert the date into MySQL. Instead of changing our date's format to meet MySql's requirement, we can help data base to recognize our date by setting the STR_TO_DATE(?, '%l:%i %p')
parameters.
For example, 2014-03-12 can be represented as STR_TO_DATE('2014-03-12', '%Y-%m-%d')
preparedStatement = connect.prepareStatement("INSERT INTO test.msft VALUES (default, STR_TO_DATE( ?, '%m/%d/%Y'), STR_TO_DATE(?, '%l:%i %p'),?,?,?,?,?)");
forEach()
can be implemented to be faster than for-each loop, because the iterable knows the best way to iterate its elements, as opposed to the standard iterator way. So the difference is loop internally or loop externally.
For example ArrayList.forEach(action)
may be simply implemented as
for(int i=0; i<size; i++)
action.accept(elements[i])
as opposed to the for-each loop which requires a lot of scaffolding
Iterator iter = list.iterator();
while(iter.hasNext())
Object next = iter.next();
do something with `next`
However, we also need to account for two overhead costs by using forEach()
, one is making the lambda object, the other is invoking the lambda method. They are probably not significant.
see also http://journal.stuffwithstuff.com/2013/01/13/iteration-inside-and-out/ for comparing internal/external iterations for different use cases.
I think the Class on img tag is better when You use the same style in different structure on Your site. You have to decide when you write less line of CSS code and HTML is more readable.
Postgres hasn't implemented an equivalent to INSERT OR REPLACE
. From the ON CONFLICT
docs (emphasis mine):
It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.
Though it doesn't give you shorthand for replacement, ON CONFLICT DO UPDATE
applies more generally, since it lets you set new values based on preexisting data. For example:
INSERT INTO users (id, level)
VALUES (1, 0)
ON CONFLICT (id) DO UPDATE
SET level = users.level + 1;
All the gory details can be found in the current RFC on the topic: RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)
Based on this related answer, you are looking at a list that looks like: A-Z
, a-z
, 0-9
, -
, .
, _
, ~
, :
, /
, ?
, #
, [
, ]
, @
, !
, $
, &
, '
, (
, )
, *
, +
, ,
, ;
, %
, and =
. Everything else must be url-encoded. Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. %
can only be used in conjunction with url encoding as in %20
), the RFC has all of these specifics.
Just write
System.Diagnostics.Process.Start(@"file path");
example
System.Diagnostics.Process.Start(@"C:\foo.jpg");
System.Diagnostics.Process.Start(@"C:\foo.doc");
System.Diagnostics.Process.Start(@"C:\foo.dxf");
...
And shell will run associated program reading it from the registry, like usual double click does.
The RequestContext
is deprecated from Primefaces 6.2. From this version use the following:
if (componentID != null && PrimeFaces.current().isAjaxRequest()) {
PrimeFaces.current().ajax().update(componentID);
}
And to execute javascript from the backbean use this way:
PrimeFaces.current().executeScript(jsCommand);
Usually sqlcmd
comes with bcp
utility (as part of mssql-tools
) which exports into CSV by default.
Usage:
bcp {dbtable | query} {in | out | queryout | format} datafile
For example:
bcp.exe MyTable out data.csv
To dump all tables into corresponding CSV files, here is the Bash script:
#!/usr/bin/env bash
# Script to dump all tables from SQL Server into CSV files via bcp.
# @file: bcp-dump.sh
server="sql.example.com" # Change this.
user="USER" # Change this.
pass="PASS" # Change this.
dbname="DBNAME" # Change this.
creds="-S '$server' -U '$user' -P '$pass' -d '$dbname'"
sqlcmd $creds -Q 'SELECT * FROM sysobjects sobjects' > objects.lst
sqlcmd $creds -Q 'SELECT * FROM information_schema.routines' > routines.lst
sqlcmd $creds -Q 'sp_tables' | tail -n +3 | head -n -2 > sp_tables.lst
sqlcmd $creds -Q 'SELECT name FROM sysobjects sobjects WHERE xtype = "U"' | tail -n +3 | head -n -2 > tables.lst
for table in $(<tables.lst); do
sqlcmd $creds -Q "exec sp_columns $table" > $table.desc && \
bcp $table out $table.csv -S $server -U $user -P $pass -d $dbname -c
done
This can be achieved through LINQ with grouping, here a list of items pointed as a data source to the actual grid view. Sample pseudo code which could help coding the actual.
var tabelDetails =(from li in dc.My_table
join m in dc.Table_One on li.ID equals m.ID
join c in dc.Table_two on li.OtherID equals c.ID
where //Condition
group new { m, li, c } by new
{
m.ID,
m.Name
} into g
select new
{
g.Key.ID,
Name = g.Key.FullName,
sponsorBonus= g.Where(s => s.c.Name == "sponsorBonus").Count(),
pairingBonus = g.Where(s => s.c.Name == "pairingBonus").Count(),
staticBonus = g.Where(s => s.c.Name == "staticBonus").Count(),
leftBonus = g.Where(s => s.c.Name == "leftBonus").Count(),
rightBonus = g.Where(s => s.c.Name == "rightBonus").Count(),
Total = g.Count() //Row wise Total
}).OrderBy(t => t.Name).ToList();
tabelDetails.Insert(tabelDetails.Count(), new //This data will be the last row of the grid
{
Name = "Total", //Column wise total
sponsorBonus = tabelDetails.Sum(s => s.sponsorBonus),
pairingBonus = tabelDetails.Sum(s => s.pairingBonus),
staticBonus = tabelDetails.Sum(s => s.staticBonus),
leftBonus = tabelDetails.Sum(s => s.leftBonus),
rightBonus = tabelDetails.Sum(s => s.rightBonus ),
Total = tabelDetails.Sum(s => s.Total)
});
The System.Windows.Media.Imaging
namespace is part of PresentationCore.dll (if you are using Visual Studio 2008 then the WPF application template will automatically add this reference). Note that this namespace is not a direct wrapping of the WIC library, although a large proportion of the more common uses are still available and it is relatively obvious how these map to the WIC versions. For more information on the classes in this namespace check out
http://msdn2.microsoft.com/en-us/library/system.windows.media.imaging.aspx
This is based on CMS's answer. The question asked for the timer to be restarted on the blur and stopped on the focus, so I moved it around a little:
$(function () {
var timerId = 0;
$('textarea').focus(function () {
clearInterval(timerId);
});
$('textarea').blur(function () {
timerId = setInterval(function () {
//some code here
}, 1000);
});
});
In Java:
String str = " hello world ";
// prints "hello world"
System.out.println(str.replaceAll("^(\\s+)|(\\s+)$", ""));
Here is my function
char *fileName = "input-1.txt";
countOfLinesFromFile(fileName);
void countOfLinesFromFile(char *filename){
FILE* myfile = fopen(filename, "r");
int ch, number_of_lines = 0;
do
{
ch = fgetc(myfile);
if(ch == '\n')
number_of_lines++;
}
while (ch != EOF);
if(ch != '\n' && number_of_lines != 0)
number_of_lines++;
fclose(myfile);
printf("number of lines in %s = %d",filename, number_of_lines);
}
In your planner component, you must be missing import HeaderAreaComponent like this-
import { HeaderAreaComponent } from '../header-area.component';
//change path according your project
Also, make sure - All the components and pipes must be declared via an NgModule.
See if this helps.
You likely want to use gpg
instead of openssl
so see "Additional Notes" at the end of this answer. But to answer the question using openssl
:
To Encrypt:
openssl enc -aes-256-cbc -in un_encrypted.data -out encrypted.data
To Decrypt:
openssl enc -d -aes-256-cbc -in encrypted.data -out un_encrypted.data
Note: You will be prompted for a password when encrypting or decrypt.
Your best source of information for openssl enc
would probably be: https://www.openssl.org/docs/man1.1.1/man1/enc.html
Command line:
openssl enc
takes the following form:
openssl enc -ciphername [-in filename] [-out filename] [-pass arg]
[-e] [-d] [-a/-base64] [-A] [-k password] [-kfile filename]
[-K key] [-iv IV] [-S salt] [-salt] [-nosalt] [-z] [-md] [-p] [-P]
[-bufsize number] [-nopad] [-debug] [-none] [-engine id]
Explanation of most useful parameters with regards to your question:
-e
Encrypt the input data: this is the default.
-d
Decrypt the input data.
-k <password>
Only use this if you want to pass the password as an argument.
Usually you can leave this out and you will be prompted for a
password. The password is used to derive the actual key which
is used to encrypt your data. Using this parameter is typically
not considered secure because your password appears in
plain-text on the command line and will likely be recorded in
bash history.
-kfile <filename>
Read the password from the first line of <filename> instead of
from the command line as above.
-a
base64 process the data. This means that if encryption is taking
place the data is base64 encoded after encryption. If decryption
is set then the input data is base64 decoded before being
decrypted.
You likely DON'T need to use this. This will likely increase the
file size for non-text data. Only use this if you need to send
data in the form of text format via email etc.
-salt
To use a salt (randomly generated) when encrypting. You always
want to use a salt while encrypting. This parameter is actually
redundant because a salt is used whether you use this or not
which is why it was not used in the "Short Answer" above!
-K key
The actual key to use: this must be represented as a string
comprised only of hex digits. If only the key is specified, the
IV must additionally be specified using the -iv option. When
both a key and a password are specified, the key given with the
-K option will be used and the IV generated from the password
will be taken. It probably does not make much sense to specify
both key and password.
-iv IV
The actual IV to use: this must be represented as a string
comprised only of hex digits. When only the key is specified
using the -K option, the IV must explicitly be defined. When a
password is being specified using one of the other options, the
IV is generated from this password.
-md digest
Use the specified digest to create the key from the passphrase.
The default algorithm as of this writing is sha-256. But this
has changed over time. It was md5 in the past. So you might want
to specify this parameter every time to alleviate problems when
moving your encrypted data from one system to another or when
updating openssl to a newer version.
Though you have specifically asked about OpenSSL you might want to consider using GPG instead for the purpose of encryption based on this article OpenSSL vs GPG for encrypting off-site backups?
To use GPG to do the same you would use the following commands:
To Encrypt:
gpg --output encrypted.data --symmetric --cipher-algo AES256 un_encrypted.data
To Decrypt:
gpg --output un_encrypted.data --decrypt encrypted.data
Note: You will be prompted for a password when encrypting or decrypt.
See Is there a clean wikipedia API just for retrieve content summary? for other proposed solutions. Here is one that I suggested:
There is actually a very nice prop called extracts that can be used with queries designed specifically for this purpose. Extracts allow you to get article extracts (truncated article text). There is a parameter called exintro that can be used to retrieve the text in the zeroth section (no additional assets like images or infoboxes). You can also retrieve extracts with finer granularity such as by a certain number of characters (exchars) or by a certain number of sentences(exsentences)
Here is a sample query http://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&titles=Stack%20Overflow and the API sandbox http://en.wikipedia.org/wiki/Special:ApiSandbox#action=query&prop=extracts&format=json&exintro=&titles=Stack%20Overflow to experiment more with this query.
Please note that if you want the first paragraph specifically you still need to get the first tag. However in this API call there are no additional assets like images to parse. If you are satisfied with this intro summary you can retrieve the text by running a function like php's strip_tag that remove the html tags.
DataRow rw = table.AsEnumerable().FirstOrDefault(tt => tt.Field<string>("Author") == "Name");
if (rw != null)
{
// row exists
}
add to your using clause :
using System.Linq;
and add :
System.Data.DataSetExtensions
to references.
If you are invoking foobarfunc
with resolution scope operator (::
), then you are calling it statically, e.g. on the class level instead of the instance level, thus you are using $this
when not in object context. $this
does not exist in class context.
If you enable E_STRICT
, PHP will raise a Notice about this:
Strict Standards:
Non-static method foobar::foobarfunc() should not be called statically
Do this instead
$fb = new foobar;
echo $fb->foobarfunc();
On a sidenote, I suggest not to use global
inside your classes. If you need something from outside inside your class, pass it through the constructor. This is called Dependency Injection and it will make your code much more maintainable and less dependant on outside things.
The '-Wait' option seemed to block for me even though my process had finished.
I tried Adrian's solution and it works. But I used Wait-Process instead of relying on a side effect of retrieving the process handle.
So:
$proc = Start-Process $msbuild -PassThru
Wait-Process -InputObject $proc
if ($proc.ExitCode -ne 0) {
Write-Warning "$_ exited with status code $($proc.ExitCode)"
}
Since Java 8, it seems like the java.time
standard library is the way to go. From Joda time web page:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Back to your question. Were you to use Java 8, I think you want LocalDateTime
. Because it contains the date and time-of-the-day, but is unaware of time zone or any reference point in time such as the unix epoch.
Open $CATALINA_BASE/conf/web.xml
and find this
<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly -->
<!-- created sessions by modifying the value below. -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.
This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different
string WordInBetween(string sentence, string wordOne, string wordTwo)
{
int start = sentence.IndexOf(wordOne) + wordOne.Length + 1;
int end = sentence.IndexOf(wordTwo) - start - 1;
return sentence.Substring(start, end);
}
Try
npm config set strict-ssl false
This is a alternative shared in this url https://github.com/nodejs/node/issues/3742
From the documentation:
Returns the phone number string for line 1, for example, the MSISDN for a GSM phone. Return null if it is unavailable.
So you have done everything right, but there is no phone number stored.
If you get null
, you could display something to get the user to input the phone number on his/her own.
This will work in Chrome
// get your input
var input = document.getElementById('txt206451');
// get it's (first) label
var label = input.labels[0];
// change it's content
label.textContent = 'thanks'
But after looking, labels doesn't seem to be widely supported..
You can use querySelector
// get txt206451's (first) label
var label = document.querySelector('label[for="txt206451"]');
// change it's content
label.textContent = 'thanks'
You can use this constructor
moment({h:0, m:0, s:0, ms:0})
http://momentjs.com/docs/#/parsing/object/
console.log( moment().format('YYYY-MM-DD HH:mm:ss') )_x000D_
_x000D_
console.log( moment({h:0, m:0, s:0, ms:0}).format('YYYY-MM-DD HH:mm:ss') )
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
_x000D_
I had this problem when I try to write a very long url, the following works.
image_url = %w(
http://minio.127.0.0.1.xip.io:9000/
bucket29/docs/b7cfab0e-0119-452c-b262-1b78e3fccf38/
28ed3774-b234-4de2-9a11-7d657707f79c?
X-Amz-Algorithm=AWS4-HMAC-SHA256&
X-Amz-Credential=ABABABABABABABABA
%2Fus-east-1%2Fs3%2Faws4_request&
X-Amz-Date=20170702T000940Z&
X-Amz-Expires=3600&X-Amz-SignedHeaders=host&
X-Amz-Signature=ABABABABABABABABABABAB
ABABABABABABABABABABABABABABABABABABA
).join
Note, there must not be any newlines, white spaces when the url string is formed. If you want newlines, then use HEREDOC.
Here you have indentation for readability, ease of modification, without the fiddly quotes and backslashes on every line. The cost of joining the strings should be negligible.
You can used following code that can solve your problem.
Matrix matrix = new Matrix();
matrix.postScale(0.5f, 0.5f);
Bitmap croppedBitmap = Bitmap.createBitmap(bitmapOriginal, 100, 100,100, 100, matrix, true);
Above method do postScalling of image before cropping, so you can get best result with cropped image without getting OOM error.
For more detail you can refer this blog
I've tested this:
When I open an Excel document D:\db\tmp\test1.xlsm
:
CurDir()
returns C:\Users\[username]\Documents
ActiveWorkbook.Path
returns D:\db\tmp
So CurDir()
has a system default and can be changed.
ActiveWorkbook.Path
does not change for the same saved Workbook.
For example, CurDir()
changes when you do "File/Save As" command, and select a random directory in the File/Directory selection dialog. Then click on Cancel to skip saving. But CurDir()
has already changed to the last selected directory.
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
var locations = ["http://webPage1.com", "http://webPage2.com"];
var len = locations.length;
var iframe = $('#frame');
var i = 0;
setInterval(function () {
iframe.attr('src', locations[++i % len]);
}, 30000);
});
</script>
</head>
<body>
<iframe id="frame"></iframe>
</body>
</html>
2020 Simple way :
git reset <commit_hash>
(The commit hash of the last commit you want to keep).
If the commit was pushed, you can then do :
git push -f
You will keep the now uncommitted changes locally
Since the introduction of attributed strings in UIViews in iOS 6, it's possible to assign a color to the placeholder text like this:
if ([textField respondsToSelector:@selector(setAttributedPlaceholder:)]) {
UIColor *color = [UIColor blackColor];
textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholderText attributes:@{NSForegroundColorAttributeName: color}];
} else {
NSLog(@"Cannot set placeholder text's color, because deployment target is earlier than iOS 6.0");
// TODO: Add fall-back code to set placeholder color.
}
The advantage to this is that it is applied to every call.
Create a class that implements IClientMessageInspector. In the BeforeSendRequest method, add your custom header to the outgoing message. It might look something like this:
public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
{
HttpRequestMessageProperty httpRequestMessage;
object httpRequestMessageObject;
if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject))
{
httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;
if (string.IsNullOrEmpty(httpRequestMessage.Headers[USER_AGENT_HTTP_HEADER]))
{
httpRequestMessage.Headers[USER_AGENT_HTTP_HEADER] = this.m_userAgent;
}
}
else
{
httpRequestMessage = new HttpRequestMessageProperty();
httpRequestMessage.Headers.Add(USER_AGENT_HTTP_HEADER, this.m_userAgent);
request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
}
return null;
}
Then create an endpoint behavior that applies the message inspector to the client runtime. You can apply the behavior via an attribute or via configuration using a behavior extension element.
Here is a great example of how to add an HTTP user-agent header to all request messages. I am using this in a few of my clients. You can also do the same on the service side by implementing the IDispatchMessageInspector.
Is this what you had in mind?
Update: I found this list of WCF features that are supported by the compact framework. I believe message inspectors classified as 'Channel Extensibility' which, according to this post, are supported by the compact framework.
If you are using MySql Wamp. This code work.
string con="SERVER=localhost; user id=root; password=; database=dbname";
public void delete()
{
try
{
MySqlConnection connect = new MySqlConnection(con);
MySqlDataAdapter da = new MySqlDataAdapter();
connect.Open();
da.DeleteCommand = new MySqlCommand("DELETE FROM table WHERE ID='" + ID.Text + "'", connect);
da.DeleteCommand.ExecuteNonQuery();
MessageBox.Show("Successfully Deleted");
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
}
Try the DATENAME()
function:
select [date_created]
from table
where DATENAME(WEEKDAY, [date_created]) <> 'Saturday'
and DATENAME(WEEKDAY, [date_created]) <> 'Sunday'
UPDATE on the Android studio AVD:
No microwaves or elevators :)
Update your web.config
<system.webServer>
<modules>
<remove name="WebDAVModule"/>
</modules>
<handlers>
<remove name="WebDAV" />
<remove name="ExtensionlessUrl-Integrated-4.0" />
<add name="ExtensionlessUrl-Integrated-4.0"
path="*."
verb="GET,HEAD,POST,DEBUG,DELETE,PUT"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
Removes the need to modify your host configs.
Update: in Rails 3.0.9: env method defined in railties/lib/rails.rb
The best superuser role would be the root.The Syntax is:
use admin
db.createUser(
{
user: "root",
pwd: "password",
roles: [ "root" ]
})
For more details look at built-in roles.
Hope this helps !!!
I wanted something similar - a function that parses a string that can be passed as a parameter or piped.
I came up with a solution as below (works as #!/bin/sh
and as #!/bin/bash
)
#!/bin/sh
set -eu
my_func() {
local content=""
# if the first param is an empty string or is not set
if [ -z ${1+x} ]; then
# read content from a pipe if passed or from a user input if not passed
while read line; do content="${content}$line"; done < /dev/stdin
# first param was set (it may be an empty string)
else
content="$1"
fi
echo "Content: '$content'";
}
printf "0. $(my_func "")\n"
printf "1. $(my_func "one")\n"
printf "2. $(echo "two" | my_func)\n"
printf "3. $(my_func)\n"
printf "End\n"
Outputs:
0. Content: ''
1. Content: 'one'
2. Content: 'two'
typed text
3. Content: 'typed text'
End
For the last case (3.) you need to type, hit enter and CTRL+D to end the input.
This code helps:
data final; set final;
first_date = INPUT(compress(char_date),date9.); format first_date date9.;
run;
I personally have tried it on SAS
Share your folder for "everyone" or some specific group and try this:
<a href="file://YOURSERVERNAME/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf"> Download PDF </a>
_x000D_
I looked into the options pattern sample and saw this:
public class Startup
{
public Startup(IConfiguration config)
{
// Configuration from appsettings.json has already been loaded by
// CreateDefaultBuilder on WebHost in Program.cs. Use DI to load
// the configuration into the Configuration property.
Configuration = config;
}
...
}
When adding Iconfiguration in the constructor of my class, I could access the configuration options through DI.
Example:
public class MyClass{
private Iconfiguration _config;
public MyClass(Iconfiguration config){
_config = config;
}
... // access _config["myAppSetting"] anywhere in this class
}
May be use Filter.
const list = [{id:0}, {id:1}, {id:2}];
let listCopy = [...list];
let filteredDataSource = listCopy.filter((item) => {
if (item.id === 1) {
item.id = 12345;
}
return item;
});
console.log(filteredDataSource);
Array [Object { id: 0 }, Object { id: 12345 }, Object { id: 2 }]
Put the characters as the thisArg
in the map function will create a "one-liner":
Array.apply(null, Array(5))
.map(function(){
return this[Math.floor(Math.random()*this.length)];
}, "abcdefghijklmnopqrstuvwxyz")
.join('');
To bring more prominence to the useful comment by @johanvdw:
If you want to ensure your your javac file path is always know when cygwin starts, you may edit your .bash_profile
file. In this example you would add export PATH=$PATH:"/cygdrive/C/Program Files/Java/jdk1.6.0_23/bin/"
somewhere in the file.
When Cygwin starts, it'll search directories in PATH and this one for executable files to run.
Correct me if I'm wrong but I'm reading the question again and again and still think that Angus McCoteup was asking how to set an element to be position: fixed.
Angus McCoteup, check out http://www.cssplay.co.uk/layouts/fixed.html - if you want your DIV to behave like a menu there, have a look at a CSS there
This is a flicker-free version of the most accepted code that you can find as answers to this question. All credit to the posters of those fatastic answers. Thanks Dusty, Chris, Matt, and Josh!
Like "Fueled"'s request in one of the comments, I also needed a version that behaved a bit more... professionaly. This code maintains styles as in previous code, but adds an offscreen image render and graphics buffering (and disposes the graphics object properly).
Result: all the good, and no flicker. :)
public class NewProgressBar : ProgressBar
{
public NewProgressBar()
{
this.SetStyle(ControlStyles.UserPaint, true);
}
protected override void OnPaintBackground(PaintEventArgs pevent)
{
// None... Helps control the flicker.
}
protected override void OnPaint(PaintEventArgs e)
{
const int inset = 2; // A single inset value to control teh sizing of the inner rect.
using (Image offscreenImage = new Bitmap(this.Width, this.Height))
{
using (Graphics offscreen = Graphics.FromImage(offscreenImage))
{
Rectangle rect = new Rectangle(0, 0, this.Width, this.Height);
if (ProgressBarRenderer.IsSupported)
ProgressBarRenderer.DrawHorizontalBar(offscreen, rect);
rect.Inflate(new Size(-inset, -inset)); // Deflate inner rect.
rect.Width = (int)(rect.Width * ((double)this.Value / this.Maximum));
if (rect.Width == 0) rect.Width = 1; // Can't draw rec with width of 0.
LinearGradientBrush brush = new LinearGradientBrush(rect, this.BackColor, this.ForeColor, LinearGradientMode.Vertical);
offscreen.FillRectangle(brush, inset, inset, rect.Width, rect.Height);
e.Graphics.DrawImage(offscreenImage, 0, 0);
}
}
}
}
If we have a single server we can directly include it in the proxy_pass. But in case if we have many servers we use upstream to maintain the servers. Nginx will load-balance based on the incoming traffic.
I was having the same issue, particularly noticeable when my <h2>
element wrapped to a second line.
I applied a class to a <div>
in the infoWindow, and changed the fonts to a generic system font (in my case, Helvetica) versus an @font-face web font which it had been using. Issue solved.
public ActionResult Questionnaire()
{
return Redirect("~/MedicalHistory.html");
}
( tl;dr
: goto option 3: INSERT with RETURNING )
Recall that in postgresql there is no "id" concept for tables, just sequences (which are typically but not necessarily used as default values for surrogate primary keys, with the SERIAL pseudo-type).
If you are interested in getting the id of a newly inserted row, there are several ways:
Option 1: CURRVAL(<sequence name>);
.
For example:
INSERT INTO persons (lastname,firstname) VALUES ('Smith', 'John');
SELECT currval('persons_id_seq');
The name of the sequence must be known, it's really arbitrary; in this example we assume that the table persons
has an id
column created with the SERIAL
pseudo-type. To avoid relying on this and to feel more clean, you can use instead pg_get_serial_sequence
:
INSERT INTO persons (lastname,firstname) VALUES ('Smith', 'John');
SELECT currval(pg_get_serial_sequence('persons','id'));
Caveat: currval()
only works after an INSERT
(which has executed nextval()
), in the same session.
Option 2: LASTVAL();
This is similar to the previous, only that you don't need to specify the sequence name: it looks for the most recent modified sequence (always inside your session, same caveat as above).
Both CURRVAL
and LASTVAL
are totally concurrent safe. The behaviour of sequence in PG is designed so that different session will not interfere, so there is no risk of race conditions (if another session inserts another row between my INSERT and my SELECT, I still get my correct value).
However they do have a subtle potential problem. If the database has some TRIGGER (or RULE) that, on insertion into persons
table, makes some extra insertions in other tables... then LASTVAL
will probably give us the wrong value. The problem can even happen with CURRVAL
, if the extra insertions are done intto the same persons
table (this is much less usual, but the risk still exists).
Option 3: INSERT
with RETURNING
INSERT INTO persons (lastname,firstname) VALUES ('Smith', 'John') RETURNING id;
This is the most clean, efficient and safe way to get the id. It doesn't have any of the risks of the previous.
Drawbacks? Almost none: you might need to modify the way you call your INSERT statement (in the worst case, perhaps your API or DB layer does not expect an INSERT to return a value); it's not standard SQL (who cares); it's available since Postgresql 8.2 (Dec 2006...)
Conclusion: If you can, go for option 3. Elsewhere, prefer 1.
Note: all these methods are useless if you intend to get the last inserted id globally (not necessarily by your session). For this, you must resort to SELECT max(id) FROM table
(of course, this will not read uncommitted inserts from other transactions).
Conversely, you should never use SELECT max(id) FROM table
instead one of the 3 options above, to get the id just generated by your INSERT
statement, because (apart from performance) this is not concurrent safe: between your INSERT
and your SELECT
another session might have inserted another record.
No need too these. Just simply add div id to href of a < a > tag
<li><a id = "aboutlink" href="#about">auck</a></li>
Just like that.
Put --exec
arg in single quotation
.
e.g. I changed "nodemon --exec yarn build-langs"
to "nodemon --exec 'yarn build-langs'"
and worked.
You are calling GridView.RenderControl(htmlTextWriter)
, hence the page raises an exception that a Server-Control was rendered outside of a Form.
You could avoid this execption by overriding VerifyRenderingInServerForm
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
With Xcode 9 the interface has been updated and now the way I did to resolve the problem was this:
Had the same error while using SourceTree connected to BitBucket repository.
When navigating to repository url on bitbucket.org the warning message appeared:
This repository is in read-only mode. You caught us doing some quick maintenance.
After around 2 hours repository was accessible again.
You can check status and uptime of bitbucket here: http://status.bitbucket.org/
The transforms are SVG transforms (for details, have a look at the standard; here are some examples). Basically, scale and translate apply the respective transformations to the coordinate system, which should work as expected in most cases. You can apply more than one transform however (e.g. first scale and then translate) and then the result might not be what you expect.
When working with the transforms, keep in mind that they transform the coordinate system. In principle, what you say is true -- if you apply a scale > 1 to an object, it will look bigger and a translate will move it to a different position relative to the other objects.
Private Sub CommandButton1_Click()
Dim Z As Long
Dim Cellidx As Range
Dim NextRow As Long
Dim Rng As Range
Dim SrcWks As Worksheet
Dim DataWks As Worksheet
Z = 1
Set SrcWks = Worksheets("Sheet1")
Set DataWks = Worksheets("Sheet2")
Set Rng = EntryWks.Range("B6:ad6")
NextRow = DataWks.UsedRange.Rows.Count
NextRow = IIf(NextRow = 1, 1, NextRow + 1)
For Each RA In Rng.Areas
For Each Cellidx In RA
Z = Z + 1
DataWks.Cells(NextRow, Z) = Cellidx
Next Cellidx
Next RA
End Sub
Alternatively
Worksheets("Sheet2").Range("P2").Value = Worksheets("Sheet1").Range("L10")
This is a CopynPaste - Method
Sub CopyDataToPlan()
Dim LDate As String
Dim LColumn As Integer
Dim LFound As Boolean
On Error GoTo Err_Execute
'Retrieve date value to search for
LDate = Sheets("Rolling Plan").Range("B4").Value
Sheets("Plan").Select
'Start at column B
LColumn = 2
LFound = False
While LFound = False
'Encountered blank cell in row 2, terminate search
If Len(Cells(2, LColumn)) = 0 Then
MsgBox "No matching date was found."
Exit Sub
'Found match in row 2
ElseIf Cells(2, LColumn) = LDate Then
'Select values to copy from "Rolling Plan" sheet
Sheets("Rolling Plan").Select
Range("B5:H6").Select
Selection.Copy
'Paste onto "Plan" sheet
Sheets("Plan").Select
Cells(3, LColumn).Select
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
LFound = True
MsgBox "The data has been successfully copied."
'Continue searching
Else
LColumn = LColumn + 1
End If
Wend
Exit Sub
Err_Execute:
MsgBox "An error occurred."
End Sub
And there might be some methods doing that in Excel.
Each time you do e.nextElement()
you skip one. So you skip two elements in each iteration of your loop.
{{ HTML::style('yourcss.css') }}
{{ HTML::script('yourjs.js') }}
Try using 0xFFF000 instead and pass that into the Color.HSVToColor method.
none of answers helped me, in case when I had several levels of nested arrays. the solution is almost same as @AlienWebguy already did, but with tiny difference.
function nestedToSingle(array $array)
{
$singleDimArray = [];
foreach ($array as $item) {
if (is_array($item)) {
$singleDimArray = array_merge($singleDimArray, nestedToSingle($item));
} else {
$singleDimArray[] = $item;
}
}
return $singleDimArray;
}
test example
$array = [
'first',
'second',
[
'third',
'fourth',
],
'fifth',
[
'sixth',
[
'seventh',
'eighth',
[
'ninth',
[
[
'tenth'
]
]
],
'eleventh'
]
],
'twelfth'
];
$array = nestedToSingle($array);
print_r($array);
//output
array:12 [
0 => "first"
1 => "second"
2 => "third"
3 => "fourth"
4 => "fifth"
5 => "sixth"
6 => "seventh"
7 => "eighth"
8 => "ninth"
9 => "tenth"
10 => "eleventh"
11 => "twelfth"
]
There is also class UnicodeEncoding, quite simple in usage:
ByteConverter = new UnicodeEncoding();
string stringDataForEncoding = "My Secret Data!";
byte[] dataEncoded = ByteConverter.GetBytes(stringDataForEncoding);
Console.WriteLine("Data after decoding: {0}", ByteConverter.GetString(dataEncoded));
To convert UTC time to Local you have to use moment.local()
.
For more info see docs
var date = moment.utc().format('YYYY-MM-DD HH:mm:ss');
console.log(date); // 2015-09-13 03:39:27
var stillUtc = moment.utc(date).toDate();
var local = moment(stillUtc).local().format('YYYY-MM-DD HH:mm:ss');
console.log(local); // 2015-09-13 09:39:27
var date = moment.utc().format();_x000D_
console.log(date, "- now in UTC"); _x000D_
_x000D_
var local = moment.utc(date).local().format();_x000D_
console.log(local, "- UTC now to local");
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
_x000D_
Here is my sample how I use it. For the css/less task. Can be applied for all.
var cssTask = function (options) {
var minifyCSS = require('gulp-minify-css'),
less = require('gulp-less'),
src = cssDependencies;
src.push(codePath + '**/*.less');
var run = function () {
var start = Date.now();
console.log('Start building CSS/LESS bundle');
gulp.src(src)
.pipe(gulpif(options.devBuild, plumber({
errorHandler: onError
})))
.pipe(concat('main.css'))
.pipe(less())
.pipe(gulpif(options.minify, minifyCSS()))
.pipe(gulp.dest(buildPath + 'css'))
.pipe(gulpif(options.devBuild, browserSync.reload({stream:true})))
.pipe(notify(function () {
console.log('END CSS/LESS built in ' + (Date.now() - start) + 'ms');
}));
};
run();
if (options.watch) {
gulp.watch(src, run);
}
};
gulp.task('dev', function () {
var options = {
devBuild: true,
minify: false,
watch: false
};
cssTask (options);
});
My suggestion:
using System.Linq;
string myStringOutput = String.Join(",", myArray.Select(p => p.ToString()).ToArray());
reference: https://coderwall.com/p/oea7uq/convert-simple-int-array-to-string-c
If increasing the number of visible options is available, the following might work for you:
<html>
<head>
<title>Select Option Tooltip Test</title>
<script>
function showIETooltip(e){
if(!e){var e = window.event;}
var obj = e.srcElement;
var objHeight = obj.offsetHeight;
var optionCount = obj.options.length;
var eX = e.offsetX;
var eY = e.offsetY;
//vertical position within select will roughly give the moused over option...
var hoverOptionIndex = Math.floor(eY / (objHeight / optionCount));
var tooltip = document.getElementById('dvDiv');
tooltip.innerHTML = obj.options[hoverOptionIndex].title;
mouseX=e.pageX?e.pageX:e.clientX;
mouseY=e.pageY?e.pageY:e.clientY;
tooltip.style.left=mouseX+10;
tooltip.style.top=mouseY;
tooltip.style.display = 'block';
var frm = document.getElementById("frm");
frm.style.left = tooltip.style.left;
frm.style.top = tooltip.style.top;
frm.style.height = tooltip.offsetHeight;
frm.style.width = tooltip.offsetWidth;
frm.style.display = "block";
}
function hideIETooltip(e){
var tooltip = document.getElementById('dvDiv');
var iFrm = document.getElementById('frm');
tooltip.innerHTML = '';
tooltip.style.display = 'none';
iFrm.style.display = 'none';
}
</script>
</head>
<body>
<select onmousemove="showIETooltip();" onmouseout="hideIETooltip();" size="10">
<option title="Option #1" value="1">Option #1</option>
<option title="Option #2" value="2">Option #2</option>
<option title="Option #3" value="3">Option #3</option>
<option title="Option #4" value="4">Option #4</option>
<option title="Option #5" value="5">Option #5</option>
<option title="Option #6" value="6">Option #6</option>
<option title="Option #7" value="7">Option #7</option>
<option title="Option #8" value="8">Option #8</option>
<option title="Option #9" value="9">Option #9</option>
<option title="Option #10" value="10">Option #10</option>
</select>
<div id="dvDiv" style="display:none;position:absolute;padding:1px;border:1px solid #333333;;background-color:#fffedf;font-size:smaller;z-index:999;"></div>
<iframe id="frm" style="display:none;position:absolute;z-index:998"></iframe>
</body>
</html>
This is the same answer as the doctors but it shows how to eliminate the problem with mutable arrays. If you use this kind of approach because of branch prediction first if will have very little to zero effect and whole code only calls mutable array values() function only once. As both variables are static they will not consume n * memory for every usage of this enumeration too.
private static boolean arrayCreated = false;
private static RFMsgType[] ArrayOfValues;
public static RFMsgType GetMsgTypeFromValue(int MessageID) {
if (arrayCreated == false) {
ArrayOfValues = RFMsgType.values();
}
for (int i = 0; i < ArrayOfValues.length; i++) {
if (ArrayOfValues[i].MessageIDValue == MessageID) {
return ArrayOfValues[i];
}
}
return RFMsgType.UNKNOWN;
}
This works for me:
In link, to attribute has value:
to="/filter/arr?fruits=apple&fruits=banana"
Route can handle this:
path="/filter/:arr"
For Multiple arrays:
to="filter/arr?fruits=apple&fruits=banana&vegetables=potato&vegetables=onion"
Route stays same.
SCREENSHOT
Thanks for the responses. I think I've solved the problem just now.
Since LD_PRELOAD is for setting some library proloaded, I check the library that ld preloads with LD_PRELOAD, one of which is "liblunar-calendar-preload.so", that is not existing in the path "/usr/lib/liblunar-calendar-preload.so", but I find a similar library "liblunar-calendar-preload-2.0.so", which is a difference version of the former one.
Then I guess maybe liblunar-calendar-preload.so was updated to a 2.0 version when the system updated, leaving LD_PRELOAD remain to be "/usr/lib/liblunar-calendar-preload.so". Thus the preload library name was not updated to the newest version.
To avoid changing environment variable, I create a symbolic link under the path "/usr/lib"
sudo ln -s liblunar-calendar-preload-2.0.so liblunar-calendar-preload.so
Then I restart bash, the error is gone.
Use this in your batch file:
%~dp0\bin\Iris.exe
%~dp0
resolves to the full path of the folder in which the batch script resides.
I think you just need to add 2 more options (contentType
and dataType
):
$('#my_get_related_keywords').click(function() {
$.ajax({
type: "POST",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8", // this
dataType: "json", // and this
success: function (msg) {
//do something
},
error: function (errormessage) {
//do something else
}
});
}
You can use pydoc
.
Open your terminal and type python -m pydoc list.append
The advantage of pydoc
over help()
is that you do not have to import a module to look at its help text.
For instance python -m pydoc random.randint
.
Also you can start an HTTP server to interactively browse documentation by typing python -m pydoc -b
(python 3)
For more information python -m pydoc
I'have tried all the answers nothing worked for me, The problem is coming form Xcode itself and has nothing to do with profiles and certificate :
Product > Scheme > Edit Scheme
In Run (Section) / info (tab) [select] the Release instead of debug as Build Configuration as follow :
It's a regression since Xcode 10.1
Config : Xcode Version 10.1 (10B61) Iphone X / IOS 12.1.4
if you are looking to generate all the number within a specific rang randomly then you can try
r = randi([a b],1,d)
a
= start point
b
= end point
d
= how many number you want to generate but keep in mind that d should be less than or equal to b-a
Try to disable your antivirus. Maybe it will make emulator a little bit faster.
Something like Rob W's answer, but allowing different a different ssh key, and works with older git versions (which don't have e.g. a core.sshCommand config).
I created the file ~/bin/git_poweruser
, with executable permission, and in the PATH:
#!/bin/bash
TMPDIR=$(mktemp -d)
trap 'rm -rf "$TMPDIR"' EXIT
cat > $TMPDIR/ssh << 'EOF'
#!/bin/bash
ssh -i $HOME/.ssh/poweruserprivatekey $@
EOF
chmod +x $TMPDIR/ssh
export GIT_SSH=$TMPDIR/ssh
git -c user.name="Power User name" -c user.email="[email protected]" $@
Whenever I want to commit or push something as "Power User", I use git_poweruser
instead of git
. It should work on any directory, and does not require changes in .gitconfig
or .ssh/config
, at least not in mine.
Also, for server admins, it may be important to note that browsers may present a prompt to the user if you use 307 redirect.
For example*, Firefox and Opera would ask the user for permission to redirect, whereas Chrome, IE and Safari would do the redirect transparently.
*per Bulletproof SSL and TLS (page 192).
I had the same problem. The answers got me on the right track. So the problem is that functions marked with async don't return a task of the function itself as expected (but another continuation task of the function).
So its the "await"and "async" keywords that screws thing up. The simplest solution then is simply to remove them. Then it works as expected. As in:
static void Main(string[] args)
{
Console.WriteLine("Foo called");
var result = Foo(5);
while (result.Status != TaskStatus.RanToCompletion)
{
Console.WriteLine("Thread ID: {0}, Status: {1}", Thread.CurrentThread.ManagedThreadId, result.Status);
Task.Delay(100).Wait();
}
Console.WriteLine("Result: {0}", result.Result);
Console.WriteLine("Finished.");
Console.ReadKey(true);
}
private static Task<string> Foo(int seconds)
{
return Task.Run(() =>
{
for (int i = 0; i < seconds; i++)
{
Console.WriteLine("Thread ID: {0}, second {1}.", Thread.CurrentThread.ManagedThreadId, i);
Task.Delay(TimeSpan.FromSeconds(1)).Wait();
}
return "Foo Completed.";
});
}
Which outputs:
Foo called
Thread ID: 1, Status: WaitingToRun
Thread ID: 3, second 0.
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 3, second 1.
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 3, second 2.
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 3, second 3.
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 3, second 4.
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Result: Foo Completed.
Finished.
std::cout << "Enter decimal number: " ;
std::cin >> input ;
std::cout << "0x" << std::hex << input << '\n' ;
if your adding a input that can be a boolean or float or int it will be passed back in the int main function call...
With function templates, based on argument types, C generates separate functions to handle each type of call appropriately. All function template definitions begin with the keyword template followed by arguments enclosed in angle brackets < and >. A single formal parameter T is used for the type of data to be tested.
Consider the following program where the user is asked to enter an integer and then a float, each uses the square function to determine the square. With function templates, based on argument types, C generates separate functions to handle each type of call appropriately. All function template definitions begin with the keyword template followed by arguments enclosed in angle brackets < and >. A single formal parameter T is used for the type of data to be tested.
Consider the following program where the user is asked to enter an integer and then a float, each uses the square function to determine the square.
#include <iostream>
using namespace std;
template <class T> // function template
T square(T); /* returns a value of type T and accepts type T (int or float or whatever) */
void main()
{
int x, y;
float w, z;
cout << "Enter a integer: ";
cin >> x;
y = square(x);
cout << "The square of that number is: " << y << endl;
cout << "Enter a float: ";
cin >> w;
z = square(w);
cout << "The square of that number is: " << z << endl;
}
template <class T> // function template
T square(T u) //accepts a parameter u of type T (int or float)
{
return u * u;
}
Here is the output:
Enter a integer: 5
The square of that number is: 25
Enter a float: 5.3
The square of that number is: 28.09
What I did:
composer update --prefer-source vendor/library-name
It fetches the library again along with it's git repo
The question is contradictory. It asks for a date without a time of day yet displays an example with a time of 00:00:00
.
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. See my other Answer for java.time solution.
If instead you want the time-of-day set to the first moment of the day, use a DateTime
object on the Joda-Time library and call its withTimeAtStartOfDay
method. Be aware that the first moment may not be the time 00:00:00
because of Daylight Saving Time or perhaps other anomalies.
(Using Python's terminology.)
To say Ruby uses "pass by value" or "pass by reference" isn't really descriptive enough to be helpful. I think as most people know it these days, that terminology ("value" vs "reference") comes from C++.
In C++, "pass by value" means the function gets a copy of the variable and any changes to the copy don't change the original. That's true for objects too. If you pass an object variable by value then the whole object (including all of its members) get copied and any changes to the members don't change those members on the original object. (It's different if you pass a pointer by value but Ruby doesn't have pointers anyway, AFAIK.)
class A {
public:
int x;
};
void inc(A arg) {
arg.x++;
printf("in inc: %d\n", arg.x); // => 6
}
void inc(A* arg) {
arg->x++;
printf("in inc: %d\n", arg->x); // => 1
}
int main() {
A a;
a.x = 5;
inc(a);
printf("in main: %d\n", a.x); // => 5
A* b = new A;
b->x = 0;
inc(b);
printf("in main: %d\n", b->x); // => 1
return 0;
}
Output:
in inc: 6
in main: 5
in inc: 1
in main: 1
In C++, "pass by reference" means the function gets access to the original variable. It can assign a whole new literal integer and the original variable will then have that value too.
void replace(A &arg) {
A newA;
newA.x = 10;
arg = newA;
printf("in replace: %d\n", arg.x);
}
int main() {
A a;
a.x = 5;
replace(a);
printf("in main: %d\n", a.x);
return 0;
}
Output:
in replace: 10
in main: 10
Ruby uses pass by value (in the C++ sense) if the argument is not an object. But in Ruby everything is an object, so there really is no pass by value in the C++ sense in Ruby.
In Ruby, "pass by object reference" (to use Python's terminology) is used:
Therefore Ruby does not use "pass by reference" in the C++ sense. If it did, then assigning a new object to a variable inside a function would cause the old object to be forgotten after the function returned.
class A
attr_accessor :x
end
def inc(arg)
arg.x += 1
puts arg.x
end
def replace(arg)
arg = A.new
arg.x = 3
puts arg.x
end
a = A.new
a.x = 1
puts a.x # 1
inc a # 2
puts a.x # 2
replace a # 3
puts a.x # 2
puts ''
def inc_var(arg)
arg += 1
puts arg
end
b = 1 # Even integers are objects in Ruby
puts b # 1
inc_var b # 2
puts b # 1
Output:
1
2
2
3
2
1
2
1
* This is why, in Ruby, if you want to modify an object inside a function but forget those changes when the function returns, then you must explicitly make a copy of the object before making your temporary changes to the copy.
For a String constant you have no choice other than escaping via backslash.
Maybe you find the MyBatis project interesting. It is a thin layer over JDBC where you can externalize your SQL queries in XML configuration files without the need to escape double quotes.
Use the built-in isinstance()
function.
import pandas as pd
def f(var):
if isinstance(var, pd.DataFrame):
print("do stuff")
Technically, it's 'possible', but under very strict conditions (rainbow tables, brute forcing based on the very small possibility that a user's password is in that hash database).
But that doesn't mean it's
You don't want to 'reverse' an MD5 hash. Using the methods outlined below, you'll never need to. 'Reversing' MD5 is actually considered malicious - a few websites offer the ability to 'crack' and bruteforce MD5 hashes - but all they are are massive databases containing dictionary words, previously submitted passwords and other words. There is a very small chance that it will have the MD5 hash you need reversed. And if you've salted the MD5 hash - this won't work either! :)
The way logins with MD5 hashing should work is:
During Registration:
User creates password -> Password is hashed using MD5 -> Hash stored in database
During Login:
User enters username and password -> (Username checked) Password is hashed using MD5 -> Hash is compared with stored hash in database
When 'Lost Password' is needed:
2 options:
or
I had the same problem in docker
and these steps worked for me:
apt update
then:
apt install libsm6 libxext6 libxrender-dev
Below is the code using lambdas
#include "stdafx.h"
#include <vector>
#include <algorithm>
using namespace std;
struct MyStruct
{
int key;
std::string stringValue;
MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}
};
int main()
{
std::vector < MyStruct > vec;
vec.push_back(MyStruct(4, "test"));
vec.push_back(MyStruct(3, "a"));
vec.push_back(MyStruct(2, "is"));
vec.push_back(MyStruct(1, "this"));
std::sort(vec.begin(), vec.end(),
[] (const MyStruct& struct1, const MyStruct& struct2)
{
return (struct1.key < struct2.key);
}
);
return 0;
}
Check the following one-liner:
print('\n'.join("%s\n%s" % (key1,('\n'.join("%s : %r" % (key2,val2) for (key2,val2) in val1.items()))) for (key1,val1) in cars.items()))
Output:
A
speed : 70
color : 2
B
speed : 60
color : 3
I can think of different method to achieve the same
IList<SelectableEnumItem> result= array;
or (i had some situation that this one didn't work well)
var result = (List<SelectableEnumItem>) array;
or use linq extension
var result = array.CastTo<List<SelectableEnumItem>>();
or
var result= array.Select(x=> x).ToArray<SelectableEnumItem>();
or more explictly
var result= array.Select(x=> new SelectableEnumItem{FirstName= x.Name, Selected = bool.Parse(x.selected) });
please pay attention in above solution I used dynamic Object
I can think of some more solutions that are combinations of above solutions. but I think it covers almost all available methods out there.
Myself I use the first one
I guess you had an error in the inline code of your image. Try this :
var image = document.createElement('img');_x000D_
_x000D_
image.src="data:image/gif;base64,R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw==";_x000D_
_x000D_
image.width=100;_x000D_
image.height=100;_x000D_
image.alt="here should be some image";_x000D_
_x000D_
document.body.appendChild(image);
_x000D_
Helpful link :http://dean.edwards.name/my/base64-ie.html
I would try to specify something like
var searchPattern = "as?x";
it should work.
<img title="<a href="javascript:alert('hello world')">The Link</a>" />
Just in case your PC is not a "Western" PC and you don't know which code page is used, you can have a look at this page: National Language Support (NLS) API Reference
[Microsoft removed this reference, take it form web-archive National Language Support (NLS) API Reference
Or you can query your registry:
C:\>reg query HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage /f ACP
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage
ACP REG_SZ 1252
End of search: 1 match(es) found.
C:\>
Thing which works for me is to use padding-bottom on the sibling just before the absolutely-positioned child. Like in your case, it will be like this:
<div style="position: relative; width:600px;">
<p>Content of unknown length, but quite quite quite quite quite quite quite quite quite quite quite quite quite quite quite quite long</p>
<div style="padding-bottom: 100px;">Content of unknown height</div>
<div class="btn" style="position: absolute; right: 0; bottom: 0; width: 200px; height: 100px;background-color: red;"></div>
</div>
You need to set the classpath to find your compiled class:
java -cp C:\Users\Matt\workspace\HelloWorld2\bin HelloWorld2
Disable "instant run", you can go to Preference Dialog ( May be Setting dialog on Windows), then select Build, Execution, Deployment > Instant Run, and uncheck all the checkbox to disable Instant Run.
And Reboot your Device this should make the thing work....instant run has a bug in Android studio 2+ This should do the magic
Use this and form the query
SELECT Concat('TRUNCATE TABLE ',table_schema,'.',TABLE_NAME, ';')
FROM INFORMATION_SCHEMA.TABLES where table_schema in (db1,db2)
INTO OUTFILE '/path/to/file.sql';
Now use this to use this query
mysql -u username -p </path/to/file.sql
if you get an error like this
ERROR 1701 (42000) at line 3: Cannot truncate a table referenced in a foreign key constraint
the easiest way to go through is at the top of your file add this line
SET FOREIGN_KEY_CHECKS=0;
which says that we don't want to check the foreign key constraints while going through this file.
It will truncate all tables in databases db1 and bd2.
Another solution for this issue is use commons-lang (since version 2.0) StringUtils.substringBetween(String str, String open, String close)
method. Main advantage is that it's null safe operation.
StringUtils.substringBetween("[wdsd34svdf]", "[", "]"); // returns wdsd34svdf
As mentioned in other answers, it is possible to construct the required behaviour / errors from using different flags with os.OpenFile
. In fact, os.Create
is just a sensible-defaults shorthand for doing so:
// Create creates or truncates the named file. If the file already exists,
// it is truncated. If the file does not exist, it is created with mode 0666
// (before umask). If successful, methods on the returned File can
// be used for I/O; the associated file descriptor has mode O_RDWR.
// If there is an error, it will be of type *PathError.
func Create(name string) (*File, error) {
return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666)
}
You should combine these flags yourself to get the behaviour you are interested in:
// Flags to OpenFile wrapping those of the underlying system. Not all
// flags may be implemented on a given system.
const (
// Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
O_RDONLY int = syscall.O_RDONLY // open the file read-only.
O_WRONLY int = syscall.O_WRONLY // open the file write-only.
O_RDWR int = syscall.O_RDWR // open the file read-write.
// The remaining values may be or'ed in to control behavior.
O_APPEND int = syscall.O_APPEND // append data to the file when writing.
O_CREATE int = syscall.O_CREAT // create a new file if none exists.
O_EXCL int = syscall.O_EXCL // used with O_CREATE, file must not exist.
O_SYNC int = syscall.O_SYNC // open for synchronous I/O.
O_TRUNC int = syscall.O_TRUNC // truncate regular writable file when opened.
)
Depending on what you pick, you will get different errors.
Here's an example where I wish to open a file for writing, but I will only truncate an existing file if the user has said that is OK:
var f *os.File
if truncateWhenExists {
// O_TRUNC - truncate regular writable file when opened.
if f, err = os.OpenFile(filepath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644); err != nil {
log.Fatalln("failed to force-open file, err:", err)
}
} else {
// O_EXCL - used with O_CREATE, file must not exist
if f, err = os.OpenFile(filepath, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0644); err != nil {
log.Fatalln("failed to open file, err:", err)
}
}
With Swift 5, you can use String
's init(data:encoding:)
initializer in order to convert a Data
instance into a String
instance using UTF-8. init(data:encoding:)
has the following declaration:
init?(data: Data, encoding: String.Encoding)
Returns a
String
initialized by converting given data into Unicode characters using a given encoding.
The following Playground code shows how to use it:
import Foundation
let json = """
{
"firstName" : "John",
"lastName" : "Doe"
}
"""
let data = json.data(using: String.Encoding.utf8)!
let optionalString = String(data: data, encoding: String.Encoding.utf8)
print(String(describing: optionalString))
/*
prints:
Optional("{\n\"firstName\" : \"John\",\n\"lastName\" : \"Doe\"\n}")
*/
And just to provide a contrast, there's also pip.
I'm going to assume compiling the QuickFix package does not produce a setup.py
file, but rather only compiles the Python bindings and relies on make install
to put them in the appropriate place.
In this case, a quick and dirty fix is to compile the QuickFix source, locate the Python extension modules (you indicated on your system these end with a .so
extension), and add that directory to your PYTHONPATH
environmental variable e.g., add
export PYTHONPATH=~/path/to/python/extensions:PYTHONPATH
or similar line in your shell configuration file.
A more robust solution would include making sure to compile with ./configure --prefix=$HOME/.local
. Assuming QuickFix knows to put the Python files in the appropriate site-packages
, when you do make install
, it should install the files to ~/.local/lib/pythonX.Y/site-packages
, which, for Python 2.6+, should already be on your Python path as the per-user site-packages directory.
If, on the other hand, it did provide a setup.py
file, simply run
python setup.py install --user
for Python 2.6+.
On Windows, you can use Mac on a virtual machine (this probably also works on Linux but I haven't tested). A virtual machine is basically a program that you run on your computer that allows you to run one OS in a window inside another one. Make sure you have at least 60GB free space on your hard drive. The virtual hard drive that you will download takes up 10GB initially but when you've installed all the necessary programs for developing iOS apps its size can easily increase to 50GB (I recommend leaving a few GBs margin just in case).
Here are some detailed steps for how install a Mac virtual machine on Windows:
Install VirtualBox.
You have to enable virtualization in the BIOS. To open the BIOS on Windows 10, you need to start by holding down the Shift key while pressing the Restart button in the start menu. Then you will get a blue screen with some options. Choose "Troubleshoot", then "Advanced options", then "UEFI Firmware Settings", then "Restart". Then your computer will restart and open the BIOS directly. On older versions of Windows, shut down the computer normally, hold the F2 key down, start your computer again and don't release F2 until you're in the BIOS. On some computers you may have to hold down another key than F2.
Now that you're in the BIOS, you need to enable virtualization. Which setting you're supposed to change depends on which computer you're using. This may vary even between two computers with the same version of Windows. On my computer, you need to set Intel Virtual Technology
in the Configuration
tab to Enabled
. On other computers it may be in for example Security -> Virtualization
or in Advanced -> CPU Setup
. If you can't find any of these options, search Google for enable virtualization (the kind of computer you have)
. Don't change anything in the BIOS just like that at random because otherwise it could cause problems on your computer. When you've enabled virtualization, save the changes and exit the BIOS. This is usually done in the Exit
tab.
Download this file (I have no association with the person who uploaded it, but I've used it myself so I'm sure there are no viruses). If the link gets broken, post a comment to let me know and I will try to upload the file somewhere else. The password to open the 7Z file is stackoverflow.com
. This 7Z file contains a VMDK file which will act as the hard drive for the Mac virtual machine. Extract that VMDK file. If disk space is an issue for you, once you've extracted the VMDK file, you can delete the 7Z file and therefore save 7GB.
Open VirtualBox that you installed in step 1. In the toolbar, press the New button. Then choose a name for your virtual machine (the name is unimportant, I called it "Mac"). In "Type", select "Mac OS X" and in "Version" select "macOS 10.13 High Sierra (64 bit)" (the Mac version you will install on the virtual machine is actually Catalina, but VirtualBox doesn't have that option yet and it works just fine if VirtualBox thinks it's High Sierra).
It's also a good idea (though not required) to move the VMDK file you extracted in step 4 to the folder listed under "Machine Folder" (in the screenshot above that would be C:\Users\myname\VirtualBox VMs
).
Select the amount of memory that your virtual machine can use. Try to balance the amount because too little memory will result in the virtual machine having low performance and a too much memory will result making your host system (Windows) run out of memory which will cause the virtual machine and/or other programs that you're running on Windows to crash. On a computer with 4GB available memory, 2GB was a good amount. Don't worry if you select a bad amount, you will be able to change it whenever you want (except when the virtual machine is running).
In the Hard disk step, choose "Use an existing virtual hard disk file" and click on the little folder icon to the right of the drop list. That will open a new window. In that new window, click on the "Add" button on the top left, which will open a browse window. Select the VMDK file that you downloaded and extracted in step 4, then click "Choose".
When you're done with this, click "Create".
Select the virtual machine in the list on the left of the window and click on the Settings button in the toolbar. In System -> Processor, select 2 CPUs; and in Network -> Attached to, select Bridged Adapter. If you realize later that you selected an amount of memory in step 6 that causes problems, you can change it in System -> Motherboard. When you're done changing the settings, click OK.
Open the command prompt (C:\Windows\System32\cmd.exe
). Run the following commands in there, replacing "Your VM Name"
with whatever you called your virtual machine in step 5 (for example "Mac"
) (keep the quotation marks):
cd "C:\Program Files\Oracle\VirtualBox\"
VBoxManage.exe modifyvm "Your VM Name" --cpuidset 00000001 000106e5 00100800 0098e3fd bfebfbff
VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/efi/0/Config/DmiSystemProduct" "iMac11,3"
VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/efi/0/Config/DmiSystemVersion" "1.0"
VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/efi/0/Config/DmiBoardProduct" "Iloveapple"
VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/smc/0/Config/DeviceKey" "ourhardworkbythesewordsguardedpleasedontsteal(c)AppleComputerInc"
VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/smc/0/Config/GetKeyFromRealSMC" 1
VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/efi/0/Config/DmiSystemSerial" C02L280HFMR7
Now everything is ready for you to use the virtual machine. In VirtualBox, click on the Start button and follow the installation instructions for Mac. Once you've installed Mac on the virtual machine, you can develop your iOS app just like if you had a real Mac.
Remark: If you want to save space on your hard disk, you can compress the VMDK file that you extracted in step 4 and used in step 7. To do this, right click on it, select Properties, click on the Advanced... button on the bottom right, and check the checkbox "Compress contents to save disk space". This will make this very large file take less disk space without making anything work less well. I did it and it reduced the disk size of the VMDK file from 50GB to 40GB without losing any data.
c:out
also has an attribute for assigning a default value if the value of person.name
happens to be null.
BehaviorSubject
The BehaviorSubject builds on top of the same functionality as our ReplaySubject, subject like, hot, and replays previous value.
The BehaviorSubject adds one more piece of functionality in that you can give the BehaviorSubject an initial value. Let’s go ahead and take a look at that code
import { ReplaySubject } from 'rxjs';
const behaviorSubject = new BehaviorSubject(
'hello initial value from BehaviorSubject'
);
behaviorSubject.subscribe(v => console.log(v));
behaviorSubject.next('hello again from BehaviorSubject');
Observables
To get started we are going to look at the minimal API to create a regular Observable. There are a couple of ways to create an Observable. The way we will create our Observable is by instantiating the class. Other operators can simplify this, but we will want to compare the instantiation step to our different Observable types
import { Observable } from 'rxjs';
const observable = new Observable(observer => {
setTimeout(() => observer.next('hello from Observable!'), 1000);
});
observable.subscribe(v => console.log(v));
Another important difference in this context would with process.stdout.clearLine()
and process.stdout.cursorTo(0)
.
This would be useful if you want to show percentage of download or processing in the only one line. If you use clearLine(), cursorTo() with console.log()
it doesn't work because it also append \n to the text. Just try out this example:
var waitInterval = 500;
var totalTime = 5000;
var currentInterval = 0;
function showPercentage(percentage){
process.stdout.clearLine();
process.stdout.cursorTo(0);
console.log(`Processing ${percentage}%...` ); //replace this line with process.stdout.write(`Processing ${percentage}%...`);
}
var interval = setInterval(function(){
currentInterval += waitInterval;
showPercentage((currentInterval/totalTime) * 100);
}, waitInterval);
setTimeout(function(){
clearInterval(interval);
}, totalTime);
This might give the increased relevance to the head part that you want. It won't double it, but it might possibly good enough for your sake:
SELECT pages.*,
MATCH (head, body) AGAINST ('some words') AS relevance,
MATCH (head) AGAINST ('some words') AS title_relevance
FROM pages
WHERE MATCH (head, body) AGAINST ('some words')
ORDER BY title_relevance DESC, relevance DESC
-- alternatively:
ORDER BY title_relevance + relevance DESC
An alternative that you also want to investigate, if you've the flexibility to switch DB engine, is Postgres. It allows to set the weight of operators and to play around with the ranking.
You can do this:
fso.CopyFile "C:\Minecraft\options.txt", "H:\Minecraft\.minecraft\options.txt"
Include the filename in the folder that you copy to.
No guarantee, but I suspect IE uses the older Protected Storage API.
An alternative way without the [<-
function:
A sample data frame dat
(shamelessly copied from @Chase's answer):
dat
x y
1 0 2
2 1 2
3 1 1
4 2 1
5 0 0
Zeroes can be replaced with NA
by the is.na<-
function:
is.na(dat) <- !dat
dat
x y
1 NA 2
2 1 2
3 1 1
4 2 1
5 NA NA
Apache Commons collection classes is the solution.
MultiMap multiMapDemo = new MultiValueMap();
multiMapDemo .put("fruit", "Mango");
multiMapDemo .put("fruit", "Orange");
multiMapDemo.put("fruit", "Blueberry");
System.out.println(multiMap.get("fruit"));
// Mango Orange Blueberry
Maven Dependency
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 --
>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
In my case, I was using https redirection just before adding cors middleware and able to fix the issue by changing order of them
What i mean is:
change this:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseHttpsRedirection();
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
...
}
to this:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseHttpsRedirection();
...
}
By the way, allowing requests from any origins and methods may not be a good idea for production stage, you should write your own cors policies at production.
Goto your_severpath/apache_ver/conf/
Open the file httpd.conf
in Notepad.
Find this line:
#LoadModule vhost_alias_module modules/mod_vhost_alias.so
Remove the hash symbol:
LoadModule vhost_alias_module modules/mod_vhost_alias.so
Then goto <Directory />
and change to:
<Directory />
Options FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
</Directory>
Then restart your local server.
You can use jstat, like :
jstat -gc pid
Full docs here : http://docs.oracle.com/javase/7/docs/technotes/tools/share/jstat.html
Building on @Waterscroll's response, if you want to use async and await in node 8+:
const fs = require('fs');
const util = require('util');
const readdir = util.promisify(fs.readdir);
const unlink = util.promisify(fs.unlink);
const directory = 'test';
async function toRun() {
try {
const files = await readdir(directory);
const unlinkPromises = files.map(filename => unlink(`${directory}/${filename}`));
return Promise.all(unlinkPromises);
} catch(err) {
console.log(err);
}
}
toRun();
import logging
urllib3_logger = logging.getLogger('urllib3')
urllib3_logger.setLevel(logging.CRITICAL)
In this way all the messages of level=INFO from urllib3 won't be present in the logfile.
So you can continue to use the level=INFO for your log messages...just modify this for the library you are using.
What you have here is a non-local variable (https://en.wikipedia.org/wiki/Non-local_variable), i.e. you access a local variable in a method an anonymous class.
Local variables of the method are kept on the stack and lost as soon as the method ends, however even after the method ends, the local inner class object is still alive on the heap and will need to access this variable (here, when an action is performed).
I would suggest two workarounds :
Either you make your own class that implements actionlistenner
and takes as constructor argument, your variable and keeps it as an class attribute. Therefore you would only access this variable within the same object.
Or (and this is probably the best solution) just qualify a copy of the variable final
to access it in the inner scope as the error suggests to make it a constant:
This would suit your case since you are not modifying the value of the variable.
You can import svg and it use it like a image
import chatSVG from '../assets/images/undraw_typing_jie3.svg'
And ise it in img tag
<img src={chatSVG} className='iconChat' alt="Icon chat"/>
Similar to other answers I had miss typed the query.
I had -
SELECT t.id FROM t.table LEFT JOIN table2 AS t2 ON t.id = t2.table_id
Should have been
SELECT t.id FROM table AS t LEFT JOIN table2 AS t2 ON t.id = t2.table_id
Mysql was trying to find a database called t which the user didn't have permission for.
HttpContext.Current
returns an instance of System.Web.HttpContext
, which does not extend System.Web.HttpContextBase
. HttpContextBase
was added later to address HttpContext
being difficult to mock. The two classes are basically unrelated (HttpContextWrapper
is used as an adapter between them).
Fortunately, HttpContext
itself is fakeable just enough for you do replace the IPrincipal
(User) and IIdentity
.
The following code runs as expected, even in a console application:
HttpContext.Current = new HttpContext(
new HttpRequest("", "http://tempuri.org", ""),
new HttpResponse(new StringWriter())
);
// User is logged in
HttpContext.Current.User = new GenericPrincipal(
new GenericIdentity("username"),
new string[0]
);
// User is logged out
HttpContext.Current.User = new GenericPrincipal(
new GenericIdentity(String.Empty),
new string[0]
);
Try command + t
.
It works for me.
...a very small library of components which you can use to help organise your code. It comes packaged as a single JavaScript file. Excluding comments, it has less than 1000 lines of actual JavaScript. It's sensibly written and you can read the whole thing in a couple of hours.
It's a front-end library, you include it in your web page with a script tag. It only affects the browser, and says little about your server, except that it should ideally expose a restful API.
If you have an API, Backbone has a few helpful features that will help you talk to it, but you can use Backbone to add interactivity to any static HTML page.
...adding structure to JavaScript.
Because JavaScript doesn't enforce any particular patterns, JavaScript applications can become very messy very quickly. Anyone who has built something beyond trivial in JavaScript will have likely run up against questions such as:
Backbone seeks to answer these questions by giving you:
We call this an MV* pattern. Models, Views and optional extras.
Despite initial appearances, Backbone is fantastically light, it hardly does anything at all. What it does do is very helpful.
It gives you a set of little objects which you can create, and which can emit events and listen to each other. You might create a little object to represent a comment for example, and then a little commentView object to represent the display of the comment in a particular place in the browser.
You can tell the commentView to listen to the comment and redraw itself when the comment changes. Even if you have the same comment displayed in several places on your page all these views can listen to the same comment model and stay in sync.
This way of composing code helps to keep you from getting tangled even if your codebase becomes very large with many interactions.
When starting out, it's common to store your data either in a global variable, or in the DOM as data attributes. Both of these have issues. Global variables can conflict with each other, and are generally bad form. Data attributes stored in the DOM can only be strings, you will have to parse them in and out again. It's difficult to store things like arrays, dates or objects, and to parse your data in a structured form.
Data attributes look like this:
<p data-username="derek" data-age="42"></p>
Backbone solves this by providing a Model object to represent your data and associated methods. Say you have a todo list, you would have a model representing each item on that list.
When your model is updated, it fires an event. You might have a view tied to that particular object. The view listens for model change events and re-renders itself.
Backbone provides you with View objects that talk to the DOM. All functions that manipulate the DOM or listen for DOM events go here.
A View typically implements a render function which redraws the whole view, or possibly part of the view. There's no obligation to implement a render function, but it's a common convention.
Each view is bound to a particular part of the DOM, so you might have a searchFormView, that only listens to the search form, and a shoppingCartView, that only displays the shopping cart.
Views are typically also bound to specific Models or Collections. When the Model updates, it fires an event which the view listens to. The view might them call render to redraw itself.
Likewise, when you type into a form, your view can update a model object. Every other view listening to that model will then call its own render function.
This gives us a clean separation of concerns that keeps our code neat and tidy.
You can implement your render function in any way you see fit. You might just put some jQuery in here to update the DOM manually.
You might also compile a template and use that. A template is just a string with insertion points. You pass it to a compile function along with a JSON object and get back a compiled string which you can insert into your DOM.
You also have access to collections which store lists of models, so a todoCollection would be a list of todo models. When a collection gains or loses a model, changes its order, or a model in a collection updates, the whole collection fires an event.
A view can listen to a collection and update itself whenever the collection updates.
You could add sort and filter methods to your collection, and make it sort itself automatically for example.
As much as possible, application components are decoupled from each other. They communicate using events, so a shoppingCartView might listenTo a shoppingCart collection, and redraw itself when the cart is added to.
shoppingCartView.listenTo(shoppingCart, "add", shoppingCartView.render);
Of course, other objects might also be listening to the shoppingCart as well, and might do other things like update a total, or save the state in local storage.
Decoupling your objects like this and communicating using events means that you'll never get tangled in knots, and adding new components and behaviour is easy. Your new components just have to listen to the other objects already in the system.
Code written for Backbone follows a loose set of conventions. DOM code belongs in a View. Collection code belongs in a Collection. Business logic goes in a model. Another developer picking up your codebase will be able to hit the ground running.
Backbone is a lightweight library that lends structure to your code. Components are decoupled and communicate via events so you won't end up in a mess. You can extend your codebase easily, simply by creating a new object and having it listen to your existing objects appropriately. Your code will be cleaner, nicer, and more maintainable.
I liked Backbone so much that I wrote a little intro book about it. You can read it online here: http://nicholasjohnson.com/backbone-book/
I also broke the material down into a short online course, which you can find here: http://www.forwardadvance.com/course/backbone. You can complete the course in about a day.
So, i present cmdmsg.bat.
The code is:
@echo off
echo WScript.Quit MsgBox(%1, vbYesNo) > #.vbs
cscript //nologo #.vbs
echo. >%ERRORLEVEL%.cm
del #.vbs
exit /b
And a example file:
@echo off
cls
call cmdmsg "hi select yes or no"
if exist "6.cm" call :yes
if exist "7.cm" call :no
:yes
cls
if exist "6.cm" del 6.cm
if exist "7.cm" del 7.cm
echo.
echo you selected yes
echo.
pause >nul
exit /b
:no
cls
if exist "6.cm" del 6.cm
if exist "7.cm" del 7.cm
echo.
echo aw man, you selected no
echo.
pause >nul
exit /b
Adding java.util.list
will resolve your problem because List interface which you are trying to use is part of java.util.list
package.
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Source (Py v2.7.3) for traceback.format_exception() and called/related functions helps greatly. Embarrassingly, I always forget to Read the Source. I only did so for this after searching for similar details in vain. A simple question, "How to recreate the same output as Python for an exception, with all the same details?" This would get anybody 90+% to whatever they're looking for. Frustrated, I came up with this example. I hope it helps others. (It sure helped me! ;-)
import sys, traceback
traceback_template = '''Traceback (most recent call last):
File "%(filename)s", line %(lineno)s, in %(name)s
%(type)s: %(message)s\n''' # Skipping the "actual line" item
# Also note: we don't walk all the way through the frame stack in this example
# see hg.python.org/cpython/file/8dffb76faacc/Lib/traceback.py#l280
# (Imagine if the 1/0, below, were replaced by a call to test() which did 1/0.)
try:
1/0
except:
# http://docs.python.org/2/library/sys.html#sys.exc_info
exc_type, exc_value, exc_traceback = sys.exc_info() # most recent (if any) by default
'''
Reason this _can_ be bad: If an (unhandled) exception happens AFTER this,
or if we do not delete the labels on (not much) older versions of Py, the
reference we created can linger.
traceback.format_exc/print_exc do this very thing, BUT note this creates a
temp scope within the function.
'''
traceback_details = {
'filename': exc_traceback.tb_frame.f_code.co_filename,
'lineno' : exc_traceback.tb_lineno,
'name' : exc_traceback.tb_frame.f_code.co_name,
'type' : exc_type.__name__,
'message' : exc_value.message, # or see traceback._some_str()
}
del(exc_type, exc_value, exc_traceback) # So we don't leave our local labels/objects dangling
# This still isn't "completely safe", though!
# "Best (recommended) practice: replace all exc_type, exc_value, exc_traceback
# with sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]
print
print traceback.format_exc()
print
print traceback_template % traceback_details
print
In specific answer to this query:
sys.exc_info()[0].__name__, os.path.basename(sys.exc_info()[2].tb_frame.f_code.co_filename), sys.exc_info()[2].tb_lineno
From your screenshot it appears you have ReSharper installed.
Depending on the key binding options you chose when you installed it, some of your standard shortcuts may now be redirected to ReSharper commands. It's worth checking, for example Ctrl+E, C is used by R# for the code cleanup dialog.
I have just tested the following pipeline and it works
parallel firstBranch: {
stage ('Starting Test')
{
build job: 'test1', parameters: [string(name: 'Environment', value: "$env.Environment")]
}
}, secondBranch: {
stage ('Starting Test2')
{
build job: 'test2', parameters: [string(name: 'Environment', value: "$env.Environment")]
}
}
This Job named 'trigger-test' accepts one parameter named 'Environment'
Job 'test1' and 'test2' are simple jobs:
Example for 'test1'
On execution, I am able to see both stages running in the same time
Cannot comment anymore but voted it up and wanted to let folks know that "
works very well for the xml config files when forming regex expressions for RegexTransformer in Solr like so: regex=".*img src="(.*)".*"
using the escaped version instead of double-quotes.
by using replaceChild():
<html>
<head>
</head>
<body>
<div>
<a id="myAnchor" href="http://www.stackoverflow.com">StackOverflow</a>
</div>
<script type="text/JavaScript">
var myAnchor = document.getElementById("myAnchor");
var mySpan = document.createElement("span");
mySpan.innerHTML = "replaced anchor!";
myAnchor.parentNode.replaceChild(mySpan, myAnchor);
</script>
</body>
</html>
The solution above was not working for me. I had to set 'class count to use import with '*'' to a high value, e.g. 999.