Install a cross compiler, like mingw64 from your package manager.
Then compile in the following way: instead of simply calling gcc
call i686-w64-mingw32-gcc
for 32-bit Windows or x86_64-w64-mingw32-gcc"
for 64-bit Windows. I would also use the --static
option, as the target system may not have all the libraries.
If you want to compile other language, like Fortran, replace -gcc
with -gfortran
in the previous commands.
Yet another alternative to manage multiple jdk versions is jEnv
After installation, you can simply change java version "locally" i.e. for a specific project directory by:
jenv local 1.6
This will also make mvn use that version locally, when you enable the mvn plugin:
jenv enable-plugin maven
The error message is fairly self-explanatory
(a,b,c,d,e) = line.split()
expects line.split()
to yield 5 elements, but in your case, it is only yielding 1 element. This could be because the data is not in the format you expect, a rogue malformed line, or maybe an empty line - there's no way to know.
To see what line is causing the issue, you could add some debug statements like this:
if len(line.split()) != 11:
print line
As Martin suggests, you might also be splitting on the wrong delimiter.
According to JVM specification, fields and methods in a Interface can have only Public, Static, Final and Abstract. Ref from Inside Java VM
By default, all the methods in interface is abstract even tough you didn't mention it explicitly.
Interfaces are meant to give only specification. It can not contain any implementations. So To avoid implementing classes to change the specification, it is made final. Since Interface cannot be instantiated, they are made static to access the field using interface name.
Groovy accepts nearly all Java syntax, so there is a spectrum of choices, as illustrated below:
// Java syntax
Map<String,List> map1 = new HashMap<>();
List list1 = new ArrayList();
list1.add("hello");
map1.put("abc", list1);
assert map1.get("abc") == list1;
// slightly less Java-esque
def map2 = new HashMap<String,List>()
def list2 = new ArrayList()
list2.add("hello")
map2.put("abc", list2)
assert map2.get("abc") == list2
// typical Groovy
def map3 = [:]
def list3 = []
list3 << "hello"
map3.'abc'= list3
assert map3.'abc' == list3
When the result is success but you get the "<" character, it means that some PHP error is returned.
If you want to see all message, you could get the result as a success response getting by the following:
success: function(response){
var out = "";
for(var i = 0; i < response.length; i++) {
out += response[i];
}
alert(out) ;
},
The error means that you are providing not as much data as the table wp_posts
does contain columns. And now the DB engine does not know in which columns to put your data.
To overcome this you must provide the names of the columns you want to fill. Example:
insert into wp_posts (column_name1, column_name2)
values (1, 3)
Look up the table definition and see which columns you want to fill.
And insert
means you are inserting a new record. You are not modifying an existing one. Use update
for that.
You can use a set which is an unordered collection of unique elements to do keep the "order of the other columns untouched":
other_columns = list(set(df.columns).difference(["mean"])) #[0, 1, 2, 3, 4]
Then, you can use a lambda to move a specific column to the front by:
In [1]: import numpy as np
In [2]: import pandas as pd
In [3]: df = pd.DataFrame(np.random.rand(10, 5))
In [4]: df["mean"] = df.mean(1)
In [5]: move_col_to_front = lambda df, col: df[[col]+list(set(df.columns).difference([col]))]
In [6]: move_col_to_front(df, "mean")
Out[6]:
mean 0 1 2 3 4
0 0.697253 0.600377 0.464852 0.938360 0.945293 0.537384
1 0.609213 0.703387 0.096176 0.971407 0.955666 0.319429
2 0.561261 0.791842 0.302573 0.662365 0.728368 0.321158
3 0.518720 0.710443 0.504060 0.663423 0.208756 0.506916
4 0.616316 0.665932 0.794385 0.163000 0.664265 0.793995
5 0.519757 0.585462 0.653995 0.338893 0.714782 0.305654
6 0.532584 0.434472 0.283501 0.633156 0.317520 0.994271
7 0.640571 0.732680 0.187151 0.937983 0.921097 0.423945
8 0.562447 0.790987 0.200080 0.317812 0.641340 0.862018
9 0.563092 0.811533 0.662709 0.396048 0.596528 0.348642
In [7]: move_col_to_front(df, 2)
Out[7]:
2 0 1 3 4 mean
0 0.938360 0.600377 0.464852 0.945293 0.537384 0.697253
1 0.971407 0.703387 0.096176 0.955666 0.319429 0.609213
2 0.662365 0.791842 0.302573 0.728368 0.321158 0.561261
3 0.663423 0.710443 0.504060 0.208756 0.506916 0.518720
4 0.163000 0.665932 0.794385 0.664265 0.793995 0.616316
5 0.338893 0.585462 0.653995 0.714782 0.305654 0.519757
6 0.633156 0.434472 0.283501 0.317520 0.994271 0.532584
7 0.937983 0.732680 0.187151 0.921097 0.423945 0.640571
8 0.317812 0.790987 0.200080 0.641340 0.862018 0.562447
9 0.396048 0.811533 0.662709 0.596528 0.348642 0.563092
You can simply set the window state
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
Filter
app.filter('unsafe', function($sce) { return $sce.trustAsHtml; });
Usage
<ANY ng-bind-html="value | unsafe"></ANY>
// On the state
constructor() {
this.state = {
email: ''
}
}
// Input view ( always check if property is available in state {this.state.email ? this.state.email : ''}
<Input
value={this.state.email ? this.state.email : ''}
onChange={event => this.setState({ email: event.target.value)}
type="text"
name="emailAddress"
placeholder="[email protected]" />
Pycharm 2020.3.3 CE ZorinOS(Linux) File>Settings > Project Structure > {select the folder} > Mark as Source(blue folder icon) > Apply
To verify:
import sys
print(sys.path)
Selected path should be listed here.
Modifying the example here:
You can use legend_out = False
import seaborn as sns
sns.set(style="whitegrid")
titanic = sns.load_dataset("titanic")
g = sns.factorplot("class", "survived", "sex",
data=titanic, kind="bar",
size=6, palette="muted",
legend_out=False)
g.despine(left=True)
g.set_ylabels("survival probability")
Code below does not print boolean, but allows for dataframe subsetting by index... I understand this is likely not the most efficient way to solve the problem, but I (1) like the way this reads and (2) you can easily subset where df1 index exists in df2:
df3 = df1[df1.index.isin(df2.index)]
or where df1 index does not exist in df2...
df3 = df1[~df1.index.isin(df2.index)]
Your specific error is with line 11:
awk 'BEGIN{sum+=$2}'
This is a line where awk
is invoked, and its BEGIN
block is specified - but you are already within a awk script, so you do not need to specify awk
. Also you want to run sum+=$2
on each line of input, so you do not want it within a BEGIN
block. Hence the line should simply read:
sum+=$2
You also do not need the lines:
x=sum
read name
the first just creates a synonym to sum
named x
and I'm not sure what the second does, but neither are needed.
This would make your awk script:
#!/bin/awk
### This script currently prints the total number of rows processed.
### You must edit this script to print the average of the 2nd column
### instead of the number of rows.
# This block of code is executed for each line in the file
{
sum+=$2
# The script should NOT print out a value for each line
}
# The END block is processed after the last line is read
END {
# NR is a variable equal to the number of rows in the file
print "Average: " sum/ NR
# Change this to print the Average instead of just the number of rows
}
Jonathan Leffler's answer gives the awk one liner which represents the same fixed code, with the addition of checking that there are at least 1 lines of input (this stops any divide by zero error). If
Stroke length depends on stroke width. You can increase length by increasing width and hide part of border by inner element.
EDIT: added pointer-events: none;
thanks to benJ.
.thin {
background: #F4FFF3;
border: 2px dashed #3FA535;
position: relative;
}
.thin:after {
content: '';
position: absolute;
left: -1px;
top: -1px;
right: -1px;
bottom: -1px;
border: 1px solid #F4FFF3;
pointer-events: none;
}
You can input json array to this function get output as string array
example Input - { "gender" : ["male", "female"] }
output - {"male", "female"}
private String[] convertToStringArray(Object array) throws Exception {
return StringUtils.stripAll(array.toString().substring(1, array.toString().length()-1).split(","));
}
IT'S WORK!!! I FINISH MY SEARCH JOURNEY!
<meta name="viewport" content="width=640px, initial-scale=.5, maximum-scale=.5" />
tested on iPhone OS6, Android 2.3.3 Emulator
i have a mobile website that has a fixed width of 640px, and i was facing the autozoom on focus to.
i was trying allot of slutions but none was working on both iPhone and Android!
now for me it's ok to disable the zoom because the website was mobile-first design!
this is where i find it: How to do viewport sizing and scaling for cross browser support?
Make another request based on response.headers.location
:
const request = function(url) {
lib.get(url, (response) => {
var body = [];
if (response.statusCode == 302) {
body = [];
request(response.headers.location);
} else {
response.on("data", /*...*/);
response.on("end", /*...*/);
};
} ).on("error", /*...*/);
};
request(url);
The other answers are great and contain more detail if you want/need them.
In addition to those, I would like to add a TL;DR:
@RunWith(MockitoJUnitRunner.class)
@Rule public MockitoRule rule = MockitoJUnit.rule();
@Before public void initMocks() {
MockitoAnnotations.initMocks(this);
}
X x = mock(X.class)
(1) and (2) and (3) are mutually exclusive.
(4) can be used in combination with the others.
Here's a way to do this as a JQuery plugin (in case you want to re-use the functionality):
$.fn.onEnterKey =
function( closure ) {
$(this).keypress(
function( event ) {
var code = event.keyCode ? event.keyCode : event.which;
if (code == 13) {
closure();
return false;
}
} );
}
Now if you want to decorate an <input>
element with this type of functionality it's as simple as this:
$('#your-input-id').onEnterKey(
function() {
// Do stuff here
} );
In laravel 5.3, you should override the default showRegistrationForm()
by including the code below into the RegisterController.php
file in app\Http\Controllers\Auth
/**
* Show the application registration form.
*
* @return \Illuminate\Http\Response
*/
public function showRegistrationForm()
{
//return view('auth.register');
abort(404); //this will throw a page not found exception
}
since you don't want to allow registration, it's better to just throw 404 error
so the intruder knows he is lost. And when you are ready for registraation in your app, uncomment //return view('auth.register');
then comment abort(404);
\\\\\\\\\\\\\\\\\\\\JUST AN FYI///////////////////////////////
If you need to use multiple authentication like create auth for users, members, students, admin, etc. then i advise you checkout this hesto/multi-auth its an awesome package for unlimited auths in L5 apps.
You can read more abouth the Auth methodology and its associated file in this writeup.
I'm using windows and having two jdk 1.8 and 14 version something ...
Faced same issue and after some debugging find the solution.
And it solved
Insert a new verse after the given verse in your stanza:
sed -i '/^lorem ipsum dolor sit amet$/ s:$:\nconsectetur adipiscing elit:' FILE
I have implemented algorithm that memorizes all computed powers and then uses them when need. So for example x^13 is equal to (x^2)^2^2 * x^2^2 * x where x^2^2 it taken from the table instead of computing it once again. This is basically implementation of @Pramod answer (but in C#). The number of multiplication needed is Ceil(Log n)
public static int Power(int base, int exp)
{
int tab[] = new int[exp + 1];
tab[0] = 1;
tab[1] = base;
return Power(base, exp, tab);
}
public static int Power(int base, int exp, int tab[])
{
if(exp == 0) return 1;
if(exp == 1) return base;
int i = 1;
while(i < exp/2)
{
if(tab[2 * i] <= 0)
tab[2 * i] = tab[i] * tab[i];
i = i << 1;
}
if(exp <= i)
return tab[i];
else return tab[i] * Power(base, exp - i, tab);
}
Which app server are you using? Each one puts its logging config in a different place, though most nowadays use Commons-Logging as a wrapper around either Log4J or java.util.logging.
Using Tomcat as an example, this document explains your options for configuring logging using either option. In either case you need to find or create a config file that defines the log level for each package and each place the logging system will output log info (typically console, file, or db).
In the case of log4j this would be the log4j.properties file, and if you follow the directions in the link above your file will start out looking like:
log4j.rootLogger=DEBUG, R
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=${catalina.home}/logs/tomcat.log
log4j.appender.R.MaxFileSize=10MB
log4j.appender.R.MaxBackupIndex=10
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
Simplest would be to change the line:
log4j.rootLogger=DEBUG, R
To something like:
log4j.rootLogger=WARN, R
But if you still want your own DEBUG level output from your own classes add a line that says:
log4j.category.com.mypackage=DEBUG
Reading up a bit on Log4J and Commons-Logging will help you understand all this.
In BBEdit works this (ex.: changing the ID values to lowercase):
Search any value: <a id="(?P<x>.*?)"></a>
Replace with the same in lowercase: <a id="\L\P<x>\E"></a>
Was: <a id="VALUE"></a>
Became: <a id="value"></a>
As my question was marked as duplicate of this one, I think it's O.K. to post why NOT omitting closing tag ?>
can be for some reasons desired.
<?php ... ?>
) PHP source is valid SGML document, which can be parsed and processed without problems with SGML parser. With additional restrictions it can be valid XML/XHTML as well. Nothing prevents you from writing valid XML/HTML/SGML code. PHP documentation is aware of this. Excerpt:
Note: Also note that if you are embedding PHP within XML or XHTML you will need to use the < ?php ?> tags to remain compliant with standards.
Of course PHP syntax is not strict SGML/XML/HTML and you create a document, which is not SGML/XML/HTML, just like you can turn HTML into XHTML to be XML compliant or not.
At some point you may want to concatenate sources. This will be not as easy as simply doing cat source1.php source2.php
if you have inconsistency introduced by omitting closing ?>
tags.
Without ?>
it's harder to tell if document was left in PHP escape mode or PHP ignore mode (PI tag <?php
may have been opened or not). Life is easier if you consistently leave your documents in PHP ignore mode. It's just like work with well formatted HTML documents compared to documents with unclosed, badly nested tags etc.
It seems that some editors like Dreamweaver may have problems with PI left open [1].
For thoroughness, I came across another solution which was part of the functionality introduced in version 1.4.3 of the jQuery click event handler.
It allows you to pass a data map to the event object that automatically gets fed back to the event handler function by jQuery as the first parameter. The data map would be handed to the .click()
function as the first parameter, followed by the event handler function.
Here's some code to illustrate what I mean:
// say your selector and click handler looks something like this...
$("some selector").click({param1: "Hello", param2: "World"}, cool_function);
// in your function, just grab the event object and go crazy...
function cool_function(event){
alert(event.data.param1);
alert(event.data.param2);
}
I know it's late in the game for this question, but the previous answers led me to this solution, so I hope it helps someone sometime!
Of the top of my head, can you try to use the 'q' operator for the string literal
something like
insert all
into domo_queries values (q'[select
substr(to_char(max_data),1,4) as year,
substr(to_char(max_data),5,6) as month,
max_data
from dss_fin_user.acq_dashboard_src_load_success
where source = 'CHQ PeopleSoft FS']')
select * from dual;
Note that the single quotes of your predicate are not escaped, and the string sits between q'[...]'.
I compare strings using =
and not <>
. I've found out that in this context =
seems to work in more reasonable fashion than <>
. I have specified that two empty (or NULL) strings are equal. The real implementation returns PL/SQL boolean, but here I changed that to pls_integer (0 is false and 1 is true) to be able easily demonstrate the function.
create or replace function is_equal(a in varchar2, b in varchar2)
return pls_integer as
begin
if a is null and b is null then
return 1;
end if;
if a = b then
return 1;
end if;
return 0;
end;
/
show errors
begin
/* Prints 0 */
dbms_output.put_line(is_equal('AAA', 'BBB'));
dbms_output.put_line(is_equal('AAA', null));
dbms_output.put_line(is_equal(null, 'BBB'));
dbms_output.put_line(is_equal('AAA', ''));
dbms_output.put_line(is_equal('', 'BBB'));
/* Prints 1 */
dbms_output.put_line(is_equal(null, null));
dbms_output.put_line(is_equal(null, ''));
dbms_output.put_line(is_equal('', ''));
dbms_output.put_line(is_equal('AAA', 'AAA'));
end;
/
I am using remotedebug-ios-webkit-adapter, works well for me with IOS and debugger open in Chrome on Windows 10.
Will be glad if it helps some one Link
First, we need GOPATH
The $GOPATH
is a folder (or set of folders) specified by its environment variable. We must notice that this is not the $GOROOT
directory where Go is installed.
export GOPATH=$HOME/gocode
export PATH=$PATH:$GOPATH/bin
We used ~/gocode
path in our computer to store the source of our application and its dependencies. The GOPATH
directory will also store the binaries of their packages.
Then check Go env
You system must have $GOPATH
and $GOROOT
, below is my Env:
GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/elpsstu/gocode"
GORACE=""
GOROOT="/home/pravin/go"
GOTOOLDIR="/home/pravin/go/pkg/tool/linux_amd64"
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"
Now, you run download go package:
go get [-d] [-f] [-fix] [-t] [-u] [build flags] [packages]
Get downloads and installs the packages named by the import paths, along with their dependencies. For more details you can look here.
I did this for an array of objects. Its basically creating new keys in the same array and unsetting the old keys.
public function transform($key, $results)
{
foreach($results as $k=>$result)
{
if( property_exists($result, $key) )
{
$results[$result->$key] = $result;
unset($results[$k]);
}
}
return $results;
}
Note: The first() method doesn't throw an exception as described in the original question. If you're getting this kind of exception, there is another error in your code.
The correct way to user first() and check for a result:
$user = User::where('mobile', Input::get('mobile'))->first(); // model or null
if (!$user) {
// Do stuff if it doesn't exist.
}
Other techniques (not recommended, unnecessary overhead):
$user = User::where('mobile', Input::get('mobile'))->get();
if (!$user->isEmpty()){
$firstUser = $user->first()
}
or
try {
$user = User::where('mobile', Input::get('mobile'))->firstOrFail();
// Do stuff when user exists.
} catch (ErrorException $e) {
// Do stuff if it doesn't exist.
}
or
// Use either one of the below.
$users = User::where('mobile', Input::get('mobile'))->get(); //Collection
if (count($users)){
// Use the collection, to get the first item use $users->first().
// Use the model if you used ->first();
}
Each one is a different way to get your required result.
You can use:
File.WriteAllBytes("Foo.txt", arrBytes); // Requires System.IO
If you have an enumerable and not an array, you can use:
File.WriteAllBytes("Foo.txt", arrBytes.ToArray()); // Requires System.Linq
Changing Tomcat config wont effect all JVM instances to get theses settings. This is not how it works, the setting will be used only to launch JVMs used by Tomcat, not started in the shell.
Look here for permanently changing the heap size.
Weird, your code seems to work for me:
import java.util.Arrays;
public class Test
{
public static void main(String[] args)
{
// args is the list of guests
Arrays.sort(args);
for(int i = 0; i < args.length; i++)
System.out.println(args[i]);
}
}
I ran that code using "java Test Bobby Joe Angel" and here is the output:
$ java Test Bobby Joe Angel
Angel
Bobby
Joe
Using React Hooks also don't forget to set the initial value.
I was using <input type='datetime-local' value={eventStart} />
and initial eventStart
was like
const [eventStart, setEventStart] = useState();
instead
const [eventStart, setEventStart] = useState('');
.
The empty string in parentheses is difference.
Also, if you reset form after submit like i do, again you need to set it to empty string, not just to empty parentheses.
This is just my small contribution to this topic, maybe it will help someone.
Ok, so this was a bit harder than I though:
def print_matrix(list_of_list):
number_width = len(str(max([max(i) for i in list_of_list])))
cols = max(map(len, list_of_list))
output = '+'+('-'*(number_width+2)+'+')*cols + '\n'
for row in list_of_list:
for column in row:
output += '|' + ' {:^{width}d} '.format(column, width = number_width)
output+='|\n+'+('-'*(number_width+2)+'+')*cols + '\n'
return output
This should work for variable number of rows, columns and number of digits (for numbers)
data = [[1,2,30],
[4,23125,6],
[7,8,999],
]
print print_matrix(data)
>>>>+-------+-------+-------+
| 1 | 2 | 30 |
+-------+-------+-------+
| 4 | 23125 | 6 |
+-------+-------+-------+
| 7 | 8 | 999 |
+-------+-------+-------+
From this MSDN article:
There is some overhead associated with creating a StringBuilder object, both in time and memory. On a machine with fast memory, a StringBuilder becomes worthwhile if you're doing about five operations. As a rule of thumb, I would say 10 or more string operations is a justification for the overhead on any machine, even a slower one.
So if you trust MSDN go with StringBuilder if you have to do more than 10 strings operations/concatenations - otherwise simple string concat with '+' is fine.
To do this you need a JDBC Connection and/or driver that supports logging the sql at a low level.
Take a look at log4jdbc
I arrived here trying to install Appium. Adding my answer in case other folks land here for the same issue.
appium-doctor --ios
... bunch of stuff...
WARN AppiumDoctor ? Error running xcrun simctl
... bunch of stuff...
info AppiumDoctor ### Manual Fixes Needed ###
info AppiumDoctor The configuration cannot be automatically fixed, please do the following first:
WARN AppiumDoctor ? Manually install Xcode, and make sure 'xcode-select -p' command shows proper path like '/Applications/Xcode.app/Contents/Developer'
In my case
xcode-select -p
/Library/Developer/CommandLineTools
which appeared wrong...but I knew I had recently updated Xcode and the command line tools
so...
sudo xcode-select -r (sudo required)
then...
xcode-select -p
/Applications/Xcode.app/Contents/Developer
After this, no warning. Appium-doctor returned clean.
Another solution with .loc:
df = pd.DataFrame({'col': ['a', 0]})
df.loc[df.index, 'col'] = 'string' + df['col'].astype(str)
This is not as quick as solutions above (>1ms per loop slower) but may be useful in case you need conditional change, like:
mask = (df['col'] == 0)
df.loc[mask, 'col'] = 'string' + df['col'].astype(str)
In my case I did it as below:
<input #fileInput hidden (change)="uploadFile($event.target.files)" type="file" />
<button mat-button color="warn" (click)="fileInput.value=''; fileInput.click()"> Upload File</button>
I am resetting it using #fileInput in HTML rather than creating a ViewChild in component.ts .
Whenever the "Upload File" button is being clicked, first it resets the #fileInput and then triggers #fileInput.click()
function.
If any separate button needed to reset then on click #fileInput.value=''
can be executed.
How about:
d = d.applymap(lambda x: np.nan if isinstance(x, basestring) and x.isspace() else x)
The applymap
function applies a function to every cell of the dataframe.
This approach is not correct beacuse of Google Server Overload. For more informations see https://gis.stackexchange.com/questions/15052/how-to-avoid-google-map-geocode-limit#answer-15365
By the way, if you wish to proceed anyway, here you can find a code that let you load multiple markers ajax sourced on google maps avoiding OVER_QUERY_LIMIT error.
I've tested on my onw server and it works!:
var lost_addresses = [];
geocode_count = 0;
resNumber = 0;
map = new GMaps({
div: '#gmap_marker',
lat: 43.921493,
lng: 12.337646,
});
function loadMarkerTimeout(timeout) {
setTimeout(loadMarker, timeout)
}
function loadMarker() {
map.setZoom(6);
$.ajax({
url: [Insert here your URL] ,
type:'POST',
data: {
"action": "loadMarker"
},
success:function(result){
/***************************
* Assuming your ajax call
* return something like:
* array(
* 'status' => 'success',
* 'results'=> $resultsArray
* );
**************************/
var res=JSON.parse(result);
if(res.status == 'success') {
resNumber = res.results.length;
//Call the geoCoder function
getGeoCodeFor(map, res.results);
}
}//success
});//ajax
};//loadMarker()
$().ready(function(e) {
loadMarker();
});
//Geocoder function
function getGeoCodeFor(maps, addresses) {
$.each(addresses, function(i,e){
GMaps.geocode({
address: e.address,
callback: function(results, status) {
geocode_count++;
if (status == 'OK') {
//if the element is alreay in the array, remove it
lost_addresses = jQuery.grep(lost_addresses, function(value) {
return value != e;
});
latlng = results[0].geometry.location;
map.addMarker({
lat: latlng.lat(),
lng: latlng.lng(),
title: 'MyNewMarker',
});//addMarker
} else if (status == 'ZERO_RESULTS') {
//alert('Sorry, no results found');
} else if(status == 'OVER_QUERY_LIMIT') {
//if the element is not in the losts_addresses array, add it!
if( jQuery.inArray(e,lost_addresses) == -1) {
lost_addresses.push(e);
}
}
if(geocode_count == addresses.length) {
//set counter == 0 so it wont's stop next round
geocode_count = 0;
setTimeout(function() {
getGeoCodeFor(maps, lost_addresses);
}, 2500);
}
}//callback
});//GeoCode
});//each
};//getGeoCodeFor()
Example:
map = new GMaps({_x000D_
div: '#gmap_marker',_x000D_
lat: 43.921493,_x000D_
lng: 12.337646,_x000D_
});_x000D_
_x000D_
var jsonData = { _x000D_
"status":"success",_x000D_
"results":[ _x000D_
{ _x000D_
"customerId":1,_x000D_
"address":"Via Italia 43, Milano (MI)",_x000D_
"customerName":"MyAwesomeCustomer1"_x000D_
},_x000D_
{ _x000D_
"customerId":2,_x000D_
"address":"Via Roma 10, Roma (RM)",_x000D_
"customerName":"MyAwesomeCustomer2"_x000D_
}_x000D_
]_x000D_
};_x000D_
_x000D_
function loadMarkerTimeout(timeout) {_x000D_
setTimeout(loadMarker, timeout)_x000D_
}_x000D_
_x000D_
function loadMarker() { _x000D_
map.setZoom(6);_x000D_
_x000D_
$.ajax({_x000D_
url: '/echo/html/',_x000D_
type: "POST",_x000D_
data: jsonData,_x000D_
cache: false,_x000D_
success:function(result){_x000D_
_x000D_
var res=JSON.parse(result);_x000D_
if(res.status == 'success') {_x000D_
resNumber = res.results.length;_x000D_
//Call the geoCoder function_x000D_
getGeoCodeFor(map, res.results);_x000D_
}_x000D_
}//success_x000D_
});//ajax_x000D_
_x000D_
};//loadMarker()_x000D_
_x000D_
$().ready(function(e) {_x000D_
loadMarker();_x000D_
});_x000D_
_x000D_
//Geocoder function_x000D_
function getGeoCodeFor(maps, addresses) {_x000D_
$.each(addresses, function(i,e){ _x000D_
GMaps.geocode({_x000D_
address: e.address,_x000D_
callback: function(results, status) {_x000D_
geocode_count++; _x000D_
_x000D_
console.log('Id: '+e.customerId+' | Status: '+status);_x000D_
_x000D_
if (status == 'OK') { _x000D_
_x000D_
//if the element is alreay in the array, remove it_x000D_
lost_addresses = jQuery.grep(lost_addresses, function(value) {_x000D_
return value != e;_x000D_
});_x000D_
_x000D_
_x000D_
latlng = results[0].geometry.location;_x000D_
map.addMarker({_x000D_
lat: latlng.lat(),_x000D_
lng: latlng.lng(),_x000D_
title: e.customerName,_x000D_
});//addMarker_x000D_
} else if (status == 'ZERO_RESULTS') {_x000D_
//alert('Sorry, no results found');_x000D_
} else if(status == 'OVER_QUERY_LIMIT') {_x000D_
_x000D_
//if the element is not in the losts_addresses array, add it! _x000D_
if( jQuery.inArray(e,lost_addresses) == -1) {_x000D_
lost_addresses.push(e);_x000D_
}_x000D_
_x000D_
} _x000D_
_x000D_
if(geocode_count == addresses.length) {_x000D_
//set counter == 0 so it wont's stop next round_x000D_
geocode_count = 0;_x000D_
_x000D_
setTimeout(function() {_x000D_
getGeoCodeFor(maps, lost_addresses);_x000D_
}, 2500);_x000D_
}_x000D_
}//callback_x000D_
});//GeoCode_x000D_
});//each_x000D_
};//getGeoCodeFor()
_x000D_
#gmap_marker {_x000D_
min-height:250px;_x000D_
height:100%;_x000D_
width:100%;_x000D_
position: relative; _x000D_
overflow: hidden;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="http://maps.google.com/maps/api/js" type="text/javascript"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/gmaps.js/0.4.24/gmaps.min.js" type="text/javascript"></script>_x000D_
_x000D_
_x000D_
<div id="gmap_marker"></div> <!-- /#gmap_marker -->
_x000D_
A small variation on the accepted answer.
toFixed(2)
returns a string, and you will always get two decimal places. These might be zeros. If you would like to suppress final zero(s), simply do this:
var discount = + ((price / listprice).toFixed(2));
Edited:
I've just discovered what seems to be a bug in Firefox 35.0.1, which means that the above may give NaN with some values.
I've changed my code to
var discount = Math.round(price / listprice * 100) / 100;
This gives a number with up to two decimal places. If you wanted three, you would multiply and divide by 1000, and so on.
The OP wants two decimal places always, but if toFixed() is broken in Firefox it needs fixing first.
See https://bugzilla.mozilla.org/show_bug.cgi?id=1134388
By default, Homebrew installs packages to your /usr/local. Macport commands require sudo to install and upgrade (similar to apt-get in Ubuntu).
For more detail:
This site suggests using Hombrew: http://deephill.com/macports-vs-homebrew/
whereas this site lists the advantages of using Macports: http://arstechnica.com/civis/viewtopic.php?f=19&t=1207907
I also switched from Ubuntu recently, and I enjoy using homebrew (it's simple and easy to use!), but if you feel attached to using sudo, Macports might be the better way to go!
If you are using Github.com, go to "Pull requests", click on the relevant pull request, and then click on the "command line instructions" link:
You can update the existing package-lock.json file instead of creating a new one. Just change the version number to a different one.
{ "name": "theme","version": "1.0.1", "description": "theme description"}
You may use cdecl utility or its online versions, like https://cdecl.org/
For example:
void (* x)(int (*[])());
is a
declare x as pointer to function (array of pointer to function returning int) returning void
I would also like to recommend vscode extension Peep, which allows you to toggle hide on the excluded files in your projects settings.json.
Hit F1 for vscode command line (command palette), then
ext install [enter] peep [enter]
You can bind "extension.peepToggle" to a key like Ctrl+Shift+P (same as F1 by default) for easy toggling. Hit Ctrl+K Ctrl+S for key bindings, enter peep
, select Peep Toggle and add your binding.
With underscorejs
var a1 = [1,2,3];
var a2 = [1,2];
_.every(a1, function(e){ return _.include(a2, e); } ); //=> false
_.every(a2, function(e){ return _.include(a1, e); } ); //=> true
I found a detailed solution here: Install OpenSSL Manually On Linux
From the blog post...:
Steps to download, compile, and install are as follows (I'm installing version 1.0.1g below; please replace "1.0.1g" with your version number):
Step – 1 : Downloading OpenSSL:
Run the command as below :
$ wget http://www.openssl.org/source/openssl-1.0.1g.tar.gz
Also, download the MD5 hash to verify the integrity of the downloaded file for just varifacation purpose. In the same folder where you have downloaded the OpenSSL file from the website :
$ wget http://www.openssl.org/source/openssl-1.0.1g.tar.gz.md5
$ md5sum openssl-1.0.1g.tar.gz
$ cat openssl-1.0.1g.tar.gz.md5
Step – 2 : Extract files from the downloaded package:
$ tar -xvzf openssl-1.0.1g.tar.gz
Now, enter the directory where the package is extracted like here is openssl-1.0.1g
$ cd openssl-1.0.1g
Step – 3 : Configuration OpenSSL
Run below command with optional condition to set prefix and directory where you want to copy files and folder.
$ ./config --prefix=/usr/local/openssl --openssldir=/usr/local/openssl
You can replace “/usr/local/openssl” with the directory path where you want to copy the files and folders. But make sure while doing this steps check for any error message on terminal.
Step – 4 : Compiling OpenSSL
To compile openssl you will need to run 2 command : make, make install as below :
$ make
Note: check for any error message for verification purpose.
Step -5 : Installing OpenSSL:
$ sudo make install
Or without sudo,
$ make install
That’s it. OpenSSL has been successfully installed. You can run the version command to see if it worked or not as below :
$ /usr/local/openssl/bin/openssl version
OpenSSL 1.0.1g 7 Apr 2014
These two ways worked for me:
To get IP address of your interface eth0. Replace eth0 in the below example with your interface name.
ifconfig eth0 | grep -w "inet" | tr -s " " | cut -f3 -d" "
Using hostname: This will give you the inet i.e. IPAddress of your etho. using -I will give you inet value of all the interfaces whereever this value is present.
hostname -i
Include this where the imports are on top:
import android.view.WindowManager;
Add this code on OnCreate part:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
Here's a Boolean thing:
if (not suffix == "flac" ) or (not suffix == "cue" ): # WRONG! FAILS
print filename + ' is not a flac or cue file'
but
if not (suffix == "flac" or suffix == "cue" ): # CORRECT!
print filename + ' is not a flac or cue file'
(not a) or (not b) == not ( a and b )
,
is false only if a and b are both true
not (a or b)
is true only if a and be are both false.
Two possible options (there might be more of course):
You can use the crypto/rand
package that supports reading random byte arrays (from /dev/urandom) and is geared towards cryptographic random generation. see http://golang.org/pkg/crypto/rand/#example_Read . It might be slower than normal pseudo-random number generation though.
Take a random number and hash it using md5 or something like this.
margin:0 auto;
0
is for top-bottom and auto
for left-right. It means that left and right margin will take auto margin according to the width of the element and the width of the container.
Generally if you want to put any element at center position then margin:auto
works perfectly. But it only works in block elements.
First you need to set a reference (Menu: Tools->References) to the Microsoft Excel Object Library then you can access all Excel Objects.
After you added the Reference you have full access to all Excel Objects. You need to add Excel in front of everything for example:
Dim xlApp as Excel.Application
Let's say you added an Excel Workbook Object in your Form and named it xLObject.
Here is how you Access a Sheet of this Object and change a Range
Dim sheet As Excel.Worksheet
Set sheet = xlObject.Object.Sheets(1)
sheet.Range("A1") = "Hello World"
(I copied the above from my answer to this question)
Another way to use Excel in Access is to start Excel through a Access Module (the way shahkalpesh described it in his answer)
Might not be relevant for everyone but this little detail was causing mine not to work:
Change div from this:
<div class="map">
To this:
<div id="map">
Thought i should add here, that if you want to access rows or columns to loop through them, you do this:
import pandas as pd
# open the file
xlsx = pd.ExcelFile("PATH\FileName.xlsx")
# get the first sheet as an object
sheet1 = xlsx.parse(0)
# get the first column as a list you can loop through
# where the is 0 in the code below change to the row or column number you want
column = sheet1.icol(0).real
# get the first row as a list you can loop through
row = sheet1.irow(0).real
Edit:
The methods icol(i)
and irow(i)
are deprecated now. You can use sheet1.iloc[:,i]
to get the i-th col and sheet1.iloc[i,:]
to get the i-th row.
You did not add #
before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.
See documentation: http://api.jquery.com/category/selectors/
its your friend.
Try this:
It seems that id: $("#Shareitem").val()
is wrong if you want to pass the value of
<input type="hidden" name="id" value="" id="id">
you need to change this line:
id: $("#Shareitem").val()
by
id: $("#id").val()
All together:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function(){
$("#Shareitem").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "/imball-reagens/public/shareitem",
data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
success:function(result){
$("#sharelink").html(result);
}});
});
});
</script>
In MySql, you can get 10 rows starting from row 20 using:
SELECT * FROM Reflow
WHERE ReflowProcessID = somenumber
ORDER BY ID DESC
LIMIT 10 OFFSET 20 --Equivalent to LIMIT 20, 10
In addition to using pure threads or the Celery queue (note that flask-celery is no longer required), you could also have a look at flask-apscheduler:
https://github.com/viniciuschiele/flask-apscheduler
A simple example copied from https://github.com/viniciuschiele/flask-apscheduler/blob/master/examples/jobs.py:
from flask import Flask
from flask_apscheduler import APScheduler
class Config(object):
JOBS = [
{
'id': 'job1',
'func': 'jobs:job1',
'args': (1, 2),
'trigger': 'interval',
'seconds': 10
}
]
SCHEDULER_API_ENABLED = True
def job1(a, b):
print(str(a) + ' ' + str(b))
if __name__ == '__main__':
app = Flask(__name__)
app.config.from_object(Config())
scheduler = APScheduler()
# it is also possible to enable the API directly
# scheduler.api_enabled = True
scheduler.init_app(app)
scheduler.start()
app.run()
I can't add comments to Vladimir's solution, but I think that this is more efficient also when your initial numbers could be also below 10.
This is my proposal:
int temp = test;
ArrayList<Integer> array = new ArrayList<Integer>();
do{
array.add(temp % 10);
temp /= 10;
} while (temp > 1);
Remember to reverse the array.
Assuming the application you are attempting to run in the background is CLI based, you can try calling the scheduled jobs using Hidden Start
Also see: http://www.howtogeek.com/howto/windows/hide-flashing-command-line-and-batch-file-windows-on-startup/
To enable zoom controls in a WebView, add the following line:
webView.getSettings().setBuiltInZoomControls(true);
With this line of code, you get the zoom enabled in your WebView, if you want to remove the zoom in and zoom out buttons provided, add the following line of code:
webView.getSettings().setDisplayZoomControls(false);
You actually invoked undefined behaviour.
Returning the address of a temporary works, but as temporaries are destroyed at the end of a function the results of accessing them will be undefined.
So you did not modify a
but rather the memory location where a
once was. This difference is very similar to the difference between crashing and not crashing.
From Zvon.org XSLT Reference:
XPath function: boolean contains (string, string)
Hope this helps.
You can try bellow code
<select onchange="myfunction($(this).val())" id="myId">
</select>
I had this issue occurring with mailto:
and tel:
links inside an iframe (in Chrome, not a webview). Clicking the links would show the grey "page not found" page and inspecting the page showed it had a ERR_UNKNOWN_URL_SCHEME error.
Adding target="_blank"
, as suggested by this discussion of the issue fixed the problem for me.
I had the same problem as you, it looks like you used the tutorial from http://www.piwai.info/chatheads-basics like I did. The problem is that you cannot reliably pass the current activity to the popup window, because you have no control over the current activity. It looks like there might be a unreliable way to get the current activity, but I don't recommend that.
The way I fixed it for my app was to not use the popup window, but instead make my own through the window manager.
private void showCustomPopupMenu()
{
windowManager2 = (WindowManager)getSystemService(WINDOW_SERVICE);
LayoutInflater layoutInflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view=layoutInflater.inflate(R.layout.xxact_copy_popupmenu, null);
params=new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity=Gravity.CENTER|Gravity.CENTER;
params.x=0;
params.y=0;
windowManager2.addView(view, params);
}
If you want this to look like a popup window, just add a transparent gray view as the background and add a onClickListener to it to remove the view from the windowManager object.
I know this isn't as convenient as a popup, but from my experience, it is the most reliable way.
and don't forget to add permission in your manifest file
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
Anders Lindahl's answer is correct, but it should be noted that if you are redirecting stdout to a file and want to redirect stderr as well then you MUST ensure that 2>&1
is specified AFTER the 1>
redirect, otherwise it will not work.
REM *** WARNING: THIS WILL NOT REDIRECT STDERR TO STDOUT ****
dir 2>&1 > a.txt
even more cool, you can pass a variable count of parameters to a function like this:
function sendmail(...$users){
foreach($users as $user){
}
}
sendmail('user1','user2','user3');
check up blur()
:
$('#textarea').blur()
source: http://api.jquery.com/blur/
If anybody has this error using phonegap or cordova with the cordova-plugin-fcm-ng or cordova-plugin-fcm plugin, the solution that worked for me is creating the extra config file for gradle "build-extras.gradle" in the \platforms\android\app folder, and putting the following lines in it
configurations.all {
resolutionStrategy {
force 'com.google.firebase:firebase-messaging:18.0.0'
force 'com.google.firebase:firebase-core:16.0.8'
}
}
I found this solution reading this page https://github.com/facebook/react-native/issues/25371, in particular comment of shreyakupadhyay on 30/07/19 and consulting https://developers.google.com/android/guides/releases#may_07_2019 about last libraries version.
Use System.currentTimeMillis() or System.nanoTime().
The string literal is pased according to the current dateformat setting, see SET DATEFORMAT
. One format which will always work is the '20090525' one.
Now, of course, you need to define 'does not work'. No records gets updated? Perhaps the Id=1
doesn't match any record...
If it says 'One record changed' then perhaps you need to show us how you verify...
First represent the epoch of the millisecond time as a date (usually 1/1/1970), then add your millisecond time divided by the number of milliseconds in a day (86400000):
=DATE(1970,1,1)+(A1/86400000)
If your cell is properly formatted, you should see a human-readable date/time.
WordPress does not execute PHP in post/page content by default unless it has a shortcode.
The quickest and easiest way to do this is to use a plugin that allows you to run PHP embedded in post content.
There are two other "quick and easy" ways to accomplish it without a plugin:
Make it a shortcode (put it in functions.php
and have it echo the country name) which is very easy - see here: Shortcode API at WP Codex
Put it in a template file - make a custom template for that page based on your default page template and add the PHP into the template file rather than the post content: Custom Page Templates
There's no fixed time for retransmission. Simple implementations estimate the RTT (round-trip-time) and if no ACK to send data has been received in 2x that time then they re-send.
They then double the wait-time and re-send once more if again there is no reply. Rinse. Repeat.
More sophisticated systems make better estimates of how long it should take for the ACK as well as guesses about exactly which data has been lost.
The bottom-line is that there is no hard-and-fast rule about exactly when to retransmit. It's up to the implementation. All retransmissions are triggered solely by the sender based on lack of response from the receiver.
TCP never drops data so no, there is no way to indicate a server should forget about some segment.
Here is a simple way without stragg or creating a function.
create table countries ( country_name varchar2 (100));
insert into countries values ('Albania');
insert into countries values ('Andorra');
insert into countries values ('Antigua');
SELECT SUBSTR (SYS_CONNECT_BY_PATH (country_name , ','), 2) csv
FROM (SELECT country_name , ROW_NUMBER () OVER (ORDER BY country_name ) rn,
COUNT (*) OVER () cnt
FROM countries)
WHERE rn = cnt
START WITH rn = 1
CONNECT BY rn = PRIOR rn + 1;
CSV
--------------------------
Albania,Andorra,Antigua
1 row selected.
As others have mentioned, if you are on 11g R2 or greater, you can now use listagg which is much simpler.
select listagg(country_name,', ') within group(order by country_name) csv
from countries;
CSV
--------------------------
Albania, Andorra, Antigua
1 row selected.
Some interesting alternatives:
OPTION 1
PrintStream p = System.out;
p.println("hello");
OPTION 2
PrintWriter p = new PrintWriter(System.out, true);
p.println("Hello");
<select v-model="challan.warehouse_id">
<option value="">Select Warehouse</option>
<option v-for="warehouse in warehouses" v-bind:value="warehouse.id" >
{{ warehouse.name }}
</option>
Here "challan.warehouse_id" come from "challan" object you get from:
editChallan: function() {
let that = this;
axios.post('/api/challan_list/get_challan_data', {
challan_id: that.challan_id
})
.then(function (response) {
that.challan = response.data;
})
.catch(function (error) {
that.errors = error;
});
}
You can use SUBSTRING
and CONVERT
:
SELECT stuff
FROM table
WHERE conditions
ORDER BY CONVERT(SUBSTRING(name_column, 6), SIGNED INTEGER);
Where name_column
is the column with the "name-" values. The SUBSTRING
removes everything up before the sixth character (i.e. the "name-" prefix) and then the CONVERT
converts the left over to a real integer.
UPDATE: Given the changing circumstances in the comments (i.e. the prefix can be anything), you'll have to throw a LOCATE
in the mix:
ORDER BY CONVERT(SUBSTRING(name_column, LOCATE('-', name_column) + 1), SIGNED INTEGER);
This of course assumes that the non-numeric prefix doesn't have any hyphens in it but the relevant comment says that:
name
can be any sequence of letters
so that should be a safe assumption.
From HTML 4 spec, which should be consistent across almost all browsers:
http://www.w3.org/TR/html401/interact/forms.html#checkbox
Checkboxes (and radio buttons) are on/off switches that may be toggled by the user. A switch is "on" when the control element's checked attribute is set. When a form is submitted, only "on" checkbox controls can become successful.
Successful is defined as follows:
A successful control is "valid" for submission. Every successful control has its control name paired with its current value as part of the submitted form data set. A successful control must be defined within a FORM element and must have a control name.
This simplifies it a bit and it behaves as you want it.
FileWriter f = new FileWriter("../playlist/"+existingPlaylist.getText()+".txt");
try {
f.write(source);
...
} catch(...) {
} finally {
//close it here
}
Be careful of what you want to convert. JPG doesn't support alpha-transparency while PNG does. You will lose that information.
To convert, you may use the following function:
// Quality is a number between 0 (best compression) and 100 (best quality)
function png2jpg($originalFile, $outputFile, $quality) {
$image = imagecreatefrompng($originalFile);
imagejpeg($image, $outputFile, $quality);
imagedestroy($image);
}
This function uses the imagecreatefrompng()
and the imagejpeg()
functions from the GD library.
I had an ArrayList which I wanted to display in a listview. ArrayList contained elements from mysql. I overrided onRefresh method and in that method I used tablelayout.removeAllViews(); and then repeated the process for getting data again from the database. But before that make sure to clear your ArrayList or whatever data structre or else new data will get appended to the old one..
If you have more than 1 image on the page that you like to enlarge, name the id's for instance "content1", "content2", "content3", etc. Then extend the script with this, like so:
$(document).ready(function() {
$("[id^=content]").hover(function() {
$(this).addClass('transition');
}, function() {
$(this).removeClass('transition');
});
});
Edit: Change the "#content" CSS to: img[id^=content] to remain having the transition effects.
I wasn't happy with Python one-liners for HTML XPath queries, so I wrote my own. Assumes that you installed python-lxml
package or ran pip install --user lxml
:
function htmlxpath() { python -c 'for x in __import__("lxml.html").html.fromstring(__import__("sys").stdin.read()).xpath(__import__("sys").argv[1]): print(x)' $1 }
Once you have it, you can use it like in this example:
> curl -s https://slashdot.org | htmlxpath '//title/text()'
Slashdot: News for nerds, stuff that matters
You can use the shortcut -I
for tar's --use-compress-program
switch, and invoke pbzip2
for bzip2 compression on multiple cores:
tar -I pbzip2 -cf OUTPUT_FILE.tar.bz2 DIRECTORY_TO_COMPRESS/
Skype was the main cause of my problem:
This error usually occurs when you have set up Visual Studio to debug an existing web application running in IIS rather than the built in ASP.NET debug web server. IIS by default listens for web requests on port 80. In this case, another application is already listening for requests on port 80. Typically, the offending application is Skype, which by default takes over listening on ports 80 and 443 when installed. Skype is already occupy the port 80. So IIS is unable to start.
To resolve the issue follow the steps:
Skype -> Tools -> Options -> Advanced -> Connection:
Uncheck "Use port 80 and 443 as alternatives for incoming connections".
And as pointed out below perform an IIS reset once done.
first import os module in your app than with use from getpid function get pid's app and save in a file.for example :
import os
pid = os.getpid()
op = open("/var/us.pid","w")
op.write("%s" % pid)
op.close()
and create a bash file in /etc/init.d path: /etc/init.d/servername
PATHAPP="/etc/bin/userscript.py &"
PIDAPP="/var/us.pid"
case $1 in
start)
echo "starting"
$(python $PATHAPP)
;;
stop)
echo "stoping"
PID=$(cat $PIDAPP)
kill $PID
;;
esac
now , u can start and stop ur app with down command:
service servername stop service servername start
or
/etc/init.d/servername stop /etc/init.d/servername start
Put
<style type="text/css">
ul#otis {
list-style-type: none;
}
</style>
immediately before the list to test it out. Or
<ul style="list-style-type: none;">
This solution is done using boto3 and Python:
import boto3
import json
invokeLambda = boto3.client('lambda', region_name='eu-west-1')
def lambda_handler(event, context):
invokeLambda.invoke(FunctionName = 'function_name', InvocationType = 'RequestResponse', Payload = json.dumps(event))
return True
ES6 React.Component
doesn't auto bind methods to itself. You need to bind them yourself in constructor
. Like this:
constructor (props){
super(props);
this.state = {
loopActive: false,
shuffleActive: false,
};
this.onToggleLoop = this.onToggleLoop.bind(this);
}
If you have access to all servers involved, put the following in the header of the reply for the page being requested in the other domain:
PHP:
header('Access-Control-Allow-Origin: *');
For example, in Drupal's xmlrpc.php code you would do this:
function xmlrpc_server_output($xml) {
$xml = '<?xml version="1.0"?>'."\n". $xml;
header('Connection: close');
header('Content-Length: '. strlen($xml));
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/x-www-form-urlencoded');
header('Date: '. date('r'));
// $xml = str_replace("\n", " ", $xml);
echo $xml;
exit;
}
This probably creates a security problem, and you should make sure that you take the appropriate measures to verify the request.
if you get an error as Parameter 'element' implicitly has an 'any' type.Vetur(7006) in vueJs
with the error:
exportColumns.forEach(element=> {
if (element.command !== undefined) {
let d = element.command.findIndex(x => x.name === "destroy");
you can fixed it by defining thoes variables as any as follow.
corrected code:
exportColumns.forEach((element: any) => {
if (element.command !== undefined) {
let d = element.command.findIndex((x: any) => x.name === "destroy");
I am showing with an example of adding random color. You can write this way
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
var col = "rgb(" + r + "," + g + "," + b + ")";
parent.childNodes[1].style.color = col;
The property is expected as a string
More on gdoron's answer, it can also be done this way:
$(window).on("click", "#filter", function() {
alert('clicked!');
});
without the need to place them all into $(function(){...})
Well, note that the request contains binary data, so I'm not posting the request as such - instead, I've converted every non-printable-ascii character into a dot (".").
POST /cgi-bin/qtest HTTP/1.1
Host: aram
User-Agent: Mozilla/5.0 Gecko/2009042316 Firefox/3.0.10
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://aram/~martind/banner.htm
Content-Type: multipart/form-data; boundary=2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Length: 514
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile1"; filename="r.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile2"; filename="g.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile3"; filename="b.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f--
Note that every line (including the last one) is terminated by a \r\n sequence.
If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE
Edit: On the model overview it's under Physical Schemata
Screenshot:
Try something like:
$('div.toggle').hide();
$('ul.product-info li a').click(function(event) {
event.preventDefault();
$(this).next('div').slideToggle(200);
});
Here is the page about that in the jQuery documentation
We can use setTimeout
function in such cases.
console.log('primary task');
setTimeout(function() {
console.log('secondary task');
}, 0);
This will make sure that secondary task will be executed when execution of primary task is finished.
check
System.getProperty("sun.jnu.encoding")
it seems to be the same encoding as the one used in your system's command line.
This has already been answered perfectly, but since I just came to this page and did not understand immediately I am just going to add a simple but complete example.
def some_func(a_char, a_float, a_something):
print a_char
params = ['a', 3.4, None]
some_func(*params)
>> a
Go to view and press "Switch to scale mode" which will adjust the virtual screen when you adjust the application.
Your regex pattern needs to be in delimiters:
$numpattern="/^([0-9]+)$/";
Below is an complete copy of the simplified script used in my other answer. Beyond additional error checking, there is an alias which allows the user to change the name of an existing alias. The syntax is given below. If the new_alias
parameter is omitted, then the alias is removed.
ChangeAlias old_alias [new_alias]
The complete script is given below.
common.GetAlias() {
local "oldname=${1:-0}"
if [[ $oldname =~ ^[0-9]+$ && oldname+1 -lt ${#FUNCNAME[@]} ]]; then
oldname="${FUNCNAME[oldname + 1]}"
fi
name="common_${oldname#common.}"
echo "${!name:-$oldname}"
}
common.Alias() {
if [[ $# -ne 2 || -z $1 || -z $2 ]]; then
echo "$(common.GetAlias): The must be only two parameters of nonzero length" >&2
return 1;
fi
eval "alias $1='$2'"
local "f=${2##*common.}"
f="${f%%;*}"
local "v=common_$f"
f="common.$f"
if [[ -n ${!v:-} ]]; then
echo "$(common.GetAlias): $1: Function \`$f' already paired with name \`${!v}'" >&2
return 1;
fi
shopt -s expand_aliases
eval "$v=\"$1\""
}
common.ChangeAlias() {
if [[ $# -lt 1 || $# -gt 2 ]]; then
echo "usage: $(common.GetAlias) old_name [new_name]" >&2
return "1"
elif ! alias "$1" &>"/dev/null"; then
echo "$(common.GetAlias): $1: Name not found" >&2
return 1;
fi
local "s=$(alias "$1")"
s="${s#alias $1=\'}"
s="${s%\'}"
local "f=${s##*common.}"
f="${f%%;*}"
local "v=common_$f"
f="common.$f"
if [[ ${!v:-} != "$1" ]]; then
echo "$(common.GetAlias): $1: Name not paired with a function \`$f'" >&2
return 1;
elif [[ $# -gt 1 ]]; then
eval "alias $2='$s'"
eval "$v=\"$2\""
else
unset "$v"
fi
unalias "$1"
}
common.Alias exception 'common.Exception'
common.Alias throw 'common.Throw'
common.Alias try '{ if common.Try; then'
common.Alias yrt 'common.EchoExitStatus; fi; common.yrT; }'
common.Alias catch '{ while common.Catch'
common.Alias hctac 'common.hctaC -r; done; common.hctaC; }'
common.Alias finally '{ if common.Finally; then'
common.Alias yllanif 'fi; common.yllaniF; }'
common.Alias caught 'common.Caught'
common.Alias EchoExitStatus 'common.EchoExitStatus'
common.Alias EnableThrowOnError 'common.EnableThrowOnError'
common.Alias DisableThrowOnError 'common.DisableThrowOnError'
common.Alias GetStatus 'common.GetStatus'
common.Alias SetStatus 'common.SetStatus'
common.Alias GetMessage 'common.GetMessage'
common.Alias MessageCount 'common.MessageCount'
common.Alias CopyMessages 'common.CopyMessages'
common.Alias TryCatchFinally 'common.TryCatchFinally'
common.Alias DefaultErrHandler 'common.DefaultErrHandler'
common.Alias DefaultUnhandled 'common.DefaultUnhandled'
common.Alias CallStack 'common.CallStack'
common.Alias ChangeAlias 'common.ChangeAlias'
common.Alias TryCatchFinallyAlias 'common.Alias'
common.CallStack() {
local -i "i" "j" "k" "subshell=${2:-0}" "wi" "wl" "wn"
local "format= %*s %*s %-*s %s\n" "name"
eval local "lineno=('' ${BASH_LINENO[@]})"
for (( i=${1:-0},j=wi=wl=wn=0; i<${#FUNCNAME[@]}; ++i,++j )); do
name="$(common.GetAlias "$i")"
let "wi = ${#j} > wi ? wi = ${#j} : wi"
let "wl = ${#lineno[i]} > wl ? wl = ${#lineno[i]} : wl"
let "wn = ${#name} > wn ? wn = ${#name} : wn"
done
for (( i=${1:-0},j=0; i<${#FUNCNAME[@]}; ++i,++j )); do
! let "k = ${#FUNCNAME[@]} - i - 1"
name="$(common.GetAlias "$i")"
printf "$format" "$wi" "$j" "$wl" "${lineno[i]}" "$wn" "$name" "${BASH_SOURCE[i]}"
done
}
common.Echo() {
[[ $common_options != *d* ]] || echo "$@" >"$common_file"
}
common.DefaultErrHandler() {
echo "Orginal Status: $common_status"
echo "Exception Type: ERR"
}
common.Exception() {
common.TryCatchFinallyVerify || return
if [[ $# -eq 0 ]]; then
echo "$(common.GetAlias): At least one parameter is required" >&2
return "1"
elif [[ ${#1} -gt 16 || -n ${1%%[0-9]*} || 10#$1 -lt 1 || 10#$1 -gt 255 ]]; then
echo "$(common.GetAlias): $1: First parameter was not an integer between 1 and 255" >&2
return "1"
fi
let "common_status = 10#$1"
shift
common_messages=()
for message in "$@"; do
common_messages+=("$message")
done
if [[ $common_options == *c* ]]; then
echo "Call Stack:" >"$common_fifo"
common.CallStack "2" >"$common_fifo"
fi
}
common.Throw() {
common.TryCatchFinallyVerify || return
local "message"
if ! common.TryCatchFinallyExists; then
echo "$(common.GetAlias): No Try-Catch-Finally exists" >&2
return "1"
elif [[ $# -eq 0 && common_status -eq 0 ]]; then
echo "$(common.GetAlias): No previous unhandled exception" >&2
return "1"
elif [[ $# -gt 0 && ( ${#1} -gt 16 || -n ${1%%[0-9]*} || 10#$1 -lt 1 || 10#$1 -gt 255 ) ]]; then
echo "$(common.GetAlias): $1: First parameter was not an integer between 1 and 255" >&2
return "1"
fi
common.Echo -n "In Throw ?=$common_status "
common.Echo "try=$common_trySubshell subshell=$BASH_SUBSHELL #=$#"
if [[ $common_options == *k* ]]; then
common.CallStack "2" >"$common_file"
fi
if [[ $# -gt 0 ]]; then
let "common_status = 10#$1"
shift
for message in "$@"; do
echo "$message" >"$common_fifo"
done
if [[ $common_options == *c* ]]; then
echo "Call Stack:" >"$common_fifo"
common.CallStack "2" >"$common_fifo"
fi
elif [[ ${#common_messages[@]} -gt 0 ]]; then
for message in "${common_messages[@]}"; do
echo "$message" >"$common_fifo"
done
fi
chmod "0400" "$common_fifo"
common.Echo "Still in Throw $=$common_status subshell=$BASH_SUBSHELL #=$# -=$-"
exit "$common_status"
}
common.ErrHandler() {
common_status=$?
trap ERR
common.Echo -n "In ErrHandler ?=$common_status debug=$common_options "
common.Echo "try=$common_trySubshell subshell=$BASH_SUBSHELL order=$common_order"
if [[ -w "$common_fifo" ]]; then
if [[ $common_options != *e* ]]; then
common.Echo "ErrHandler is ignoring"
common_status="0"
return "$common_status" # value is ignored
fi
if [[ $common_options == *k* ]]; then
common.CallStack "2" >"$common_file"
fi
common.Echo "Calling ${common_errHandler:-}"
eval "${common_errHandler:-} \"${BASH_LINENO[0]}\" \"${BASH_SOURCE[1]}\" \"${FUNCNAME[1]}\" >$common_fifo <$common_fifo"
if [[ $common_options == *c* ]]; then
echo "Call Stack:" >"$common_fifo"
common.CallStack "2" >"$common_fifo"
fi
chmod "0400" "$common_fifo"
fi
common.Echo "Still in ErrHandler $=$common_status subshell=$BASH_SUBSHELL -=$-"
if [[ common_trySubshell -eq BASH_SUBSHELL ]]; then
return "$common_status" # value is ignored
else
exit "$common_status"
fi
}
common.Token() {
local "name"
case $1 in
b) name="before";;
t) name="$common_Try";;
y) name="$common_yrT";;
c) name="$common_Catch";;
h) name="$common_hctaC";;
f) name="$common_yllaniF";;
l) name="$common_Finally";;
*) name="unknown";;
esac
echo "$name"
}
common.TryCatchFinallyNext() {
common.ShellInit
local "previous=$common_order" "errmsg"
common_order="$2"
if [[ $previous != $1 ]]; then
errmsg="${BASH_SOURCE[2]}: line ${BASH_LINENO[1]}: syntax error_near unexpected token \`$(common.Token "$2")'"
echo "$errmsg" >&2
[[ /dev/fd/2 -ef $common_file ]] || echo "$errmsg" >"$common_file"
kill -s INT 0
return "1"
fi
}
common.ShellInit() {
if [[ common_initSubshell -ne BASH_SUBSHELL ]]; then
common_initSubshell="$BASH_SUBSHELL"
common_order="b"
fi
}
common.Try() {
common.TryCatchFinallyVerify || return
common.TryCatchFinallyNext "[byhl]" "t" || return
common_status="0"
common_subshell="$common_trySubshell"
common_trySubshell="$BASH_SUBSHELL"
common_messages=()
common.Echo "-------------> Setting try=$common_trySubshell at subshell=$BASH_SUBSHELL"
}
common.yrT() {
local "status=$?"
common.TryCatchFinallyVerify || return
common.TryCatchFinallyNext "[t]" "y" || return
common.Echo -n "Entered yrT ?=$status status=$common_status "
common.Echo "try=$common_trySubshell subshell=$BASH_SUBSHELL"
if [[ common_status -ne 0 ]]; then
common.Echo "Build message array. ?=$common_status, subshell=$BASH_SUBSHELL"
local "message=" "eof=TRY_CATCH_FINALLY_END_OF_MESSAGES_$RANDOM"
chmod "0600" "$common_fifo"
echo "$eof" >"$common_fifo"
common_messages=()
while read "message"; do
common.Echo "----> $message"
[[ $message != *$eof ]] || break
common_messages+=("$message")
done <"$common_fifo"
fi
common.Echo "In ytT status=$common_status"
common_trySubshell="$common_subshell"
}
common.Catch() {
common.TryCatchFinallyVerify || return
common.TryCatchFinallyNext "[yh]" "c" || return
[[ common_status -ne 0 ]] || return "1"
local "parameter" "pattern" "value"
local "toggle=true" "compare=p" "options=$-"
local -i "i=-1" "status=0"
set -f
for parameter in "$@"; do
if "$toggle"; then
toggle="false"
if [[ $parameter =~ ^-[notepr]$ ]]; then
compare="${parameter#-}"
continue
fi
fi
toggle="true"
while "true"; do
eval local "patterns=($parameter)"
if [[ ${#patterns[@]} -gt 0 ]]; then
for pattern in "${patterns[@]}"; do
[[ i -lt ${#common_messages[@]} ]] || break
if [[ i -lt 0 ]]; then
value="$common_status"
else
value="${common_messages[i]}"
fi
case $compare in
[ne]) [[ ! $value == "$pattern" ]] || break 2;;
[op]) [[ ! $value == $pattern ]] || break 2;;
[tr]) [[ ! $value =~ $pattern ]] || break 2;;
esac
done
fi
if [[ $compare == [not] ]]; then
let "++i,1"
continue 2
else
status="1"
break 2
fi
done
if [[ $compare == [not] ]]; then
status="1"
break
else
let "++i,1"
fi
done
[[ $options == *f* ]] || set +f
return "$status"
}
common.hctaC() {
common.TryCatchFinallyVerify || return
common.TryCatchFinallyNext "[c]" "h" || return
[[ $# -ne 1 || $1 != -r ]] || common_status="0"
}
common.Finally() {
common.TryCatchFinallyVerify || return
common.TryCatchFinallyNext "[ych]" "f" || return
}
common.yllaniF() {
common.TryCatchFinallyVerify || return
common.TryCatchFinallyNext "[f]" "l" || return
[[ common_status -eq 0 ]] || common.Throw
}
common.Caught() {
common.TryCatchFinallyVerify || return
[[ common_status -eq 0 ]] || return 1
}
common.EchoExitStatus() {
return "${1:-$?}"
}
common.EnableThrowOnError() {
common.TryCatchFinallyVerify || return
[[ $common_options == *e* ]] || common_options+="e"
}
common.DisableThrowOnError() {
common.TryCatchFinallyVerify || return
common_options="${common_options/e}"
}
common.GetStatus() {
common.TryCatchFinallyVerify || return
echo "$common_status"
}
common.SetStatus() {
common.TryCatchFinallyVerify || return
if [[ $# -ne 1 ]]; then
echo "$(common.GetAlias): $#: Wrong number of parameters" >&2
return "1"
elif [[ ${#1} -gt 16 || -n ${1%%[0-9]*} || 10#$1 -lt 1 || 10#$1 -gt 255 ]]; then
echo "$(common.GetAlias): $1: First parameter was not an integer between 1 and 255" >&2
return "1"
fi
let "common_status = 10#$1"
}
common.GetMessage() {
common.TryCatchFinallyVerify || return
local "upper=${#common_messages[@]}"
if [[ upper -eq 0 ]]; then
echo "$(common.GetAlias): $1: There are no messages" >&2
return "1"
elif [[ $# -ne 1 ]]; then
echo "$(common.GetAlias): $#: Wrong number of parameters" >&2
return "1"
elif [[ ${#1} -gt 16 || -n ${1%%[0-9]*} || 10#$1 -ge upper ]]; then
echo "$(common.GetAlias): $1: First parameter was an invalid index" >&2
return "1"
fi
echo "${common_messages[$1]}"
}
common.MessageCount() {
common.TryCatchFinallyVerify || return
echo "${#common_messages[@]}"
}
common.CopyMessages() {
common.TryCatchFinallyVerify || return
if [[ $# -ne 1 ]]; then
echo "$(common.GetAlias): $#: Wrong number of parameters" >&2
return "1"
elif [[ ${#common_messages} -gt 0 ]]; then
eval "$1=(\"\${common_messages[@]}\")"
else
eval "$1=()"
fi
}
common.TryCatchFinallyExists() {
[[ ${common_fifo:-u} != u ]]
}
common.TryCatchFinallyVerify() {
local "name"
if ! common.TryCatchFinallyExists; then
echo "$(common.GetAlias "1"): No Try-Catch-Finally exists" >&2
return "2"
fi
}
common.GetOptions() {
local "opt"
local "name=$(common.GetAlias "1")"
if common.TryCatchFinallyExists; then
echo "$name: A Try-Catch-Finally already exists" >&2
return "1"
fi
let "OPTIND = 1"
let "OPTERR = 0"
while getopts ":cdeh:ko:u:v:" opt "$@"; do
case $opt in
c) [[ $common_options == *c* ]] || common_options+="c";;
d) [[ $common_options == *d* ]] || common_options+="d";;
e) [[ $common_options == *e* ]] || common_options+="e";;
h) common_errHandler="$OPTARG";;
k) [[ $common_options == *k* ]] || common_options+="k";;
o) common_file="$OPTARG";;
u) common_unhandled="$OPTARG";;
v) common_command="$OPTARG";;
\?) #echo "Invalid option: -$OPTARG" >&2
echo "$name: Illegal option: $OPTARG" >&2
return "1";;
:) echo "$name: Option requires an argument: $OPTARG" >&2
return "1";;
*) echo "$name: An error occurred while parsing options." >&2
return "1";;
esac
done
shift "$((OPTIND - 1))"
if [[ $# -lt 1 ]]; then
echo "$name: The fifo_file parameter is missing" >&2
return "1"
fi
common_fifo="$1"
if [[ ! -p $common_fifo ]]; then
echo "$name: $1: The fifo_file is not an open FIFO" >&2
return "1"
fi
shift
if [[ $# -lt 1 ]]; then
echo "$name: The function parameter is missing" >&2
return "1"
fi
common_function="$1"
if ! chmod "0600" "$common_fifo"; then
echo "$name: $common_fifo: Can not change file mode to 0600" >&2
return "1"
fi
local "message=" "eof=TRY_CATCH_FINALLY_END_OF_FILE_$RANDOM"
{ echo "$eof" >"$common_fifo"; } 2>"/dev/null"
if [[ $? -ne 0 ]]; then
echo "$name: $common_fifo: Can not write" >&2
return "1"
fi
{ while [[ $message != *$eof ]]; do
read "message"
done <"$common_fifo"; } 2>"/dev/null"
if [[ $? -ne 0 ]]; then
echo "$name: $common_fifo: Can not read" >&2
return "1"
fi
return "0"
}
common.DefaultUnhandled() {
local -i "i"
echo "-------------------------------------------------"
echo "$(common.GetAlias "common.TryCatchFinally"): Unhandeled exception occurred"
echo "Status: $(GetStatus)"
echo "Messages:"
for ((i=0; i<$(MessageCount); i++)); do
echo "$(GetMessage "$i")"
done
echo "-------------------------------------------------"
}
common.TryCatchFinally() {
local "common_file=/dev/fd/2"
local "common_errHandler=common.DefaultErrHandler"
local "common_unhandled=common.DefaultUnhandled"
local "common_options="
local "common_fifo="
local "common_function="
local "common_flags=$-"
local "common_trySubshell=-1"
local "common_initSubshell=-1"
local "common_subshell"
local "common_status=0"
local "common_order=b"
local "common_command="
local "common_messages=()"
local "common_handler=$(trap -p ERR)"
[[ -n $common_handler ]] || common_handler="trap ERR"
common.GetOptions "$@" || return "$?"
shift "$((OPTIND + 1))"
[[ -z $common_command ]] || common_command+="=$"
common_command+='("$common_function" "$@")'
set -E
set +e
trap "common.ErrHandler" ERR
if true; then
common.Try
eval "$common_command"
common.EchoExitStatus
common.yrT
fi
while common.Catch; do
"$common_unhandled" >&2
break
common.hctaC -r
done
common.hctaC
[[ $common_flags == *E* ]] || set +E
[[ $common_flags != *e* ]] || set -e
[[ $common_flags != *f* || $- == *f* ]] || set -f
[[ $common_flags == *f* || $- != *f* ]] || set +f
eval "$common_handler"
return "$((common_status?2:0))"
}
To inspect your localStorage items you may type console.log(localStorage);
in your javascript console (firebug for example or in new FF versions the shipped js console).
You can use this line of Code to get rid of the browsers localStorage contents. Just execute it in your javascript console:
localStorage.clear();
All the answers already covered most of the things but I will add my 5 cents. In short reverting a merge commit is quite simple:
git revert -m 1 <commit-hash>
If you have permission you can push it directly to the "master" branch otherwise simply push it to your "revert" branch and create pull request.
You might find more useful info on this subject here: https://itcodehub.blogspot.com/2019/06/how-to-revert-merge-in-git.html
The previous posters made a little mistake. The accept attribute is only a display filter. It will not validate your entry before submitting.
This attribute forces the file dialog to display the required mime type only. But the user can override that filter. He can choose . and see all the files in the current directory. By doing so, he can select any file with any extension, and submit the form.
So, to answer to the original poster, NO. You cannot restrict the input file to one particular extension by using HTML.
But you can use javascript to test the filename that has been chosen, just before submitting. Just insert an onclick attribute on your submit button and call the code that will test the input file value. If the extension is forbidden, you'll have to return false to invalidate the form. You may even use a jQuery custom validator and so on, to validate the form.
Finally, you'll have to test the extension on the server side too. Same problem about the maximum allowed file size.
backdrop-filter
Unfortunately Mozilla has really dropped the ball and taken it's time with the feature. I'm personally hoping it makes it in to the next Firefox ESR as that is what the next major version of Waterfox will use.
MDN (Mozilla Developer Network) article: https://developer.mozilla.org/en-US/docs/Web/CSS/backdrop-filter
Mozilla implementation: https://bugzilla.mozilla.org/show_bug.cgi?id=1178765
From the MDN documentation page:
/* URL to SVG filter */
backdrop-filter: url(commonfilters.svg#filter);
/* <filter-function> values */
backdrop-filter: blur(2px);
backdrop-filter: brightness(60%);
backdrop-filter: contrast(40%);
backdrop-filter: drop-shadow(4px 4px 10px blue);
backdrop-filter: grayscale(30%);
backdrop-filter: hue-rotate(120deg);
backdrop-filter: invert(70%);
backdrop-filter: opacity(20%);
backdrop-filter: sepia(90%);
backdrop-filter: saturate(80%);
/* Multiple filters */
backdrop-filter: url(filters.svg#filter) blur(4px) saturate(150%);
Just fix your replaceAt
:
String.prototype.replaceAt = function(index, charcount) {
return this.substr(0, index) + this.substr(index + charcount);
}
mystring.replaceAt(4, 1);
I'd call it removeAt
instead. :)
It seems this all hinges on the question, is it possible to create a filename that can be used to hack into a server (or do some-such other damage). If not, then it seems the simple answer to is try creating the file wherever it will, ultimately, be used (since that will be the operating system of choice, no doubt). Let the operating system sort it out. If it complains, port that complaint back to the User as a Validation Error.
This has the added benefit of being reliably portable, since all (I'm pretty sure) operating systems will complain if the filename is not properly formed for that OS.
If it is possible to do nefarious things with a filename, perhaps there are measures that can be applied before testing the filename on the resident operating system -- measures less complicated than a full "sanitation" of the filename.
Simply it's work fine, in HTML:
<button type="button" id="btn_CommitAll"class="btn_CommitAll">save</button>
In JQuery side put this function for disable button:
function disableButton() {
$('.btn_CommitAll').prop("disabled", true);
}
For enable button:
function enableButton() {
$('.btn_CommitAll').prop("disabled", false);
}
That's all.
It's critical to emphasize the comma (,
) in a when
clause. It acts as an ||
of an if
statement, that is, it does an OR comparison and not an AND comparison between the delimited expressions of the when
clause. See the following case statement:
x = 3
case x
when 3, x < 2 then 'apple'
when 3, x > 2 then 'orange'
end
=> "apple"
x
is not less than 2, yet the return value is "apple"
. Why? Because x
was 3 and since ',`` acts as an
||, it did not bother to evaluate the expression
x < 2'.
You might think that to perform an AND, you can do something like this below, but it doesn't work:
case x
when (3 && x < 2) then 'apple'
when (3 && x > 2) then 'orange'
end
=> nil
It doesn't work because (3 && x > 2)
evaluates to true, and Ruby takes the True value and compares it to x
with ===
, which is not true, since x
is 3.
To do an &&
comparison, you will have to treat case
like an if
/else
block:
case
when x == 3 && x < 2 then 'apple'
when x == 3 && x > 2 then 'orange'
end
In the Ruby Programming Language book, Matz says this latter form is the simple (and infrequently used) form, which is nothing more than an alternative syntax for if
/elsif
/else
. However, whether it is infrequently used or not, I do not see any other way to attach multiple &&
expressions for a given when
clause.
Press the F12 function key in the Chrome browser to launch the JavaScript debugger and then click "Scripts".
Choose the JavaScript file on top and place the breakpoint to the debugger for the JavaScript code.
The function declaration int writeFile () ; seems to be missing in the code. Add int writeFile () ; before the function main()
ALTER TABLE TABLE_NAME ADD (COLUMN_NAME_NEW varchar2(4000 char));
update TABLE_NAME set COLUMN_NAME_NEW = COLUMN_NAME;
ALTER TABLE TABLE_NAME DROP COLUMN COLUMN_NAME;
ALTER TABLE TABLE_NAME rename column COLUMN_NAME_NEW to COLUMN_NAME;
it works for me, just change: Provider=Microsoft.Jet.OLEDB.4.0 (VS2013)
OleDbConnection connection = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Z:\\GENERAL\\OFMPTP_PD_SG.MDB");
DataSet DS = new DataSet();
connection.Open();
string query =
@"SELECT * from MONTHLYPROD";
OleDbDataAdapter DBAdapter = new OleDbDataAdapter();
DBAdapter.SelectCommand = new OleDbCommand(query, connection);
DBAdapter.Fill(DS);
Luis Montoya
Another example to output date and time using zero as a fill character on instances of single digit values: 2017-06-04 18:13:02
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;
int main()
{
time_t t = time(0); // Get time now
struct tm * now = localtime(&t);
cout.fill('0');
cout << (now->tm_year + 1900) << '-'
<< setw(2) << (now->tm_mon + 1) << '-'
<< setw(2) << now->tm_mday << ' '
<< setw(2) << now->tm_hour << ':'
<< setw(2) << now->tm_min << ':'
<< setw(2) << now->tm_sec
<< endl;
return 0;
}
If you are trying to do something similar to the Google search page when open in Chrome, (where certain events are triggered when you 'focus' on the page), then the hover() event may help.
$(window).hover(function() {
// code here...
});
It is possible to apply the specific GridView / Table layout via custom CSS rules (as it was discussed in the <table><tbody> scrollable? thread) to fix GridView's Header. However, this approach will not work in all browsers. The 3-rd ASP.NET GridView controls (such as the ASPxGridView from DevExpress component vendor provide this functionality.
Check also the following CodeProject solutions:
Answer for a slightly different problem:
You have a sequence of raw unicode that was saved into a str variable:
s_str: str = "\x00\x01\x00\xc0\x01\x00\x00\x00\x04"
You need to be able to get the byte literal of that unicode (for struct.unpack(), etc.)
s_bytes: bytes = b'\x00\x01\x00\xc0\x01\x00\x00\x00\x04'
Solution:
s_new: bytes = bytes(s, encoding="raw_unicode_escape")
Reference (scroll up for standard encodings):
I think that it's better to use simply str_replace, like the manual says:
If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of ereg_replace() or preg_replace().
<?
$badUrl = "http://www.site.com/backend.php?/c=crud&m=index&t=care";
$goodUrl = str_replace('?/', '?', $badUrl);
FTL stands for FreeMarker Template.
It is very useful when you want to follow the MVC (Model View Controller) pattern.
The idea behind using the MVC pattern for dynamic Web pages is that you separate the designers (HTML authors) from the programmers.
The Objective-C language level synchronization uses the mutex, just like NSLock
does. Semantically there are some small technical differences, but it is basically correct to think of them as two separate interfaces implemented on top of a common (more primitive) entity.
In particular with a NSLock
you have an explicit lock whereas with @synchronized
you have an implicit lock associated with the object you are using to synchronize. The benefit of the language level locking is the compiler understands it so it can deal with scoping issues, but mechanically they behave basically the same.
You can think of @synchronized
as a compiler rewrite:
- (NSString *)myString {
@synchronized(self) {
return [[myString retain] autorelease];
}
}
is transformed into:
- (NSString *)myString {
NSString *retval = nil;
pthread_mutex_t *self_mutex = LOOK_UP_MUTEX(self);
pthread_mutex_lock(self_mutex);
retval = [[myString retain] autorelease];
pthread_mutex_unlock(self_mutex);
return retval;
}
That is not exactly correct because the actual transform is more complex and uses recursive locks, but it should get the point across.
Solved by removing the -webkit-transform
from the navbar:
-webkit-transform: translate3d(0, 0, 0);
pillaged from https://stackoverflow.com/a/12653766/391925
Let us say your table has following fields:
( pk_id int not null auto_increment primary key,
col1 int,
col2 varchar(10)
)
then, to copy values from one row to the other row with new key value, following query may help
insert into my_table( col1, col2 ) select col1, col2 from my_table where pk_id=?;
This will generate a new value for pk_id
field and copy values from col1
, and col2
of the selected row.
You can extend this sample to apply for more fields in the table.
UPDATE:
In due respect to the comments from JohnP and Martin -
We can use temporary table to buffer first from main table and use it to copy to main table again. Mere update of pk reference field in temp table will not help as it might already be present in the main table. Instead we can drop the pk field from the temp table and copy all other to the main table.
With reference to the answer by Tim Ruehsen in the referred posting:
CREATE TEMPORARY TABLE tmp SELECT * from my_table WHERE ...;
ALTER TABLE tmp drop pk_id; # drop autoincrement field
# UPDATE tmp SET ...; # just needed to change other unique keys
INSERT INTO my_table SELECT 0,tmp.* FROM tmp;
DROP TEMPORARY TABLE tmp;
Hope this helps.
You might be in debug mode. If this is the problem, you can simply click on the "Java" button (next to the "Debug" button) in the upper-right hand corner, or click on "Open Perspective" and then select "Java (default)" from the "Open Perspective" window.
This should work
SELECT EXTRACTVALUE(column_name, '/DCResponse/ContextData/Decision') FROM traptabclob;
I have assumed the ** were just for highlighting?
If you are starting out a react-native app and seeing this issue, then you have to follow all the instructions listed in firebase (when you setup iOS/android app) or the instructions @ React-native google auth android DEVELOPER_ERROR Code 10 question
When it can be the same header for all requests or you dispose the client after each request you can use the DefaultRequestHeaders.Add
option:
client.DefaultRequestHeaders.Add("apikey","xxxxxxxxx");
I used this command to find last 5 minutes logs for particular event "DHCPACK
", try below:
$ grep "DHCPACK" /var/log/messages | grep "$(date +%h\ %d) [$(date --date='5 min ago' %H)-$(date +%H)]:*:*"
Clearing a list in place will affect all other references of the same list.
For example, this method doesn't affect other references:
>>> a = [1, 2, 3]
>>> b = a
>>> a = []
>>> print(a)
[]
>>> print(b)
[1, 2, 3]
But this one does:
>>> a = [1, 2, 3]
>>> b = a
>>> del a[:] # equivalent to del a[0:len(a)]
>>> print(a)
[]
>>> print(b)
[]
>>> a is b
True
You could also do:
>>> a[:] = []
Expanding on eumiro's comment, normally tuple(l)
will convert a list l
into a tuple:
In [1]: l = [4,5,6]
In [2]: tuple
Out[2]: <type 'tuple'>
In [3]: tuple(l)
Out[3]: (4, 5, 6)
However, if you've redefined tuple
to be a tuple rather than the type
tuple
:
In [4]: tuple = tuple(l)
In [5]: tuple
Out[5]: (4, 5, 6)
then you get a TypeError since the tuple itself is not callable:
In [6]: tuple(l)
TypeError: 'tuple' object is not callable
You can recover the original definition for tuple
by quitting and restarting your interpreter, or (thanks to @glglgl):
In [6]: del tuple
In [7]: tuple
Out[7]: <type 'tuple'>
As of Git v2.23.0 (August 2019), git switch
is preferred over git checkout
when you’re simply switching branches/tags. I’m guessing they did this since git checkout
had two functions: for switching branches and for restoring files. So in v2.23.0, they added two new commands, git switch
, and git restore
, to separate those concerns. I would predict at some point in the future, git checkout
will be deprecated.
To switch to a normal branch, use git switch <branch-name>
. To switch to a commit-like object, including single commits and tags, use git switch --detach <commitish>
, where <commitish>
is the tag name or commit number.
The --detach
option forces you to recognize that you’re in a mode of “inspection and discardable experiments”. To create a new branch from the commitish you’re switching to, use git switch -c <new-branch> <start-point>
.
URL-encoded payload must be provided on the body
parameter of the http.NewRequest(method, urlStr string, body io.Reader)
method, as a type that implements io.Reader
interface.
Based on the sample code:
package main
import (
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
)
func main() {
apiUrl := "https://api.com"
resource := "/user/"
data := url.Values{}
data.Set("name", "foo")
data.Set("surname", "bar")
u, _ := url.ParseRequestURI(apiUrl)
u.Path = resource
urlStr := u.String() // "https://api.com/user/"
client := &http.Client{}
r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
resp, _ := client.Do(r)
fmt.Println(resp.Status)
}
resp.Status
is 200 OK
this way.
you can use list to define it.
objs = list()
for i in range(10):
objs.append(MyClass())
In case you are using keras, there is a built in utility for that:
from keras.utils.np_utils import to_categorical
categorical_labels = to_categorical(int_labels, num_classes=3)
And it does pretty much the same as @YXD's answer (see source-code).
Use master.dbo.fn_varbintohexsubstring(0, HashBytes('SHA1', @input), 1, 0)
instead of master.dbo.fn_varbintohexstr
and then substringing
the result.
In fact fn_varbintohexstr
calls fn_varbintohexsubstring
internally. The first argument of fn_varbintohexsubstring
tells it to add 0xF
as the prefix or not. fn_varbintohexstr
calls fn_varbintohexsubstring
with 1
as the first argument internaly.
Because you don't need 0xF
, call fn_varbintohexsubstring
directly.
Just the thread.
Your class shoud look something like this:
class Something { int[] array; //global array, replace type of course void function1() { array = new int[10]; //let say you declare it here that will be 10 integers in size } void function2() { array[0] = 12; //assing value at index 0 to 12. } }
That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.
Here Response.Write():to display only string and you can not display any other data type values like int,date,etc.Conversion(from one data type to another) is not allowed. whereas Response .Output .Write(): you can display any type of data like int, date ,string etc.,by giving index values.
Here is example:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write ("hi good morning!"+"is it right?");//only strings are allowed
Response.Write("Scott is {0} at {1:d}", "cool", DateTime.Now);//this will give error(conversion is not allowed)
Response.Output.Write("\nhi goood morning!");//works fine
Response.Output.Write("Jai is {0} on {1:d}", "cool", DateTime.Now);//here the current date will be converted into string and displayed
}
Actually, I think that the answer given in the question you mentioned is just wrong (UPDATE - 20101106: someone fixed it, this answer refers to the version preceding the edit) and this explains, at least partially, why you run into troubles.
It generates two jar files in logmanager/target: logmanager-0.1.0.jar, and logmanager-0.1.0-jar-with-dependencies.jar.
The first one is the JAR of the logmanager module generated during the package
phase by jar:jar
(because the module has a packaging of type jar
). The second one is the assembly generated by assembly:assembly
and should contain the classes from the current module and its dependencies (if you used the descriptor jar-with-dependencies
).
I get an error when I double-click on the first jar:
Could not find the main class: com.gorkwobble.logmanager.LogManager. Program will exit.
If you applied the suggested configuration of the link posted as reference, you configured the jar plugin to produce an executable artifact, something like this:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.gorkwobble.logmanager.LogManager</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
So logmanager-0.1.0.jar
is indeed executable but 1. this is not what you want (because it doesn't have all dependencies) and 2. it doesn't contain com.gorkwobble.logmanager.LogManager
(this is what the error is saying, check the content of the jar).
A slightly different error when I double-click the jar-with-dependencies.jar:
Failed to load Main-Class manifest attribute from: C:\EclipseProjects\logmanager\target\logmanager-0.1.0-jar-with-dependencies.jar
Again, if you configured the assembly plugin as suggested, you have something like this:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
With this setup, logmanager-0.1.0-jar-with-dependencies.jar
contains the classes from the current module and its dependencies but, according to the error, its META-INF/MANIFEST.MF
doesn't contain a Main-Class
entry (its likely not the same MANIFEST.MF as in logmanager-0.1.0.jar). The jar is actually not executable, which again is not what you want.
So, my suggestion would be to remove the configuration
element from the maven-jar-plugin and to configure the maven-assembly-plugin like this:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.2</version>
<!-- nothing here -->
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2-beta-4</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>org.sample.App</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
Of course, replace org.sample.App
with the class you want to have executed. Little bonus, I've bound assembly:single
to the package
phase so you don't have to run assembly:assembly
anymore. Just run mvn install
and the assembly will be produced during the standard build.
So, please update your pom.xml with the configuration given above and run mvn clean install
. Then, cd into the target
directory and try again:
java -jar logmanager-0.1.0-jar-with-dependencies.jar
If you get an error, please update your question with it and post the content of the META-INF/MANIFEST.MF
file and the relevant part of your pom.xml
(the plugins configuration parts). Also please post the result of:
java -cp logmanager-0.1.0-jar-with-dependencies.jar com.gorkwobble.logmanager.LogManager
to demonstrate it's working fine on the command line (regardless of what eclipse is saying).
EDIT: For Java 6, you need to configure the maven-compiler-plugin. Add this to your pom.xml:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
For me the issue is resolved by adding domain name in user name as follow:
string userName="yourUserName";
string password="passowrd";
string hostName="LdapServerHostName";
string domain="yourDomain";
System.DirectoryServices.AuthenticationTypes option = System.DirectoryServices.AuthenticationTypes.SecureSocketsLayer;
string userNameWithDomain = string.Format("{0}@{1}",userName , domain);
DirectoryEntry directoryOU = new DirectoryEntry("LDAP://" + hostName, userNameWithDomain, password, option);
Ofcourse this is a closed issue, i would like to add something to your discussion
In mozilla i have observed a weird behaviour for this code
$(document).keydown(function(){
//my code
});
the code is being triggered twice. When debugged i found that actually there are two events getting fired: 'keypress' and 'keydown'. I disabled one of the event and the code shown me expected behavior.
$(document).unbind('keypress');
$(document).keydown(function(){
//my code
});
This works for all browsers and also there is no need to check for browser specific(if($.browser.mozilla){ }).
Hope this might be useful for someone
Alternatively you can also use CASE
for the same:
SELECT CASE WHEN field1 IS NULL OR field1 = ''
THEN 'empty'
ELSE field1 END AS field1
FROM tablename.
I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer
Here's what I used:
In JavaScript:
var url = "http://www.mynewsfeed.com/articles/index.php?id=17";
var encoded_url = encodeURIComponent(url);
var decoded_url = decodeURIComponent(encoded_url);
In PHP:
$url = "http://www.mynewsfeed.com/articles/index.php?id=17";
$encoded_url = url_encode(url);
$decoded_url = url_decode($encoded_url);
You can also try it online here: http://www.mynewsfeed.x10.mx/articles/index.php?id=17
My issue was, i am unable to create a view with my "scott" user in oracle 11g edition. So here is my solution for this
Error in my case
SQL>create view v1 as select * from books where id=10;
insufficient privileges.
Solution
1)open your cmd and change your directory to where you install your oracle database. in my case i was downloaded in E drive so my location is E:\app\B_Amar\product\11.2.0\dbhome_1\BIN> after reaching in the position you have to type sqlplus sys as sysdba
E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba
2) Enter password: here you have to type that password that you give at the time of installation of oracle software.
3) Here in this step if you want create a new user then you can create otherwise give all the privileges to existing user.
for creating new user
SQL> create user abc identified by xyz;
here abc is user and xyz is password.
giving all the privileges to abc user
SQL> grant all privileges to abc;
grant succeeded.
if you are seen this message then all the privileges are giving to the abc user.
4) Now exit from cmd, go to your SQL PLUS and connect to the user i.e enter your username & password.Now you can happily create view.
In My case
in cmd E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba
SQL> grant all privileges to SCOTT;
grant succeeded.
Now I can create views.
use this style
@"server=.\sqlexpress;"
Just for the records.
Here is a link from Microsoft that I think is the best way to present a MessageBox in ASP.Net
Also it presents choices like Yes and NO.
Instructions on how to get the class from the link working on your project:
Add this code to your aspx page where you want to display the message box:
<asp:Literal ID="PopupBox" runat="server"></asp:Literal>
Add this code on you cs page where you want to decision to be made:
string title = "My box title goes here";
string text = "Do you want to Update this record?";
MessageBox messageBox = new MessageBox(text, title, MessageBox.MessageBoxIcons.Question, MessageBox.MessageBoxButtons.YesOrNo, MessageBox.MessageBoxStyle.StyleA);
messageBox.SuccessEvent.Add("YesModClick");
PopupBox.Text = messageBox.Show(this);
Add this method to your cs page. This is what will be executed when the user clicks Yes. You don't need to make another one for the NoClick
method.
[WebMethod]
public static string YesModClick(object sender, EventArgs e)
{
string strToRtn = "";
// The code that you want to execute when the user clicked yes goes here
return strToRtn;
}
Add a WebUserControl1.ascx file to your root path and add this code to the file:
<link href="~/Styles/MessageBox.css" rel="stylesheet" type="text/css" />
<div id="result"></div>
<asp:ScriptManager runat="server" ID="scriptManager" EnablePageMethods="True">
</asp:ScriptManager> //<-- Make sure you only have one ScriptManager on your aspx page. Remove the one on your aspx page if you already have one.
Add this line on top of your aspx page:
<%@ Register src="~/MessageBoxUserControl.ascx" tagname="MessageBoxUserControl" tagprefix="uc1" %>
Add this line inside your aspx page (Inside your asp:Content tag if you have one)
<uc1:MessageBoxUserControl ID="MessageBoxUserControl1" runat="server" />
Save the image files 1.jpg, 2.jpg, 3.jpg, 4.jpg
from the Microsoft project above into your ~/Images/
path.
Done
Hope it helps.
Pablo
For arrays of structs/values, I have different results with:
first = Marshal.UnsafeAddrOfPinnedArrayElement(array, 0).ToInt64();
second = Marshal.UnsafeAddrOfPinnedArrayElement(array, 1).ToInt64();
arrayElementSize = second - first;
(oversimplified example)
Whatever the approach, you really need to understand how .Net works to correctly interpret the results. For instance, the returned element size is the "aligned" element size, with some padding. The overhead and thus the size is different depending on the usage of a type: "boxed" on the GC heap, on the stack, as a field, as an array element.
(I wanted to know what would be the memory impact of using "dummy" empty structs (without any field) to mimic "optional" arguments of generics; making tests with different layouts involving empty structs, I can see that an empty struct uses (at least) 1 byte per element; I vaguely remember it is because .Net needs a different address for each field, which wouldn't work if a field really was empty/0-sized).
You can you with your source folder so whenever you build, those files are automatically copied to the classes directory.
Instead of using properties file, use XML file.
If the data is too small, you can even use web.xml for accessing the properties.
Please note that any of these approach will require app server restart for changes to be reflected.
If you don't have any server side code, you security depends on the security of the access to your JavaScript code on the client side (ie everybody who has the code could upload something).
So I would recommend, to simply create a special S3 bucket which is public writeable (but not readable), so you don't need any signed components on the client side.
The bucket name (a GUID eg) will be your only defense against malicious uploads (but a potential attacker could not use your bucket to transfer data, because it is write only to him)
var versionAttrib = new AssemblyName(Assembly.GetExecutingAssembly().FullName);
If you can move to SQL Server 2008, you can take advantage of the FILESTREAM support which gives you the best of both - the files are stored in the filesystem, but the database integration is much better than just storing a filepath in a varchar field. Your query can return a standard .NET file stream, which makes the integration a lot simpler.
I solve the issue which gives below written error:
Error:
The authenticity of host 'XXX.XXX.XXX' can't be established.
RSA key fingerprint is 09:6c:ef:cd:55:c4:4f:ss:5a:88:46:0a:a9:27:83:89.
Solution:
1. install any openSSH tool.
2. run command ssh
3. it will ask for do u add this host like.
accept YES.
4. This host will add in the known host list.
5. Now you are able to connect with this host.
This solution is working now......
Something like next:
>>> myList = [1, 2, 3, 100, 5]
>>> [i[0] for i in sorted(enumerate(myList), key=lambda x:x[1])]
[0, 1, 2, 4, 3]
enumerate(myList)
gives you a list containing tuples of (index, value):
[(0, 1), (1, 2), (2, 3), (3, 100), (4, 5)]
You sort the list by passing it to sorted
and specifying a function to extract the sort key (the second element of each tuple; that's what the lambda
is for. Finally, the original index of each sorted element is extracted using the [i[0] for i in ...]
list comprehension.
Here's a demo. Even works in IE7:
http://james.padolsey.com/demos/grayscale/
and
http://james.padolsey.com/javascript/grayscaling-in-non-ie-browsers/
The following worked for me after hours of trying
$http.post("http://localhost:8080/yourresource", parameter, {headers:
{'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } }).
However following code did not work, I am unclear as to why, hopefully someone can improve this answer.
$http({ method: 'POST', url: "http://localhost:8080/yourresource",
parameter,
headers: {'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST'}
})
This worked for me with some css frameworks (material design lite [MDL]).
table {
table-layout: fixed;
white-space: normal!important;
}
td {
word-wrap: break-word;
}
Laravel 4.2 and beyond, may use try relationship querying:-
Products::whereHas('product_category', function($query) {
$query->whereIn('category_id', ['223', '15']);
});
public function product_category() {
return $this->hasMany('product_category', 'product_id');
}
With attribute selector we target input type text in CSS
input[type=text] {
background:gold;
font-size:15px;
}
Your problem is that, if the user clicks cancel, operationType
is null and thus throws a NullPointerException. I would suggest that you move
if (operationType.equalsIgnoreCase("Q"))
to the beginning of the group of if statements, and then change it to
if(operationType==null||operationType.equalsIgnoreCase("Q")).
This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.
Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.
Regarding elegance, the closest thing to the mathematical notation (a <= x <= b) slightly improves readability:
public static bool IsBetween(this int value, int min, int max)
{
return min <= value && value <= max;
}
For further illustration:
public static bool IsOutside(this int value, int min, int max)
{
return value < min || max < value;
}
Assuming you don't have extraneous whitespace:
with open('file') as f:
w, h = [int(x) for x in next(f).split()] # read first line
array = []
for line in f: # read rest of lines
array.append([int(x) for x in line.split()])
You could condense the last for loop into a nested list comprehension:
with open('file') as f:
w, h = [int(x) for x in next(f).split()]
array = [[int(x) for x in line.split()] for line in f]
The Easiest way is this way :
from csv import reader
# open file in read mode
with open('file.csv', 'r') as read_obj:
# pass the file object to reader() to get the reader object
csv_reader = reader(read_obj)
# Iterate over each row in the csv using reader object
for row in csv_reader:
# row variable is a list that represents a row in csv
print(row)
output:
['Year:', 'Dec:', 'Jan:']
['1', '50', '60']
['2', '25', '50']
['3', '30', '30']
['4', '40', '20']
['5', '10', '10']
.aku {
transition: all .2s ease-in-out;
}
.aku:hover {
transform: scale(1.1);
}
You can simply use adb install command to install/update APK silently. Sample code is below
public static void InstallAPK(String filename){
File file = new File(filename);
if(file.exists()){
try {
String command;
filename = StringUtil.insertEscape(filename);
command = "adb install -r " + filename;
Process proc = Runtime.getRuntime().exec(new String[] { "su", "-c", command });
proc.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
}
}
If you only want to sort only on the 5th field then use -k5,5
.
Also, use the -t
command line switch to specify the delimiter to tab
. Try this:
sort -k5,5 -r -n -t \t filename
or if the above doesn't work (with the tab
) this:
sort -k5,5 -r -n -t $'\t' filename
The man page for sort states:
-t, --field-separator=SEP use SEP instead of non-blank to blank transition
Finally, this SO question Unix Sort with Tab Delimiter might be helpful.
Your setup.py
file needs setuptools
. Some Python packages used to use distutils
for distribution, but most now use setuptools
, a more complete package. Here is a question about the differences between them.
To install setuptools
on Debian:
sudo apt-get install python3-setuptools
For an older version of Python (Python 2.x):
sudo apt-get install python-setuptools
In my case I had created a SB app from the SB Initializer and had included a fair number of deps in it to other things. I went in and commented out the refs to them in the build.gradle file and so was left with:
implementation 'org.springframework.boot:spring-boot-starter-hateoas'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'org.hsqldb:hsqldb'
runtimeOnly 'org.postgresql:postgresql'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc'
as deps. Then my bare-bones SB app was able to build and get running successfully. As I go to try to do things that may need those commented-out libs I will add them back and see what breaks.
Back in the old days of Python, to call a function with arbitrary arguments, you would use apply
:
apply(f,args,kwargs)
apply
still exists in Python2.7 though not in Python3, and is generally not used anymore. Nowadays,
f(*args,**kwargs)
is preferred. The multiprocessing.Pool
modules tries to provide a similar interface.
Pool.apply
is like Python apply
, except that the function call is performed in a separate process. Pool.apply
blocks until the function is completed.
Pool.apply_async
is also like Python's built-in apply
, except that the call returns immediately instead of waiting for the result. An AsyncResult
object is returned. You call its get()
method to retrieve the result of the function call. The get()
method blocks until the function is completed. Thus, pool.apply(func, args, kwargs)
is equivalent to pool.apply_async(func, args, kwargs).get()
.
In contrast to Pool.apply
, the Pool.apply_async
method also has a callback which, if supplied, is called when the function is complete. This can be used instead of calling get()
.
For example:
import multiprocessing as mp
import time
def foo_pool(x):
time.sleep(2)
return x*x
result_list = []
def log_result(result):
# This is called whenever foo_pool(i) returns a result.
# result_list is modified only by the main process, not the pool workers.
result_list.append(result)
def apply_async_with_callback():
pool = mp.Pool()
for i in range(10):
pool.apply_async(foo_pool, args = (i, ), callback = log_result)
pool.close()
pool.join()
print(result_list)
if __name__ == '__main__':
apply_async_with_callback()
may yield a result such as
[1, 0, 4, 9, 25, 16, 49, 36, 81, 64]
Notice, unlike pool.map
, the order of the results may not correspond to the order in which the pool.apply_async
calls were made.
So, if you need to run a function in a separate process, but want the current process to block until that function returns, use Pool.apply
. Like Pool.apply
, Pool.map
blocks until the complete result is returned.
If you want the Pool of worker processes to perform many function calls asynchronously, use Pool.apply_async
. The order of the results is not guaranteed to be the same as the order of the calls to Pool.apply_async
.
Notice also that you could call a number of different functions with Pool.apply_async
(not all calls need to use the same function).
In contrast, Pool.map
applies the same function to many arguments.
However, unlike Pool.apply_async
, the results are returned in an order corresponding to the order of the arguments.
I'll never easily remember these cryptic command modifiers so I took the top answer and turned it into a function in my ~/.bashrc
file:
cgrep() {
# For files that are arrays 10's of thousands of characters print.
# Use cpgrep to print 30 characters before and after search patttern.
if [ $# -eq 2 ] ; then
# Format was 'cgrep "search string" /path/to/filename'
grep -o -P ".{0,30}$1.{0,30}" "$2"
else
# Format was 'cat /path/to/filename | cgrep "search string"
grep -o -P ".{0,30}$1.{0,30}"
fi
} # cgrep()
Here's what it looks like in action:
$ ll /tmp/rick/scp.Mf7UdS/Mf7UdS.Source
-rw-r--r-- 1 rick rick 25780 Jul 3 19:05 /tmp/rick/scp.Mf7UdS/Mf7UdS.Source
$ cat /tmp/rick/scp.Mf7UdS/Mf7UdS.Source | cgrep "Link to iconic"
1:43:30.3540244000 /mnt/e/bin/Link to iconic S -rwxrwxrwx 777 rick 1000 ri
$ cgrep "Link to iconic" /tmp/rick/scp.Mf7UdS/Mf7UdS.Source
1:43:30.3540244000 /mnt/e/bin/Link to iconic S -rwxrwxrwx 777 rick 1000 ri
The file in question is one continuous 25K line and it is hopeless to find what you are looking for using regular grep
.
Notice the two different ways you can call cgrep
that parallels grep
method.
There is a "niftier" way of creating the function where "$2" is only passed when set which would save 4 lines of code. I don't have it handy though. Something like ${parm2} $parm2
. If I find it I'll revise the function and this answer.
This works for me - i am using jackson 2.0.4
ObjectMapper objectMapper = new ObjectMapper();
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
objectMapper.setDateFormat(df);
Easy way to compare two json string in javascript
var obj1 = {"name":"Sam","class":"MCA"};
var obj2 = {"class":"MCA","name":"Sam"};
var flag=true;
if(Object.keys(obj1).length==Object.keys(obj2).length){
for(key in obj1) {
if(obj1[key] == obj2[key]) {
continue;
}
else {
flag=false;
break;
}
}
}
else {
flag=false;
}
console.log("is object equal"+flag);
You can also solve this problem by creating an array of values and assigning that array:
newheaders <- c("a", "b", "c", ... "x")
colnames(data) <- newheaders
The reason is that your rule
%.o: %.cpp
...
expects the .cpp file to reside in the same directory as the .o your building. Since test.exe in your case depends on build/widgets/apple.o (etc), make is expecting apple.cpp to be build/widgets/apple.cpp.
You can use VPATH to resolve this:
VPATH = src/widgets
BUILDDIR = build/widgets
$(BUILDDIR)/%.o: %.cpp
...
When attempting to build "build/widgets/apple.o", make will search for apple.cpp in VPATH. Note that the build rule has to use special variables in order to access the actual filename make finds:
$(BUILDDIR)/%.o: %.cpp
$(CC) $< -o $@
Where "$<" expands to the path where make located the first dependency.
Also note that this will build all the .o files in build/widgets. If you want to build the binaries in different directories, you can do something like
build/widgets/%.o: %.cpp
....
build/ui/%.o: %.cpp
....
build/tests/%.o: %.cpp
....
I would recommend that you use "canned command sequences" in order to avoid repeating the actual compiler build rule:
define cc-command
$(CC) $(CFLAGS) $< -o $@
endef
You can then have multiple rules like this:
build1/foo.o build1/bar.o: %.o: %.cpp
$(cc-command)
build2/frotz.o build2/fie.o: %.o: %.cpp
$(cc-command)
You could use my JavaScript hash table implementation, jshashtable. It allows any object to be used as a key, not just strings.
try this: File->project Structure into Project Structure Left > SDKs SDK location select Android SDK location (old version use Press +, add another sdk)
Click the items in the list view. Add a button that will edit the selected items. Add the code
try
{
LSTDEDUCTION.SelectedItems[0].SubItems[1].Text = txtcarName.Text;
LSTDEDUCTION.SelectedItems[0].SubItems[0].Text = txtcarBrand.Text;
LSTDEDUCTION.SelectedItems[0].SubItems[2].Text = txtCarName.Text;
}
catch{}
The 4-Step Answer above worked for me, but it returns the SH1-key... but Google asks for the MD5-key to generate your API key.
One needs simply to add a '-v' in the command in step 3. -like so:
Updated 4-Step Answer
Ok I did this in Windows 7 32-bit system.
step 1: go to - C:\Program Files\Java\jdk1.7.0\bin - and run jarsigner.exe first ( double click)
step2: locate debug.keystore (in Eclipse: Windows/Preferences/Android/build..), in my case it was - C:\Users\MyPcName.android
step3: open command prompt and go to dir - C:\Program Files\Java\jdk1.7.0\bin and give the following command: keytool -v -list -keystore "C:\Users\MyPcName.android\debug.keystore"
step4: it will ask for Keystore password now. The default is 'android'
You can use the for..in TypeScript operator to access the index when dealing with collections.
var test = [7,8,9];
for (var i in test) {
console.log(i + ': ' + test[i]);
}
Output:
0: 7
1: 8
2: 9
See Demo
It's the only construct in C that you can use to #define
a multistatement operation, put a semicolon after, and still use within an if
statement. An example might help:
#define FOO(x) foo(x); bar(x)
if (condition)
FOO(x);
else // syntax error here
...;
Even using braces doesn't help:
#define FOO(x) { foo(x); bar(x); }
Using this in an if
statement would require that you omit the semicolon, which is counterintuitive:
if (condition)
FOO(x)
else
...
If you define FOO like this:
#define FOO(x) do { foo(x); bar(x); } while (0)
then the following is syntactically correct:
if (condition)
FOO(x);
else
....
Go into your application directory on terminal and run following command:
heroku restart
It seems to me that the answer provided by Nemo is the correct one. If those instructions do not work, the issue may be related to the version of gcc/ld you're using, as an exercise I compiled an example program using instructions detailed here
#include <stdio.h>
void deadcode() { printf("This is d dead codez\n"); }
int main(void) { printf("This is main\n"); return 0 ; }
Then I compiled the code using progressively more aggressive dead-code removal switches:
gcc -Os test.c -o test.elf
gcc -Os -fdata-sections -ffunction-sections test.c -o test.elf -Wl,--gc-sections
gcc -Os -fdata-sections -ffunction-sections test.c -o test.elf -Wl,--gc-sections -Wl,--strip-all
These compilation and linking parameters produced executables of size 8457, 8164 and 6160 bytes, respectively, the most substantial contribution coming from the 'strip-all' declaration. If you cannot produce similar reductions on your platform,then maybe your version of gcc does not support this functionality. I'm using gcc(4.5.2-8ubuntu4), ld(2.21.0.20110327) on Linux Mint 2.6.38-8-generic x86_64
private File convertMultiPartToFile(MultipartFile file ) throws IOException
{
File convFile = new File( file.getOriginalFilename() );
FileOutputStream fos = new FileOutputStream( convFile );
fos.write( file.getBytes() );
fos.close();
return convFile;
}
Try this "html-approach" which is acceptable for small JS projects
function msg(animal,is) {
console.log(animal, is.checked); // Do stuff
}
_x000D_
<input type="checkbox" oninput="msg('dog', this)" />Do you have a dog? <br>
<input type="checkbox" oninput="msg('frog',this)" />Do you have a frog?<br>
...
_x000D_
From What's this "serialization" thing all about?:
It lets you take an object or group of objects, put them on a disk or send them through a wire or wireless transport mechanism, then later, perhaps on another computer, reverse the process: resurrect the original object(s). The basic mechanisms are to flatten object(s) into a one-dimensional stream of bits, and to turn that stream of bits back into the original object(s).
Like the Transporter on Star Trek, it's all about taking something complicated and turning it into a flat sequence of 1s and 0s, then taking that sequence of 1s and 0s (possibly at another place, possibly at another time) and reconstructing the original complicated "something."
So, implement the Serializable
interface when you need to store a copy of the object, send them to another process which runs on the same system or over the network.
Because you want to store or send an object.
It makes storing and sending objects easy. It has nothing to do with security.
var str = '[basic_salary]+100/[basic_salary]';
var arr = str.split('');
var myArr = [];
for(var i=0;i<arr.length;i++){
if(arr[i] == '['){
var a = '';
for(var j=i+1;j<arr.length;j++){
if(arr[j] == ']'){
var i = j-1;
break;
}else{
a += arr[j];
}
}
myArr.push(a);
}
var operatorsArr = ['+','-','*','/','%'];
if(operatorsArr.includes(arr[i])){
myArr.push(arr[i]);
}
var numbArr = ['0','1','2','3','4','5','6','7','8','9'];
if(numbArr.includes(arr[i])){
var a = '';
for(var j=i;j<arr.length;j++){
if(numbArr.includes(arr[j])){
a += arr[j];
}else{
var i = j-1;
break;
}
}
myArr.push(a);
}
}
myArr = ["basic_salary", "+", "100", "/", "basic_salary"]
(function(angular) {
'use strict';
angular.module('dragModule', [])
.directive('myDraggable', ['$document', function($document) {
return {
link: function(scope, element, attr) {
element.bind("keydown keypress", function (event) {
console.log('keydown keypress', event.which);
if(event.which === 13) {
event.preventDefault();
}
});
}
};
}]);
})(window.angular);
You can't restart a thread so your best option is to save the current state of the object at the time the thread was stopped and when operations need to continue on that object you can recreate that object using the saved and then start the new thread.
These two articles Swing Worker and Concurrency may help you determine the best solution for your problem.