If you want to write bytes then you should open the file in binary mode.
f = open('/tmp/output', 'wb')
I use two methods for relative sizing. I have a class called Relative
with three attached properties To
, WidthPercent
and HeightPercent
which is useful if I want an element to be a relative size of an element anywhere in the visual tree and feels less hacky than the converter approach - although use what works for you, that you're happy with.
The other approach is rather more cunning. Add a ViewBox
where you want relative sizes inside, then inside that, add a Grid
at width 100. Then if you add a TextBlock
with width 10 inside that, it is obviously 10% of 100.
The ViewBox
will scale the Grid
according to whatever space it has been given, so if its the only thing on the page, then the Grid
will be scaled out full width and effectively, your TextBlock
is scaled to 10% of the page.
If you don't set a height on the Grid
then it will shrink to fit its content, so it'll all be relatively sized. You'll have to ensure that the content doesn't get too tall, i.e. starts changing the aspect ratio of the space given to the ViewBox
else it will start scaling the height as well. You can probably work around this with a Stretch
of UniformToFill
.
If you want to have control over this you need to implement the [IEquatable interface][1]
[1]: http://This method determines equality by using the default equality comparer, as defined by the object's implementation of the IEquatable.Equals method for T (the type of values in the list).
I think you have putted e.preventDefault(); before ajax call that's why its prevent calling of that function and your Ajax call will not call.
So try to remove that e.prevent Default() before Ajax call and add it to the after Ajax call.
This seems to be the fastest solution I could come up with, and is faster than os.walk
and a lot faster than any glob
solution.
f.path
to f.name
(do not change it for subfolders!).Args: dir: str, ext: list
.
Function returns two lists: subfolders, files
.
See below for a detailed speed anaylsis.
def run_fast_scandir(dir, ext): # dir: str, ext: list
subfolders, files = [], []
for f in os.scandir(dir):
if f.is_dir():
subfolders.append(f.path)
if f.is_file():
if os.path.splitext(f.name)[1].lower() in ext:
files.append(f.path)
for dir in list(subfolders):
sf, f = run_fast_scandir(dir, ext)
subfolders.extend(sf)
files.extend(f)
return subfolders, files
subfolders, files = run_fast_scandir(folder, [".jpg"])
In case you need the file size, you can also create a sizes
list and add f.stat().st_size
like this for a display of MiB:
sizes.append(f"{f.stat().st_size/1024/1024:.0f} MiB")
Speed analysis
for various methods to get all files with a specific file extension inside all subfolders and the main folder.
tl;dr:
fast_scandir
clearly wins and is twice as fast as all other solutions, except os.walk.os.walk
is second place slighly slower.glob
will greatly slow down the process.fast_scandir took 499 ms. Found files: 16596. Found subfolders: 439
os.walk took 589 ms. Found files: 16596
find_files took 919 ms. Found files: 16596
glob.iglob took 998 ms. Found files: 16596
glob.glob took 1002 ms. Found files: 16596
pathlib.rglob took 1041 ms. Found files: 16596
os.walk-glob took 1043 ms. Found files: 16596
Tests were done with W7x64, Python 3.8.1, 20 runs. 16596 files in 439 (partially nested) subfolders.
find_files
is from https://stackoverflow.com/a/45646357/2441026 and lets you search for several extensions.
fast_scandir
was written by myself and will also return a list of subfolders. You can give it a list of extensions to search for (I tested a list with one entry to a simple if ... == ".jpg"
and there was no significant difference).
# -*- coding: utf-8 -*-
# Python 3
import time
import os
from glob import glob, iglob
from pathlib import Path
directory = r"<folder>"
RUNS = 20
def run_os_walk():
a = time.time_ns()
for i in range(RUNS):
fu = [os.path.join(dp, f) for dp, dn, filenames in os.walk(directory) for f in filenames if
os.path.splitext(f)[1].lower() == '.jpg']
print(f"os.walk\t\t\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found files: {len(fu)}")
def run_os_walk_glob():
a = time.time_ns()
for i in range(RUNS):
fu = [y for x in os.walk(directory) for y in glob(os.path.join(x[0], '*.jpg'))]
print(f"os.walk-glob\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found files: {len(fu)}")
def run_glob():
a = time.time_ns()
for i in range(RUNS):
fu = glob(os.path.join(directory, '**', '*.jpg'), recursive=True)
print(f"glob.glob\t\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found files: {len(fu)}")
def run_iglob():
a = time.time_ns()
for i in range(RUNS):
fu = list(iglob(os.path.join(directory, '**', '*.jpg'), recursive=True))
print(f"glob.iglob\t\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found files: {len(fu)}")
def run_pathlib_rglob():
a = time.time_ns()
for i in range(RUNS):
fu = list(Path(directory).rglob("*.jpg"))
print(f"pathlib.rglob\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found files: {len(fu)}")
def find_files(files, dirs=[], extensions=[]):
# https://stackoverflow.com/a/45646357/2441026
new_dirs = []
for d in dirs:
try:
new_dirs += [ os.path.join(d, f) for f in os.listdir(d) ]
except OSError:
if os.path.splitext(d)[1].lower() in extensions:
files.append(d)
if new_dirs:
find_files(files, new_dirs, extensions )
else:
return
def run_fast_scandir(dir, ext): # dir: str, ext: list
# https://stackoverflow.com/a/59803793/2441026
subfolders, files = [], []
for f in os.scandir(dir):
if f.is_dir():
subfolders.append(f.path)
if f.is_file():
if os.path.splitext(f.name)[1].lower() in ext:
files.append(f.path)
for dir in list(subfolders):
sf, f = run_fast_scandir(dir, ext)
subfolders.extend(sf)
files.extend(f)
return subfolders, files
if __name__ == '__main__':
run_os_walk()
run_os_walk_glob()
run_glob()
run_iglob()
run_pathlib_rglob()
a = time.time_ns()
for i in range(RUNS):
files = []
find_files(files, dirs=[directory], extensions=[".jpg"])
print(f"find_files\t\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found files: {len(files)}")
a = time.time_ns()
for i in range(RUNS):
subf, files = run_fast_scandir(directory, [".jpg"])
print(f"fast_scandir\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found files: {len(files)}. Found subfolders: {len(subf)}")
Follow the below steps to avoid (cannot convert between unicode and non-unicode string data types) this error
i) Add the Data conversion Transformation tool to your DataFlow.
ii) To open the DataFlow Conversion and select [string DT_STR] datatype.
iii) Then go to Destination flow, select Mapping.
iv) change your i/p name to copy of the name.
According to the Apache site this is the Gradle dependency you need to include, if you use Android API 23 or newer:
dependencies {
compile group: 'cz.msebera.android' , name: 'httpclient', version: '4.4.1.1'
}
Source: https://hc.apache.org/httpcomponents-client-4.5.x/android-port.html
It seems you need to do combobox->itemData(combobox->currentIndex())
if you want to get the current data of the QComboBox.
If you are using your own class derived from QComboBox, you can add a currentData()
function.
If all you want is to see the date like so "YYYY-MM-DD" without all the other clutter e.g. "Thu May 21 12:08:18 EDT 2015" then just use java.sql.Date
. This example gets the current date:
new java.sql.Date(System.currentTimeMillis());
Also java.sql.Date
is a subclass of java.util.Date
.
Yes! And another solution. My solution differs in the keys that are being checked.
In all other solutions we only look at the keys in dict_b
. But here we look in the union of both dictionaries.
Do with it as you please
def update_nested(dict_a, dict_b):
set_keys = set(dict_a.keys()).union(set(dict_b.keys()))
for k in set_keys:
v = dict_a.get(k)
if isinstance(v, dict):
new_dict = dict_b.get(k, None)
if new_dict:
update_nested(v, new_dict)
else:
new_value = dict_b.get(k, None)
if new_value:
dict_a[k] = new_value
mapStateToProps
, mapDispatchToProps
and connect
from react-redux
library provides a convenient way to access your state
and dispatch
function of your store. So basically connect is a higher order component, you can also think as a wrapper if this make sense for you. So every time your state
is changed mapStateToProps
will be called with your new state
and subsequently as you props
update component will run render function to render your component in browser. mapDispatchToProps
also stores key-values on the props
of your component, usually they take a form of a function. In such way you can trigger state
change from your component onClick
, onChange
events.
From docs:
const TodoListComponent = ({ todos, onTodoClick }) => (
<ul>
{todos.map(todo =>
<Todo
key={todo.id}
{...todo}
onClick={() => onTodoClick(todo.id)}
/>
)}
</ul>
)
const mapStateToProps = (state) => {
return {
todos: getVisibleTodos(state.todos, state.visibilityFilter)
}
}
const mapDispatchToProps = (dispatch) => {
return {
onTodoClick: (id) => {
dispatch(toggleTodo(id))
}
}
}
function toggleTodo(index) {
return { type: TOGGLE_TODO, index }
}
const TodoList = connect(
mapStateToProps,
mapDispatchToProps
)(TodoList)
Also make sure that you are familiar with React stateless functions and Higher-Order Components
The difference between link
and controller
comes into play when you want to nest directives in your DOM and expose API functions from the parent directive to the nested ones.
From the docs:
Best Practice: use controller when you want to expose an API to other directives. Otherwise use link.
Say you want to have two directives my-form
and my-text-input
and you want my-text-input
directive to appear only inside my-form
and nowhere else.
In that case, you will say while defining the directive my-text-input
that it requires a controller from the parent
DOM element using the require argument, like this: require: '^myForm'
. Now the controller from the parent element will be injected
into the link
function as the fourth argument, following $scope, element, attributes
. You can call functions on that controller and communicate with the parent directive.
Moreover, if such a controller is not found, an error will be raised.
There is no real need to use the link
function if one is defining the controller
since the $scope
is available on the controller
. Moreover, while defining both link
and controller
, one does need to be careful about the order of invocation of the two (controller
is executed before).
However, in keeping with the Angular way, most DOM manipulation and 2-way binding using $watchers
is usually done in the link
function while the API for children and $scope
manipulation is done in the controller
. This is not a hard and fast rule, but doing so will make the code more modular and help in separation of concerns (controller will maintain the directive
state and link
function will maintain the DOM
+ outside bindings).
TLDR; In addition to the accepted answer; One is implicit and one is explicit.
When the HTML you've written or had generated by an application/library/framework is read by your browser it will do it's best to interpret what your HTML meant (which can vary from browser to browser). When you use the HTML entity codes, you are being more specific to the browser. You are explicitly telling it you wish to display a character to the user (and not that you are just spacing your HTML for easier readability for the developer for instance).
To be more concrete, if the output HTML were:
<html>
<title>hello</title>
<body>
<p>
Tell me and I will forget. Teach me and I
may remember. Involve me and I will learn.
</p>
</body>
</html>
The browser would only render one space between all of these words (even the ones that have been indented for better developer readability.
If, however, you put the same thing and only changed the <p>
tag to:
<p>Hello There</p>
Then it would render the spaces, as you've instructed it more explicitly. There is some history of using these spaces for styling. This use has somewhat been diminished as CSS has matured. However, there are still valid uses for many of the HTML character entities: avoiding unexpectedly/unintentionally interpretation (e.g. if you wanted to display code). The w3 has a great page to show the other character codes.
For regular Windows users who are not skilled with computers, it is practically not possible to install and use extensions from outside the Chrome Web Store.
Users of other operating systems (Linux, Mac, Chrome OS) can easily install unpacked extensions (in developer mode).
Windows users can also load an unpacked extension, but they will always see an information bubble with "Disable developer mode extensions" when they start Chrome or open a new incognito window, which is really annoying. The only way for Windows users to use unpacked extensions without such dialogs is to switch to Chrome on the developer channel, by installing https://www.google.com/chrome/browser/index.html?extra=devchannel#eula.
Extensions can be loaded in unpacked mode by following the following steps:
chrome://extensions
(via omnibox or menu -> Tools -> Extensions).If you have a crx
file, then it needs to be extracted first. CRX files are zip files with a different header. Any capable zip program should be able to open it. If you don't have such a program, I recommend 7-zip.
These steps will work for almost every extension, except extensions that rely on their extension ID. If you use the previous method, you will get an extension with a random extension ID. If it is important to preserve the extension ID, then you need to know the public key of your CRX file and insert this in your manifest.json. I have previously given a detailed explanation on how to get and use this key at https://stackoverflow.com/a/21500707.
If the script only defines the functions and does nothing else, you can first execute the script within the context of the current shell using the source
or .
command and then simply call the function. See help source
for more information.
suppose you need a label with text customername than you can achive it using 2 ways
[1]@Html.Label("CustomerName")
[2]@Html.LabelFor(a => a.CustomerName) //strongly typed
2nd method used a property from your model. If your view implements a model then you can use the 2nd method.
More info please visit below link
http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2-strongly-typed-html-helpers.aspx
Below are the reasons of Error: redirect_uri_mismatch issue occurs :
Recommended to use domain URL
There are several good answers here that handle this error in a broad scope. I ran into a specific situation with Spring Security which had a quick, although probably not optimal, fix.
During user authorization (immediately after logging in and passing authentication) I was testing a user entity for a specific authority in a custom class that extends SimpleUrlAuthenticationSuccessHandler.
My user entity implements UserDetails and has a Set of lazy loaded Roles which threw the "org.hibernate.LazyInitializationException - could not initialize proxy - no Session" exception. Changing that Set from "fetch=FetchType.LAZY" to "fetch=FetchType.EAGER" fixed this for me.
ALTER TABLE MyTable MODIFY Col3 varchar(20) NULL;
Do we have java syntax corresponding to below process
val dfResults = dfSource.select(concat_ws(",",dfSource.columns.map(c => col(c)): _*))
I aware it's been some time since this question was posted, but I found really useful resource, which discusses usage of AntiForgeryToken and makes it less troublesome to use. It also provides jquery plugin for easily including antiforgery token in AJAX calls:
Anti-Forgery Request Recipes For ASP.NET MVC And AJAX
I'm not contributing much, but maybe someone will find it useful.
You can use the COALESCE function in MS SQL.
INSERT INTO t ( value ) VALUES( COALESCE(@value, 'something') )
Personally, I'm not crazy about this solution as it is a maintenance nightmare if you want to change the default value.
My preference would be Mitchel Sellers proposal, but that doesn't work in MS SQL. Can't speak to other SQL dbms.
if x
is a vector with raw scores then scale(x)
is a vector with standardized scores.
Or manually: (x-mean(x))/sd(x)
The below code worked for me in jQuery2.1.3
$("#topbar").animate('{height:"toggle"}');
Need not calculate your div height,padding,margin and borders. It will take care.
To fix, I deleted the app from Simulator.
I also ran Clean first.
I do not think anything orientation-related triggered it. The biggest thing that changed before this symptom started is that a Swift framework started calling NSLog
on worker threads instead of main thread.
If you have another variable also referring to the same dictionary, there is a big difference:
>>> d = {"stuff": "things"}
>>> d2 = d
>>> d = {}
>>> d2
{'stuff': 'things'}
>>> d = {"stuff": "things"}
>>> d2 = d
>>> d.clear()
>>> d2
{}
This is because assigning d = {}
creates a new, empty dictionary and assigns it to the d
variable. This leaves d2
pointing at the old dictionary with items still in it. However, d.clear()
clears the same dictionary that d
and d2
both point at.
Make a new div with whatever name (I will just use table-split) and give it a width, without adding content to it, while placing it between necessary divs that need to be separated.
You can add whatever width you find necessary. I just used 0.6% because it's what I needed for when I had to do this.
.table-split {_x000D_
display: table-cell;_x000D_
width: 0.6%_x000D_
}
_x000D_
<div class="table-split"></div>
_x000D_
waits milliseconds to check if the key is pressed, if pressed in that interval return its ascii value, otherwise it still -1
you don't need to set the width of header in css, just put the background image as center using this code:
background: url("images/logo.png") no-repeat top center;
or you can just use img
tag and put align="center"
in the div
If you face with the problem at the first time installing Android Studio on your computer.
mklink /D "c:\Android-Sdk" "C:\Users\ **YOUR-USERNAME** \AppData\Local\Android\sdk"
Go to "C:\Users\ YOUR-USERNAME \AppData\Local\" path and create Android\sdk folders inside it.
After that you can continue installation.
git show <commit>
To show what a commit did with stats:
git show <commit> --stat
To show commit log with differences introduced for each commit in a range:
git log -p <commit1> <commit2>
<commit>
?Each commit has a unique id we reference here as <commit>
. The unique id is an SHA-1 hash – a checksum of the content you’re storing plus a header. #TMI
If you don't know your <commit>
:
git log
to view the commit history
Find the commit you care about.
You can use float:left in DIV or use SPAN tag, like
<div style="width:100px;float:left"> First </div>
<div> Second </div>
<br/>
or
<span style="width:100px;"> First </span>
<span> Second </span>
<br/>
The git.exe from Github for windows is located in a path like C:\Users\<username>\AppData\Local\GitHub\PortableGit_<numbersandletters>\bin\git.exe
1 You have to replace <username>
and <numbersandletters>
to the actual situation on your system.
In Android Studio you can specify the path to the Git executable at File->Settings...->Version Control->Git->Path to Git executable
. Here you have to include the actual executable name. As an example, in my case the actual path is: C:\Users\dennis\AppData\Local\GitHub\PortableGit_69703d1db91577f4c666e767a6ca5ec50a48d243\bin\git.exe
Edit: Last git update has put the git.exe file in cmd\ folder instead of bin\ . so now the actual path will be as suggested in the comment below by al3xAndr3w.
C:\Users\<username>\AppData\Local\GitHub\PortableGit_<numbersandletters>\cmd\git.exe
You're using the this
keyword which actually refers to the "currently running instance of the object you're using", that is, you're invoking this.method2();
on your superclass, that is, it will call the method2() on the object you're using, which is the SubClass.
The HTML4 spec for the <input>
element specifies the following script events are available:
onfocus, onblur, onselect, onchange, onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup
here's an example that bind's to all these events and shows what's going on http://jsfiddle.net/pxfunc/zJ7Lf/
I think you can filter out which events are truly relevent to your situation and detect what the text value was before and after the event to determine a change
Note: if you want to disable ARC for many files, you have to:
-fno-objc-arc
My personal preference is libxml2. It's very easy to use but I never bothered to benchmark it, as I've only used it for configuration file parsing.
string sub = input.Substring(input.Length - 5);
try this below solution:
exclude:path.resolve(__dirname, "node_modules")
Your Problem were the slice declarations in your data structs
(except for Track
, they shouldn't be slices...). This was compounded by some rather goofy fieldnames in the fetched json file, which can be fixed via structtags, see godoc.
The code below parsed the json successfully. If you've further questions, let me know.
package main
import "fmt"
import "net/http"
import "io/ioutil"
import "encoding/json"
type Tracks struct {
Toptracks Toptracks_info
}
type Toptracks_info struct {
Track []Track_info
Attr Attr_info `json: "@attr"`
}
type Track_info struct {
Name string
Duration string
Listeners string
Mbid string
Url string
Streamable Streamable_info
Artist Artist_info
Attr Track_attr_info `json: "@attr"`
}
type Attr_info struct {
Country string
Page string
PerPage string
TotalPages string
Total string
}
type Streamable_info struct {
Text string `json: "#text"`
Fulltrack string
}
type Artist_info struct {
Name string
Mbid string
Url string
}
type Track_attr_info struct {
Rank string
}
func perror(err error) {
if err != nil {
panic(err)
}
}
func get_content() {
url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"
res, err := http.Get(url)
perror(err)
defer res.Body.Close()
decoder := json.NewDecoder(res.Body)
var data Tracks
err = decoder.Decode(&data)
if err != nil {
fmt.Printf("%T\n%s\n%#v\n",err, err, err)
switch v := err.(type){
case *json.SyntaxError:
fmt.Println(string(body[v.Offset-40:v.Offset]))
}
}
for i, track := range data.Toptracks.Track{
fmt.Printf("%d: %s %s\n", i, track.Artist.Name, track.Name)
}
}
func main() {
get_content()
}
If you look for POSIX compliant solution:
cd DirsRoot && find . -type f -print -o -name . -o -prune
-maxdepth is not POSIX compliant option.
Use SET
command in Windows CMD to temporarily set the default python for the current session.
SET PATH=C:\Program Files\Python 3.5
Here is another solution:
>>>list1=["C:\\","D:\\","E:\\","C:\\"]
>>>set1=set(list1)
>>>set1
set(['E:\\', 'D:\\', 'C:\\'])
In this code I have used the set method in order to turn it into a set and then it removed all duplicate values from the list
With Okio:
String result = Okio.buffer(Okio.source(inputStream)).readUtf8();
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.
The example code above was really helpful to me, however (as has been hinted at above), I think you need to use NSMutableURLRequest
rather than NSURLRequest
. In its current form, I couldn't get it to respond to the setHTTPMethod
call. Changing the type fixed things right up.
float
and double
don't store decimal places. They store binary places: float
is (assuming IEEE 754) 24 significant bits (7.22 decimal digits) and double is 53 significant bits (15.95 significant digits).
Converting from double
to float
will give you the closest possible float
, so rounding won't help you. Goining the other way may give you "noise" digits in the decimal representation.
#include <stdio.h>
int main(void) {
double orig = 12345.67;
float f = (float) orig;
printf("%.17g\n", f); // prints 12345.669921875
return 0;
}
To get a double
approximation to the nice decimal value you intended, you can write something like:
double round_to_decimal(float f) {
char buf[42];
sprintf(buf, "%.7g", f); // round to 7 decimal digits
return atof(buf);
}
You can do the following:
Example using PHP (you can do this in any language of your choice):
Server:
<?php $years = range(1900, strftime("%Y", time())); ?>
HTML
<select>
<option>Select Year</option>
<?php foreach($years as $year) : ?>
<option value="<?php echo $year; ?>"><?php echo $year; ?></option>
<?php endforeach; ?>
</select>
As an added benefit, this works has a browser compatibility of a 100% ;-)
There are several ways. One way is to use save()
to save the exact object. e.g. for data frame foo
:
save(foo,file="data.Rda")
Then load it with:
load("data.Rda")
You could also use write.table()
or something like that to save the table in plain text, or dput()
to obtain R code to reproduce the table.
Once you have cloned the repo, you have everything: you can then hg up branchname
or hg up tagname
to update your working copy.
UP: hg up
is a shortcut of hg update
, which also has hg checkout
alias for people with git
habits.
This expression will force the first letter to be alphabetic and the remaining characters to be alphanumeric or any of the following special characters: @,#,%,&,*
^[A-Za-z][A-Za-z0-9@#%&*]*$
You can also use following Node.js module to do it with ease:
https://www.npmjs.com/package/mssql-to-csv
var mssqlExport = require('mssql-to-csv')
// All config options supported by https://www.npmjs.com/package/mssql
var dbconfig = {
user: 'username',
password: 'pass',
server: 'servername',
database: 'dbname',
requestTimeout: 320000,
pool: {
max: 20,
min: 12,
idleTimeoutMillis: 30000
}
};
var options = {
ignoreList: ["sysdiagrams"], // tables to ignore
tables: [], // empty to export all the tables
outputDirectory: 'somedir',
log: true
};
mssqlExport(dbconfig, options).then(function(){
console.log("All done successfully!");
process.exit(0);
}).catch(function(err){
console.log(err.toString());
process.exit(-1);
});
This one-liner works, for all types of objects, as long as they are in globals()
dict, which they should be:
def name_of_global_obj(xx):
return [objname for objname, oid in globals().items()
if id(oid)==id(xx)][0]
or, equivalently:
def name_of_global_obj(xx):
for objname, oid in globals().items():
if oid is xx:
return objname
Return the contents of this :class:.KeyedTuple
as a dictionary
In [46]: result = aggregate_events[0]
In [47]: type(result)
Out[47]: sqlalchemy.util._collections.result
In [48]: def to_dict(query_result=None):
...: cover_dict = {key: getattr(query_result, key) for key in query_result.keys()}
...: return cover_dict
...:
...:
In [49]: to_dict(result)
Out[49]:
{'calculate_avg': None,
'calculate_max': None,
'calculate_min': None,
'calculate_sum': None,
'dataPointIntID': 6,
'data_avg': 10.0,
'data_max': 10.0,
'data_min': 10.0,
'data_sum': 60.0,
'deviceID': u'asas',
'productID': u'U7qUDa',
'tenantID': u'CvdQcYzUM'}
Well you can remove the third calendar instance.
GregorianCalendar c1 = new GregorianCalendar();
GregorianCalendar c2 = new GregorianCalendar();
c1.set(2000, 1, 1);
c2.set(2010,1, 1);
c2.add(GregorianCalendar.MILLISECOND, -1 * c1.getTimeInMillis());
I tried this and it worked:
Object obj = 10;
String str = obj.toString();
double d = Double.valueOf(str).doubleValue();
I'm didn't totally follow, but to add an action listener, you just call addActionListener (from Abstract Button). If this doesn't totally answer your question, can you provide some more details?
If you want to convert a single VARBINARY
value into VARCHAR
(STRING
) you can do by declaring a variable like this:
DECLARE @var VARBINARY(MAX)
SET @var = 0x21232F297A57A5A743894A0E4A801FC3
SELECT CAST(@var AS VARCHAR(MAX))
If you are trying to select from table column then you can do like this:
SELECT CAST(myBinaryCol AS VARCHAR(MAX))
FROM myTable
running the following worked for me
npm audit fix --force
df.filter(regex='[A-CEG-I]') # does NOT depend on the column order
Note that any regular expression is allowed here, so this approach can be very general. E.g. if you wanted all columns starting with a capital or lowercase "A" you could use: df.filter(regex='^[Aa]')
df[ list(df.loc[:,'A':'C']) + ['E'] + list(df.loc[:,'G':'I']) ]
Note that unlike the label-based method, this only works if your columns are alphabetically sorted. This is not necessarily a problem, however. For example, if your columns go ['A','C','B']
, then you could replace 'A':'C'
above with 'A':'B'
.
And for completeness, you always have the option shown by @Magdalena of simply listing each column individually, although it could be much more verbose as the number of columns increases:
df[['A','B','C','E','G','H','I']] # does NOT depend on the column order
A B C E G H I
0 -0.814688 -1.060864 -0.008088 2.697203 -0.763874 1.793213 -0.019520
1 0.549824 0.269340 0.405570 -0.406695 -0.536304 -1.231051 0.058018
2 0.879230 -0.666814 1.305835 0.167621 -1.100355 0.391133 0.317467
Here is another REST-only working example for Google Service Accounts accessing G Suite Users and Groups, authenticating through JWT. This was only possible through reflection of Google libraries, since Google documentation of these APIs are beyond terrible. Anyone used to code in MS technologies will have a hard time figuring out how everything goes together in Google services.
$iss = "<name>@<serviceaccount>.iam.gserviceaccount.com"; # The email address of the service account.
$sub = "[email protected]"; # The user to impersonate (required).
$scope = "https://www.googleapis.com/auth/admin.directory.user.readonly https://www.googleapis.com/auth/admin.directory.group.readonly";
$certPath = "D:\temp\mycertificate.p12";
$grantType = "urn:ietf:params:oauth:grant-type:jwt-bearer";
# Auxiliary functions
function UrlSafeEncode([String] $Data) {
return $Data.Replace("=", [String]::Empty).Replace("+", "-").Replace("/", "_");
}
function UrlSafeBase64Encode ([String] $Data) {
return (UrlSafeEncode -Data ([Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($Data))));
}
function KeyFromCertificate([System.Security.Cryptography.X509Certificates.X509Certificate2] $Certificate) {
$privateKeyBlob = $Certificate.PrivateKey.ExportCspBlob($true);
$key = New-Object System.Security.Cryptography.RSACryptoServiceProvider;
$key.ImportCspBlob($privateKeyBlob);
return $key;
}
function CreateSignature ([Byte[]] $Data, [System.Security.Cryptography.X509Certificates.X509Certificate2] $Certificate) {
$sha256 = [System.Security.Cryptography.SHA256]::Create();
$key = (KeyFromCertificate $Certificate);
$assertionHash = $sha256.ComputeHash($Data);
$sig = [Convert]::ToBase64String($key.SignHash($assertionHash, "2.16.840.1.101.3.4.2.1"));
$sha256.Dispose();
return $sig;
}
function CreateAssertionFromPayload ([String] $Payload, [System.Security.Cryptography.X509Certificates.X509Certificate2] $Certificate) {
$header = @"
{"alg":"RS256","typ":"JWT"}
"@;
$assertion = New-Object System.Text.StringBuilder;
$assertion.Append((UrlSafeBase64Encode $header)).Append(".").Append((UrlSafeBase64Encode $Payload)) | Out-Null;
$signature = (CreateSignature -Data ([System.Text.Encoding]::ASCII.GetBytes($assertion.ToString())) -Certificate $Certificate);
$assertion.Append(".").Append((UrlSafeEncode $signature)) | Out-Null;
return $assertion.ToString();
}
$baseDateTime = New-Object DateTime(1970, 1, 1, 0, 0, 0, [DateTimeKind]::Utc);
$timeInSeconds = [Math]::Truncate([DateTime]::UtcNow.Subtract($baseDateTime).TotalSeconds);
$jwtClaimSet = @"
{"scope":"$scope","email_verified":false,"iss":"$iss","sub":"$sub","aud":"https://oauth2.googleapis.com/token","exp":$($timeInSeconds + 3600),"iat":$timeInSeconds}
"@;
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($certPath, "notasecret", [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable);
$jwt = CreateAssertionFromPayload -Payload $jwtClaimSet -Certificate $cert;
# Retrieve the authorization token.
$authRes = Invoke-WebRequest -Uri "https://oauth2.googleapis.com/token" -Method Post -ContentType "application/x-www-form-urlencoded" -UseBasicParsing -Body @"
assertion=$jwt&grant_type=$([Uri]::EscapeDataString($grantType))
"@;
$authInfo = ConvertFrom-Json -InputObject $authRes.Content;
$resUsers = Invoke-WebRequest -Uri "https://www.googleapis.com/admin/directory/v1/users?domain=<required_domain_name_dont_trust_google_documentation_on_this>" -Method Get -Headers @{
"Authorization" = "$($authInfo.token_type) $($authInfo.access_token)"
}
$users = ConvertFrom-Json -InputObject $resUsers.Content;
$users.users | ft primaryEmail, isAdmin, suspended;
Use index notation with the key.
Object.keys(obj).forEach(function(k){
console.log(k + ' - ' + obj[k]);
});
In Tomcat 7.0 Windows Service Installer Version.There is not catalina.bat in /bin . So you need open Tomcat7w.exe in /bin and add blow JVM argument
-XX:PermSize=256m -XX:MaxPermSize=512m
on Java Option in Java Tab, like this. You also add other options.
Another, if you use IntellijIDEA you need add JVM argument in Server Configurations,like this.
Here's a gist I discovered for real-time charts in ChartJS:
https://gist.github.com/arisetyo/5985848
ChartJS looks like it's simple to use and looks nice.
Also there's FusionCharts, a more sophisticated library for enterprise use, with a demo of real time here:
http://www.fusioncharts.com/explore/real-time-charts
EDIT I also started using Rickshaw for real time graphs and it's easy to use and pretty customizable: http://code.shutterstock.com/rickshaw/
As pointed by Larcho, starting from API level 10, you can use BitmapRegionDecoder
to load specific regions from an image and with that, you can accomplish to show a large image in high resolution by allocating in memory just the needed regions. I've recently developed a lib that provides the visualisation of large images with touch gesture handling. The source code and samples are available here.
This is in no way specific to std::unique_ptr
, but applies to any class that is movable. It's guaranteed by the language rules since you are returning by value. The compiler tries to elide copies, invokes a move constructor if it can't remove copies, calls a copy constructor if it can't move, and fails to compile if it can't copy.
If you had a function that accepts std::unique_ptr
as an argument you wouldn't be able to pass p to it. You would have to explicitly invoke move constructor, but in this case you shouldn't use variable p after the call to bar()
.
void bar(std::unique_ptr<int> p)
{
// ...
}
int main()
{
unique_ptr<int> p = foo();
bar(p); // error, can't implicitly invoke move constructor on lvalue
bar(std::move(p)); // OK but don't use p afterwards
return 0;
}
Make sure that you alter the system and enable restricted session before you kill them or they will quickly log back into the database before you get your work completed.
Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.
That option could be useful when copying very large files over a potentially unstable connection.
Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.
Maybe it's because I am not using Core yet. My project didn't have a LaunchSettings.json file but that did prompt me to look in the project properties. I found it under the Web tab and simply changed the project url:
Basically, you need to catch the OperationCanceledException
and check the state of the cancellation token that was passed to SendAsync
(or GetAsync
, or whatever HttpClient
method you're using):
IsCancellationRequested
is true), it means the request really was canceledOf course, this isn't very convenient... it would be better to receive a TimeoutException
in case of timeout. I propose a solution here based on a custom HTTP message handler: Better timeout handling with HttpClient
Many thanks to @Ciro Santilli answer! I found that his choice for boundary is quite "unhappy" because all of thoose hyphens: in fact, as @Fake Name commented, when you are using your boundary inside request it comes with two more hyphens on front:
Example:
POST / HTTP/1.1
HOST: host.example.com
Cookie: some_cookies...
Connection: Keep-Alive
Content-Type: multipart/form-data; boundary=12345
--12345
Content-Disposition: form-data; name="sometext"
some text that you wrote in your html form ...
--12345
Content-Disposition: form-data; name="name_of_post_request" filename="filename.xyz"
content of filename.xyz that you upload in your form with input[type=file]
--12345
Content-Disposition: form-data; name="image" filename="picture_of_sunset.jpg"
content of picture_of_sunset.jpg ...
--12345--
I found on this w3.org page that is possible to incapsulate multipart/mixed header in a multipart/form-data, simply choosing another boundary string inside multipart/mixed and using that one to incapsulate data. At the end, you must "close" all boundary used in FILO order to close the POST request (like:
POST / HTTP/1.1
...
Content-Type: multipart/form-data; boundary=12345
--12345
Content-Disposition: form-data; name="sometext"
some text sent via post...
--12345
Content-Disposition: form-data; name="files"
Content-Type: multipart/mixed; boundary=abcde
--abcde
Content-Disposition: file; file="picture.jpg"
content of jpg...
--abcde
Content-Disposition: file; file="test.py"
content of test.py file ....
--abcde--
--12345--
Take a look at the link above.
User: Access to resource of the database. Like a key to enter a house.
Schema: Collection of information about database objects. Like Index in your book which contains the short information about the chapter.
To use both is a nice answer; it's not a question of either or.
The advantage of using both is that the CSS will hide the element immediately when the page loads. The jQuery .hide will flash the element for a quarter of a second then hide it.
In the case when we want to have the element not shown when the page loads we can use CSS and set display:none & use the jQuery .hide(). If we plan to toggle the element we can use jQuery toggle.
Its easy to switch between prefork or worker mpm in Apache 2.4 on RHEL7
Check MPM type by executing
sudo httpd -V
Server version: Apache/2.4.6 (Red Hat Enterprise Linux)
Server built: Jul 26 2017 04:45:44
Server's Module Magic Number: 20120211:24
Server loaded: APR 1.4.8, APR-UTIL 1.5.2
Compiled using: APR 1.4.8, APR-UTIL 1.5.2
Architecture: 64-bit
Server MPM: prefork
threaded: no
forked: yes (variable process count)
Server compiled with....
-D APR_HAS_SENDFILE
-D APR_HAS_MMAP
-D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
-D APR_USE_SYSVSEM_SERIALIZE
-D APR_USE_PTHREAD_SERIALIZE
-D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
-D APR_HAS_OTHER_CHILD
-D AP_HAVE_RELIABLE_PIPED_LOGS
-D DYNAMIC_MODULE_LIMIT=256
-D HTTPD_ROOT="/etc/httpd"
-D SUEXEC_BIN="/usr/sbin/suexec"
-D DEFAULT_PIDLOG="/run/httpd/httpd.pid"
-D DEFAULT_SCOREBOARD="logs/apache_runtime_status"
-D DEFAULT_ERRORLOG="logs/error_log"
-D AP_TYPES_CONFIG_FILE="conf/mime.types"
-D SERVER_CONFIG_FILE="conf/httpd.conf"
Now to change MPM edit following file and uncomment required MPM
/etc/httpd/conf.modules.d/00-mpm.conf
# Select the MPM module which should be used by uncommenting exactly
# one of the following LoadModule lines:
# prefork MPM: Implements a non-threaded, pre-forking web server
# See: http://httpd.apache.org/docs/2.4/mod/prefork.html
LoadModule mpm_prefork_module modules/mod_mpm_prefork.so
# worker MPM: Multi-Processing Module implementing a hybrid
# multi-threaded multi-process web server
# See: http://httpd.apache.org/docs/2.4/mod/worker.html
#
#LoadModule mpm_worker_module modules/mod_mpm_worker.so
# event MPM: A variant of the worker MPM with the goal of consuming
# threads only for connections with active processing
# See: http://httpd.apache.org/docs/2.4/mod/event.html
#
#LoadModule mpm_event_module modules/mod_mpm_event.so
If you want to add a sourceSet for testing in addition to all the existing ones, within a module regardless of the active flavor:
sourceSets {
test {
java.srcDirs += [
'src/customDir/test/kotlin'
]
print(java.srcDirs) // Clean
}
}
Pay attention to the operator +=
and if you want to run integration tests change test
to androidTest
.
GL
$('div').attr('class', function(i, c){
return c.replace(/(^|\s)color-\S+/g, '');
});
One of my favorites is realpath foo
realpath - return the canonicalized absolute pathname realpath expands all symbolic links and resolves references to '/./', '/../' and extra '/' characters in the null terminated string named by path and stores the canonicalized absolute pathname in the buffer of size PATH_MAX named by resolved_path. The resulting path will have no symbolic link, '/./' or '/../' components.
Sure - just don't use the Sun base64 encoder/decoder. There are plenty of other options available, including Apache Codec or this public domain implementation.
Then read why you shouldn't use sun.* packages.
Late to the party on this question, but this is even easier:
$('#myForm').submit(function() {
// Get all the forms elements and their values in one step
var values = $(this).serialize();
});
Since i had problems with the other solutions (especially to get it working in all browsers, for example edge doesn't recognize "*" as a valid value for "Access-Control-Allow-Methods"), i had to use a custom filter component, which in the end worked for me and did exactly what i wanted to achieve.
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods",
"ACL, CANCELUPLOAD, CHECKIN, CHECKOUT, COPY, DELETE, GET, HEAD, LOCK, MKCALENDAR, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, REPORT, SEARCH, UNCHECKOUT, UNLOCK, UPDATE, VERSION-CONTROL");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Key, Authorization");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
public void init(FilterConfig filterConfig) {
// not needed
}
public void destroy() {
//not needed
}
}
I found I way to flip only the background not whole element after seeing a clue to flip in Alex's answer. Thanks alex for your answer
HTML
<div class="prev"><a href="">Previous</a></div>
<div class="next"><a href="">Next</a></div>
CSS
.next a, .prev a {
width:200px;
background:#fff
}
.next {
float:left
}
.prev {
float:right
}
.prev a:before, .next a:before {
content:"";
width:16px;
height:16px;
margin:0 5px 0 0;
background:url(http://i.stack.imgur.com/ah0iN.png) no-repeat 0 0;
display:inline-block
}
.next a:before {
margin:0 0 0 5px;
transform:scaleX(-1);
}
See example here http://jsfiddle.net/qngrf/807/
It could be dependent upon what is supported by the module you are trying to compile. If your makefile is generated by using autotools, use:
--prefix=<myinstalldir>
when running the ./configure
some packages allow you to also override when running:
make prefix=<myinstalldir>
however, if your not using ./configure, only way to know for sure is to open up the makefile and check. It should be one of the first few variables at the top.
Well, as it was said before, you can't GROUP
by literals, I think that you are confused cause you can ORDER
by 1, 2, 3. When you use functions as your columns, you need to GROUP by the same expression. Besides, the HAVING clause is wrong, you can only use what is in the agreggations. In this case, your query should be like this:
SELECT
LEFT(SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000), PATINDEX('%[^0-9]%', SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000))-1),
qvalues.name,
qvalues.compound,
MAX(qvalues.rid) MaxRid
FROM batchinfo join qvalues
ON batchinfo.rowid=qvalues.rowid
WHERE LEN(datapath)>4
GROUP BY
LEFT(SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000), PATINDEX('%[^0-9]%', SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000))-1),
qvalues.name,
qvalues.compound
Unlike it's most popular commercial competitor, numpy pretty much from the outset is about "arbitrary-dimensional" arrays, that's why the core class is called ndarray
. You can check the dimensionality of a numpy array using the .ndim
property. The .shape
property is a tuple of length .ndim
containing the length of each dimensions. Currently, numpy can handle up to 32 dimensions:
a = np.ones(32*(1,))
a
# array([[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ 1.]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]])
a.shape
# (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
a.ndim
# 32
If a numpy array happens to be 2d like your second example, then it's appropriate to think about it in terms of rows and columns. But a 1d array in numpy is truly 1d, no rows or columns.
If you want something like a row or column vector you can achieve this by creating a 2d array with one of its dimensions equal to 1.
a = np.array([[1,2,3]]) # a 'row vector'
b = np.array([[1],[2],[3]]) # a 'column vector'
# or if you don't want to type so many brackets:
b = np.array([[1,2,3]]).T
Use this code where str is your JSON string:
NSError *err = nil;
NSArray *arr =
[NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingMutableContainers
error:&err];
// access the dictionaries
NSMutableDictionary *dict = arr[0];
for (NSMutableDictionary *dictionary in arr) {
// do something using dictionary
}
According to the virtualenv pep at http://www.python.org/dev/peps/pep-0405/#specification you can just use sys.prefix
instead os.environ['VIRTUAL_ENV']
.
the sys.real_prefix
does not exist in my virtualenv and same with sys.base_prefix
.
I generally consider it bad practice to mix java code into jsps/tag files. Using 'eq' should do the trick :
<c:if test="${dp.Status eq 'OLD'}">
...
</c:if>
To use in Eloquent. Add on top of your model
protected $table = 'table_name as alias'
//table_name should be exact as in your database
..then use in your query like
ModelName::query()->select(alias.id, alias.name)
my_string.replaceAll("\\p{C}", "?");
See more about Unicode regex. java.util.regexPattern
/String.replaceAll
supports them.
Also, what helped me understand this particular scenario that you described is the Promise API documentation, specifically where it explains how the promised returned by the then
method will be resolved differently depending on what the handler fn returns:
if the handler function:
- returns a value, the promise returned by then gets resolved with the returned value as its value;
- throws an error, the promise returned by then gets rejected with the thrown error as its value;
- returns an already resolved promise, the promise returned by then gets resolved with that promise's value as its value;
- returns an already rejected promise, the promise returned by then gets rejected with that promise's value as its value.
- returns another pending promise object, the resolution/rejection of the promise returned by then will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the value of the promise returned by then will be the same as the value of the promise returned by the handler.
aString = "hello world"
aString.startswith("hello")
More info about startswith
.
test.html
is will be helpful for how to use VLC WebAPI.
test.html
is located in the directory where VLC was installed.
e.g. C:\Program Files (x86)\VideoLAN\VLC\sdk\activex\test.html
The following code is a quote from the test.html
.
HTML:
<object classid="clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921" width="640" height="360" id="vlc" events="True">
<param name="MRL" value="" />
<param name="ShowDisplay" value="True" />
<param name="AutoLoop" value="False" />
<param name="AutoPlay" value="False" />
<param name="Volume" value="50" />
<param name="toolbar" value="true" />
<param name="StartTime" value="0" />
<EMBED pluginspage="http://www.videolan.org"
type="application/x-vlc-plugin"
version="VideoLAN.VLCPlugin.2"
width="640"
height="360"
toolbar="true"
loop="false"
text="Waiting for video"
name="vlc">
</EMBED>
</object>
JavaScript:
You can get vlc object from getVLC()
.
It works on IE 10 and Chrome.
function getVLC(name)
{
if (window.document[name])
{
return window.document[name];
}
if (navigator.appName.indexOf("Microsoft Internet")==-1)
{
if (document.embeds && document.embeds[name])
return document.embeds[name];
}
else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
{
return document.getElementById(name);
}
}
var vlc = getVLC("vlc");
// do something.
// e.g. vlc.playlist.play();
The data returned by the JSON is in json format : which is simply an arrays of values. Thats why you are seeing [object Object],[object Object],[object Object].
You have to iterate through that values to get actuall value. Like the following
jQuery provides $.each() for iterations, so you could also do this:
$.getJSON("url_with_json_here", function(data){
$.each(data, function (linktext, link) {
console.log(linktext);
console.log(link);
});
});
Now just create an Hyperlink using that info.
Am afraid this question has been answered a few times, Pls take a look at the following if it's related
In sqlserver
DECLARE @p_date DATE
SELECT *
FROM table1
WHERE column_dateTime=@p_date
In C# Pass the short string of date value using ToShortDateString() function. sample: DateVariable.ToShortDateString();
If its only about ignoring the first two fields and if you don't want a space when masking those fields (like some of the answers above do) :
awk '{gsub($1" "$2" ",""); print;}' file
Possible and easiest one-line solution is to use:
file_get_contents("YOUR_REQUESTED_FILE");
Or equivavelt for example CURL.
You should try this syntax - assuming you want to have @OrderID
as a parameter for your stored procedure:
CREATE PROCEDURE dbo.YourStoredProcNameHere
@OrderID INT
AS
BEGIN
DECLARE @OrderItemID AS INT
DECLARE @AppointmentID AS INT
DECLARE @PurchaseOrderID AS INT
DECLARE @PurchaseOrderItemID AS INT
DECLARE @SalesOrderID AS INT
DECLARE @SalesOrderItemID AS INT
SELECT @OrderItemID = OrderItemID
FROM [OrderItem]
WHERE OrderID = @OrderID
SELECT @AppointmentID = AppoinmentID
FROM [Appointment]
WHERE OrderID = @OrderID
SELECT @PurchaseOrderID = PurchaseOrderID
FROM [PurchaseOrder]
WHERE OrderID = @OrderID
END
OF course, that only works if you're returning exactly one value (not multiple values!)
for n in range(6,0,-1)
This would give you 6,5,4,3,2,1
As for
for n in reversed(range(0,6))
would give you 5,4,3,2,1,0
What everyone is forgeting is explaining WHY this happens.
A Char, is basically an integer, but with a pointer in the ASCII table. All characters have a corresponding integer value as you can clearly see when trying to parse it.
Pranay has clearly a different character set, thats why HIS code doesnt work. the only way is
int val = '1' - '0';
because this looks up the integer value in the table of '0'
which is then the 'base value'
subtracting your number in char format from this will give you the original number.
check the @viewchild
in your .ts
@ViewChild('ngOtpInput') ngOtpInput:any;
set the below code in your method were you want the fields to be clear.
yourMethod(){
this.ngOtpInput.setValue(yourValue);
}
As of python 3.2, using only standard library functions:
u_tm = datetime.datetime.utcfromtimestamp(0)
l_tm = datetime.datetime.fromtimestamp(0)
l_tz = datetime.timezone(l_tm - u_tm)
t = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=l_tz)
str(t)
'2009-07-10 18:44:59.193982-07:00'
Just need to use l_tm - u_tm
or u_tm - l_tm
depending whether you want to show as + or - hours from UTC. I am in MST, which is where the -07 comes from. Smarter code should be able to figure out which way to subtract.
And only need to calculate the local timezone once. That is not going to change. At least until you switch from/to Daylight time.
Use checkbox and change the input type accordingly.
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int start,end;
Log.i("inside checkbox chnge",""+isChecked);
if(!isChecked){
start=passWordEditText.getSelectionStart();
end=passWordEditText.getSelectionEnd();
passWordEditText.setTransformationMethod(new PasswordTransformationMethod());;
passWordEditText.setSelection(start,end);
}else{
start=passWordEditText.getSelectionStart();
end=passWordEditText.getSelectionEnd();
passWordEditText.setTransformationMethod(null);
passWordEditText.setSelection(start,end);
}
}
After writing to external storage, some file managers don't see the file right away. This can be confusing if a user thinks they copied something to the SD card, but then can't find it there. So after you copy the file, run the following code to notify file managers of its presence.
MediaScannerConnection.scanFile(
context,
new String[]{myFile.getAbsolutePath()},
null,
null);
See the documentation and this answer for more.
If you want to present a new view in the same storyboard,
In CurrentViewController.m,
#import "YourViewController.h"
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
YourViewController *viewController = (YourViewController *)[storyboard instantiateViewControllerWithIdentifier:@"YourViewControllerIdentifier"];
[self presentViewController:viewController animated:YES completion:nil];
To set identifier to a view controller, Open MainStoryBoard.storyboard. Select YourViewController View-> Utilities -> ShowIdentityInspector. There you can specify the identifier.
You can use StringBuffer
or StringBuilder
for this. Both are for dynamic string manipulation. StringBuffer
is thread-safe where as StringBuilder
is not.
Use StringBuffer
in a multi-thread environment. But if it is single threaded StringBuilder
is recommended and it is much faster than StringBuffer
.
You can put in this directory your Xampp control panel shortcut
it will work fine (it will automatically start after windows startup) as @wajahat-hashmi answered above:
C:\Users\User-Name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
About aditional windows script or programs that we need to run automatically...
I needed to create some additional scripts to initialize some windows services. If someone has the same need you can put in that same directory, they will all run right after windows startup.
For me, Xampp auto start and other scripts and shortcuts worked fine in windows 8.1, I think it will work fine in any windows version.
I hope it works well for anyone who has the same need.
Here's another way: this adds a circle to the current axes, plot or image or whatever :
from matplotlib.patches import Circle # $matplotlib/patches.py
def circle( xy, radius, color="lightsteelblue", facecolor="none", alpha=1, ax=None ):
""" add a circle to ax= or current axes
"""
# from .../pylab_examples/ellipse_demo.py
e = Circle( xy=xy, radius=radius )
if ax is None:
ax = pl.gca() # ax = subplot( 1,1,1 )
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_edgecolor( color )
e.set_facecolor( facecolor ) # "none" not None
e.set_alpha( alpha )
(The circles in the picture get squashed to ellipses because imshow aspect="auto"
).
Tested and working!
with https, user & password
<?php
//Data, connection, auth
$dataFromTheForm = $_POST['fieldName']; // request data from the form
$soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
$soapUser = "username"; // username
$soapPassword = "password"; // password
// xml post structure
$xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
<PRICE>'.$dataFromTheForm.'</PRICE>
</GetItemPrice >
</soap:Body>
</soap:Envelope>'; // data from the form, e.g. some ID number
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice",
"Content-length: ".strlen($xml_post_string),
); //SOAPAction: your op URL
$url = $soapUrl;
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// converting
$response = curl_exec($ch);
curl_close($ch);
// converting
$response1 = str_replace("<soap:Body>","",$response);
$response2 = str_replace("</soap:Body>","",$response1);
// convertingc to XML
$parser = simplexml_load_string($response2);
// user $parser to get your data out of XML response and to display it.
?>
If your columns should not contain NULL
values, you need to define the columns as NOT NULL
as well, otherwise the passed in NULL
will be used instead of the default and not produce an error.
If you don't pass in any value to these fields (which requires you to specify the fields that you do want to use), the defaults will be used:
INSERT INTO
table1 (field1, field3)
VALUES (5,10)
The solution at my end was to explicitly add a JoinColumn annotation like this:
@JoinColumn(name="mapping_type_id")
The column name is usually the table name + "_id" if there is an id field. Additionally, keep in mind which field it should be based on the relationship, OneToMany or ManyToOne.
Hope this helps.
For me the simple solution works to set cookies in HttpRequestMessage object.
protected async Task<HttpResponseMessage> SendRequest(HttpRequestMessage requestMessage, CancellationToken cancellationToken = default(CancellationToken))
{
requestMessage.Headers.Add("Cookie", $"<Cookie Name 1>=<Cookie Value 1>;<Cookie Name 2>=<Cookie Value 2>");
return await _httpClient.SendAsync(requestMessage, cancellationToken).ConfigureAwait(false);
}
I followed these steps (for Mac).
In /etc/ssh/sshd_config
change
#ChallengeResponseAuthentication yes
#PasswordAuthentication yes
to
ChallengeResponseAuthentication no
PasswordAuthentication no
Now generate the RSA key:
ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa
(For me an RSA key worked. A DSA key did not work.)
A private key will be generated in ~/.ssh/id_rsa
along with ~/.ssh/id_rsa.pub
(public key).
Now move to the .ssh folder: cd ~/.ssh
Enter rm -rf authorized_keys
(sometimes multiple keys lead to an error).
Enter vi authorized_keys
Enter :wq
to save this empty file
Enter cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
Restart the SSH:
sudo launchctl stop com.openssh.sshd
sudo launchctl start com.openssh.sshd
If you revise your regular expression like this:
drupal-6.14/(?=sites(?!/all|/default)).*
^^
...then it will match all inputs that contain drupal-6.14/
followed by sites
followed by anything other than /all
or /default
. For example:
drupal-6.14/sites/foo
drupal-6.14/sites/bar
drupal-6.14/sitesfoo42
drupal-6.14/sitesall
Changing ?=
to ?!
to match your original regex simply negates those matches:
drupal-6.14/(?!sites(?!/all|/default)).*
^^
So, this simply means that drupal-6.14/
now cannot be followed by sites
followed by anything other than /all
or /default
. So now, these inputs will satisfy the regex:
drupal-6.14/sites/all
drupal-6.14/sites/default
drupal-6.14/sites/all42
But, what may not be obvious from some of the other answers (and possibly your question) is that your regex will also permit other inputs where drupal-6.14/
is followed by anything other than sites
as well. For example:
drupal-6.14/foo
drupal-6.14/xsites
Conclusion: So, your regex basically says to include all subdirectories of drupal-6.14
except those subdirectories of sites
whose name begins with anything other than all
or default
.
You may use Request.Cookies collection to read the cookies.
if(Request.Cookies["key"]!=null)
{
var value=Request.Cookies["key"].Value;
}
There is big difference between dot (".")
and text()
:-
The dot (".")
in XPath
is called the "context item expression" because it refers to the context item. This could be match with a node (such as an element
, attribute
, or text node
) or an atomic value (such as a string
, number
, or boolean
). While text()
refers to match only element text
which is in string
form.
The dot (".")
notation is the current node in the DOM. This is going to be an object of type Node while Using the XPath
function text() to get the text for an element only gets the text up to the first inner element. If the text you are looking for is after the inner element you must use the current node to search for the string and not the XPath
text() function.
For an example :-
<a href="something.html">
<img src="filename.gif">
link
</a>
Here if you want to find anchor a
element by using text link, you need to use dot (".")
. Because if you use //a[contains(.,'link')]
it finds the anchor a
element but if you use //a[contains(text(),'link')]
the text()
function does not seem to find it.
Hope it will help you..:)
If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40)
.
If you use pyplot
programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40)
or afterwards with ax.yaxis.label.set_size(40)
.
You can use rownum :
SELECT * FROM table WHERE rownum > 10 and rownum <= 20
var start = +new Date();
var counter = 0;
for(var i = 1; i < LIMIT; i++){
++counter;
db.users.save({id : i, name : "MongoUser [" + i + "]"}, function(err, saved) {
if( err || !saved ) console.log("Error");
else console.log("Saved");
if (--counter === 0)
{
var end = +new Date();
console.log("all users saved in " + (end-start) + " milliseconds");
}
});
}
Dim rows() AS DataRow = DataTable.Select("ColumnName1 = 'value3'")
If rows.Count > 0 Then
searchedValue = rows(0).Item("ColumnName2")
End If
With FirstOrDefault
:
Dim row AS DataRow = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault()
If Not row Is Nothing Then
searchedValue = row.Item("ColumnName2")
End If
In C#:
var row = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault();
if (row != null)
searchedValue = row["ColumnName2"];
This can't be done in chrome now to avoid spamming, refer to javascript onbeforeunload not showing custom message for more details.
The best method is to wrap the span inside a button and disable the button
$("#buttonD").click(function(){_x000D_
alert("button clicked");_x000D_
})_x000D_
_x000D_
$("#buttonS").click(function(){_x000D_
alert("span clicked");_x000D_
})
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
_x000D_
<button class="btn btn-success" disabled="disabled" id="buttonD">_x000D_
<span>Disabled button</span>_x000D_
</button>_x000D_
_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
<span class="btn btn-danger" disabled="disabled" id="buttonS">Disabled span</span>
_x000D_
You can't declare an extern
local method inside of a method, or any other method with an attribute. Move your DLL import into the class:
using System.Runtime.InteropServices;
public class WindowHandling
{
[DllImport("User32.dll")]
public static extern int SetForegroundWindow(IntPtr point);
public void ActivateTargetApplication(string processName, List<string> barcodesList)
{
Process p = Process.Start("notepad++.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
IntPtr processFoundWindow = p.MainWindowHandle;
}
}
CREATE TABLE table_temp_list_objects AS
SELECT o.owner, o.object_name FROM sys.all_objects o WHERE o.object_type ='TABLE';
Here is the correct implementation using numpy (np.log()
is the natural logarithm)
import numpy as np
p = 100
r = 0.06 / 12
FV = 4000
n = np.log(1 + FV * r/ p) / np.log(1 + r)
print ("Number of periods = " + str(n))
Output:
Number of periods = 36.55539635919235
You need to use an older version of the data connectivity driver (2007 Office System Driver: Data Connectivity Components) and select Excel version 2007-2010 in the connection manager configuration window. I assume the newest data connectivity driver for Office 2016 is corrupt
I decided to download the assigned port numbers from IANA, filter out the used ports, and sort each "Unassigned" range in order of most ports available, descending. This did not work, since the csv file has ranges marked as "Unassigned" that overlap other port number reservations. I manually expanded the ranges of assigned port numbers, leaving me with a list of all assigned port numbers. I then sorted that list and generated my own list of unassigned ranges.
Since this stackoverflow.com page ranked very high in my search about the topic, I figured I'd post the largest ranges here for anyone else who is interested. These are for both TCP and UDP where the number of ports in the range is at least 500.
Total Start End
829 29170 29998
815 38866 39680
710 41798 42507
681 43442 44122
661 46337 46997
643 35358 36000
609 36866 37474
596 38204 38799
592 33657 34248
571 30261 30831
563 41231 41793
542 21011 21552
528 28590 29117
521 14415 14935
510 26490 26999
Source (via the CSV download button):
http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml
Best programmatically Understanding.
when syntax is
{}
then this isJsonObject
when syntax is
[]
then this isJsonArray
A JSONObject
is a JSON-like object that can be represented as an element in the JSONArray
. JSONArray
can contain a (or many) JSONObject
Hope this will helpful to you !
This query will give you a list of email addresses and how many times they're used, with the most used addresses first.
SELECT email,
count(*) AS c
FROM TABLE
GROUP BY email
HAVING c > 1
ORDER BY c DESC
If you want the full rows:
select * from table where email in (
select email from table
group by email having count(*) > 1
)
The result of your code will be the same. The reason is that the two incrementation operations can be seen as two distinct function calls. Both functions cause an incrementation of the variable, and only their return values are different. In this case, the return value is just thrown away, which means that there's no distinguishable difference in the output.
However, under the hood there's a difference: The post-incrementation i++
needs to create a temporary variable to store the original value of i
, then performs the incrementation and returns the temporary variable. The pre-incrementation ++i
doesn't create a temporary variable. Sure, any decent optimization setting should be able to optimize this away when the object is something simple like an int
, but remember that the ++-operators are overloaded in more complicated classes like iterators. Since the two overloaded methods might have different operations (one might want to output "Hey, I'm pre-incremented!" to stdout for example) the compiler can't tell whether the methods are equivalent when the return value isn't used (basically because such a compiler would solve the unsolvable halting problem), it needs to use the more expensive post-incrementation version if you write myiterator++
.
Three reasons why you should pre-increment:
An "em" is a typographical unit of width, the width of a wide-ish letter like "m" pronounced "em". Similarly there is an "en". Similarly "en-dash" and "em-dash" for – and —
With the Java optional package or Oracle JDK installed, adding one of the following lines to your ~/.bash_profile file will set the environment variable accordingly.
export JAVA_HOME="$(/usr/libexec/java_home -v 1.6)"
or
export JAVA_HOME="$(/usr/libexec/java_home -v 1.7)"
or
export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)"
or simply
export JAVA_HOME="$(/usr/libexec/java_home)"
Note: If you installed openjdk on mac using brew, run sudo ln -sfn /usr/local/opt/openjdk/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk.jdk
for the above to work
Update: added -v flag based on Jilles van Gurp response.
My sphinx.conf
source post_source
{
type = mysql
sql_host = localhost
sql_user = ***
sql_pass = ***
sql_db = ***
sql_port = 3306
sql_query_pre = SET NAMES utf8
# query before fetching rows to index
sql_query = SELECT *, id AS pid, CRC32(safetag) as safetag_crc32 FROM hb_posts
sql_attr_uint = pid
# pid (as 'sql_attr_uint') is necessary for sphinx
# this field must be unique
# that is why I like sphinx
# you can store custom string fields into indexes (memory) as well
sql_field_string = title
sql_field_string = slug
sql_field_string = content
sql_field_string = tags
sql_attr_uint = category
# integer fields must be defined as sql_attr_uint
sql_attr_timestamp = date
# timestamp fields must be defined as sql_attr_timestamp
sql_query_info_pre = SET NAMES utf8
# if you need unicode support for sql_field_string, you need to patch the source
# this param. is not supported natively
sql_query_info = SELECT * FROM my_posts WHERE id = $id
}
index posts
{
source = post_source
# source above
path = /var/data/posts
# index location
charset_type = utf-8
}
Test script:
<?php
require "sphinxapi.php";
$safetag = $_GET["my_post_slug"];
// $safetag = preg_replace("/[^a-z0-9\-_]/i", "", $safetag);
$conf = getMyConf();
$cl = New SphinxClient();
$cl->SetServer($conf["server"], $conf["port"]);
$cl->SetConnectTimeout($conf["timeout"]);
$cl->setMaxQueryTime($conf["max"]);
# set search params
$cl->SetMatchMode(SPH_MATCH_FULLSCAN);
$cl->SetArrayResult(TRUE);
$cl->setLimits(0, 1, 1);
# looking for the post (not searching a keyword)
$cl->SetFilter("safetag_crc32", array(crc32($safetag)));
# fetch results
$post = $cl->Query(null, "post_1");
echo "<pre>";
var_dump($post);
echo "</pre>";
exit("done");
?>
Sample result:
[array] =>
"id" => 123,
"title" => "My post title.",
"content" => "My <p>post</p> content.",
...
[ and other fields ]
Sphinx query time:
0.001 sec.
Sphinx query time (1k concurrent):
=> 0.346 sec. (average)
=> 0.340 sec. (average of last 10 query)
MySQL query time:
"SELECT * FROM hb_posts WHERE id = 123;"
=> 0.001 sec.
MySQL query time (1k concurrent):
"SELECT * FROM my_posts WHERE id = 123;"
=> 1.612 sec. (average)
=> 1.920 sec. (average of last 10 query)
7 years later, allow me to give a one-liner solution by building on a previous answer. You could do the followwing:
numbers = [1, 2, 3]
to Add [3, 4, 5]
into numbers
without repeating 3
, do the following:
numbers = list(set(numbers + [3, 4, 5]))
This results in 4
and 5
being added to numbers
as in [1, 2, 3, 4, 5]
Explanation:
Now let me explain what happens, starting from the inside of the set()
instruction, we took numbers
and added 3
, 4
, and 5
to it which makes numbers
look like [1, 2, 3, 3, 4, 5]
.
Then, we took that ([1, 2, 3, 3, 4, 5]
) and transformed it into a set which gets rid of duplicates, resulting in the following {1, 2, 3, 4, 5}
. Now since we wanted a list and not a set, we used the function list()
to make that set ({1, 2, 3, 4, 5}
) into a list, resulting in [1, 2, 3, 4, 5]
which we assigned to the variable numbers
This, I believe, will work for all types of data in a list, and objects as well if done correctly.
from __future__ import division
somelist = [1,12,2,53,23,6,17]
max_value = max(somelist)
min_value = min(somelist)
avg_value = 0 if len(somelist) == 0 else sum(somelist)/len(somelist)
If you want to manually find the minimum as a function:
somelist = [1,12,2,53,23,6,17]
def my_min_function(somelist):
min_value = None
for value in somelist:
if not min_value:
min_value = value
elif value < min_value:
min_value = value
return min_value
Python 3.4 introduced the statistics
package, which provides mean
and additional stats:
from statistics import mean, median
somelist = [1,12,2,53,23,6,17]
avg_value = mean(somelist)
median_value = median(somelist)
In my case I was using XAMPP, and there was a log that told me the error. To find it, go to the XAMPP control panel, and click "Configure" for MySQL, then click on "Open Log."
The most current data of the log is at the bottom, and the log is organized by date, time, some number, and text in brackets that may say "Note" or "Error." One that says "Error" is likely causing the issue.
For me, my error was a tablespace that was causing an issue, so I deleted the database files at the given location.
Note: The tablespace files for your installation of XAMPP may be at a different location, but they were in /opt/lampp/var/mysql
for me. I think that's typical of XAMPP on Debian-based distributions. Also, my instructions on what to click in the control panel to see the log may be a bit different for you because I'm running XAMPP on an Ubuntu-based distribution of Linux (Feren OS).
The issue for me was that I was doing $.ajax with dataType: "json"
for a POST request that was returning an HTTP 201 (created) and no request body. The fix was to simply remove that key/value.
Download openssl for windows from https://code.google.com/archive/p/openssl-for-windows/downloads
Set Environment variable to the path variable as path="C:\your_folder\openssl-0.9.8k_X64\bin"
Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.
git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67
Then, abort the rebase again.
The required file can be accessed as below from resource folder in scala
val file = scala.io.Source.fromFile(s"src/main/resources/app.config").getLines().mkString
if you use
angularjs
you have just to write the right css in order to frame you div
html code
<div
style="height:51px;width:111px;margin-left:203px;"
ng-click="nextDetail()">
</div>
JS Code(in your controller):
$scope.nextDetail = function()
{
....
}
Try PHP Mailer library.
Or Send mail through SMTP filter it before sending it.
Also Try to give all details like FROM
, return-path
.
If you really want to understand ANSI C 89, I need to correct you in one thing; In ANSI C 89 the difference between the following functions:
int main()
int main(void)
int main(int argc, char* argv[])
is:
int main()
int main(void)
int main(int argc, char * argv[])
About when using each of the functions
int main(void)
int main(int argc, char * argv[])
About void main()
In ANSI C 89, when using void main
and compiling the project AS -ansi -pedantic
(in Ubuntu, e.g)
you will receive a warning indicating that your main function is of type void and not of type int, but you will be able to run the project.
Most C developers tend to use int main()
on all of its variants, though void main()
will also compile.
The MSDN is a good reference for these type of questions regarding syntax and usage. This is from the Transact SQL Reference - CASE page.
http://msdn.microsoft.com/en-us/library/ms181765.aspx
USE AdventureWorks2012;
GO
SELECT ProductNumber, Name, "Price Range" =
CASE
WHEN ListPrice = 0 THEN 'Mfg item - not for resale'
WHEN ListPrice < 50 THEN 'Under $50'
WHEN ListPrice >= 50 and ListPrice < 250 THEN 'Under $250'
WHEN ListPrice >= 250 and ListPrice < 1000 THEN 'Under $1000'
ELSE 'Over $1000'
END
FROM Production.Product
ORDER BY ProductNumber ;
GO
Another good site you may want to check out if you're using SQL Server is SQL Server Central. This has a large variety of resources available for whatever area of SQL Server you would like to learn.
table{_x000D_
border: 1px solid black;_x000D_
}_x000D_
table td {_x000D_
border: 1px solid black; /* Style just to show the table cell boundaries */_x000D_
}_x000D_
_x000D_
_x000D_
table.no-spacing {_x000D_
border-spacing:0; /* Removes the cell spacing via CSS */_x000D_
border-collapse: collapse; /* Optional - if you don't want to have double border where cells touch */_x000D_
}
_x000D_
<p>Default table:</p>_x000D_
_x000D_
<table>_x000D_
<tr>_x000D_
<td>First cell</td>_x000D_
<td>Second cell</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
<p>Removed spacing:</p>_x000D_
_x000D_
<table class="no-spacing" cellspacing="0"> <!-- cellspacing 0 to support IE6 and IE7 -->_x000D_
<tr>_x000D_
<td>First cell</td>_x000D_
<td>Second cell</td>_x000D_
</tr>_x000D_
</table>
_x000D_
By default many profiles are defaulted to 0 core file size because the average user doesn't know what to do with them.
Try ulimit -c unlimited
before running your program.
There's a better way of storing JSON in the HTML:
HTML
<script id="some-data" type="application/json">{"param_1": "Value 1", "param_2": "Value 2"}</script>
JavaScript
JSON.parse(document.getElementById('some-data').textContent);
On my side, this error came from the data type "INT' in the Null values column. The error is resolved by just changing the data a type to varchar.
In case someone is using python and linux and looking for full path to file:
>>> path=os.popen("readlink -f file").read()
>>> print path
abs/path/to/file
I use spring 3.2.3 and here is how I solved similar problem.
1) Added RedirectAttributes redirectAttributes to the method parameter list in controller 1.
public String controlMapping1(
@ModelAttribute("mapping1Form") final Object mapping1FormObject,
final BindingResult mapping1BindingResult,
final Model model,
final RedirectAttributes redirectAttributes)
2) Inside the method added code to add flash attribute to redirectAttributes redirectAttributes.addFlashAttribute("mapping1Form", mapping1FormObject);
3) Then, in the second contoller use method parameter annotated with @ModelAttribute to access redirect Attributes
@ModelAttribute("mapping1Form") final Object mapping1FormObject
Here is the sample code from Controller 1:
@RequestMapping(value = { "/mapping1" }, method = RequestMethod.POST)
public String controlMapping1(
@ModelAttribute("mapping1Form") final Object mapping1FormObject,
final BindingResult mapping1BindingResult,
final Model model,
final RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("mapping1Form", mapping1FormObject);
return "redirect:mapping2";
}
From Contoller 2:
@RequestMapping(value = "/mapping2", method = RequestMethod.GET)
public String controlMapping2(
@ModelAttribute("mapping1Form") final Object mapping1FormObject,
final BindingResult mapping1BindingResult,
final Model model) {
model.addAttribute("transformationForm", mapping1FormObject);
return "new/view";
}
I understand that every time I type the String literal "", the same String object is referenced in the String pool.
There's no such guarantee made. And you can't rely on it in your application, it's completely up to jvm to decide.
or did the language creators simply not share my views?
Yep. To me, it seems very low priority thing.
NSDateFormatter *df= [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd"];
NSDate *dt1 = [[NSDate alloc] init];
NSDate *dt2 = [[NSDate alloc] init];
dt1=[df dateFromString:@"2011-02-25"];
dt2=[df dateFromString:@"2011-03-25"];
NSComparisonResult result = [dt1 compare:dt2];
switch (result)
{
case NSOrderedAscending: NSLog(@"%@ is greater than %@", dt2, dt1); break;
case NSOrderedDescending: NSLog(@"%@ is less %@", dt2, dt1); break;
case NSOrderedSame: NSLog(@"%@ is equal to %@", dt2, dt1); break;
default: NSLog(@"erorr dates %@, %@", dt2, dt1); break;
}
Enjoy coding......
Gumbo gets my vote, however, the OP doesn't specify whether just "Id" is an allowable word, which means I'd make a minor modification:
\w+Id\b
1 or more word characters followed by "Id" and a breaking space. The [a-zA-Z] variants don't take into account non-English alphabetic characters. I might also use \s instead of \b as a space rather than a breaking space. It would depend if you need to wrap over multiple lines.
I am having the same problem, and I guess the way of doing this will be to remove the data-toggle attribute and have a custom handler for the links.
Something in the lines of:
$("a[data-target=#myModal]").click(function(ev) {
ev.preventDefault();
var target = $(this).attr("href");
// load the url and show modal on success
$("#myModal .modal-body").load(target, function() {
$("#myModal").modal("show");
});
});
Will try it later and post comments.
I found myself wanting to do this and I reviewed the above answers and did a hybrid approach of them. It got a little tricky, but here is what I did:
My button already worked with a server side post. I wanted to let that to continue to work so I left the "OnClick" the same, but added a OnClientClick:
OnClientClick="if (!OnClick_Submit()) return false;"
Here is my full button element in case it matters:
<asp:Button UseSubmitBehavior="false" runat="server" Class="ms-ButtonHeightWidth jiveSiteSettingsSubmit" OnClientClick="if (!OnClick_Submit()) return false;" OnClick="BtnSave_Click" Text="<%$Resources:wss,multipages_okbutton_text%>" id="BtnOK" accesskey="<%$Resources:wss,okbutton_accesskey%>" Enabled="true"/>
If I inspect the onclick attribute of the HTML button at runtime it actually looks like this:
if (!OnClick_Submit()) return false;WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$PlaceHolderMain$ctl03$RptControls$BtnOK", "", true, "", "", false, true))
Then in my Javascript I added the OnClick_Submit method. In my case I needed to do a check to see if I needed to show a dialog to the user. If I show the dialog I return false causing the event to stop processing. If I don't show the dialog I return true causing the event to continue processing and my postback logic to run as it used to.
function OnClick_Submit() {
var initiallyActive = initialState.socialized && initialState.activityEnabled;
var socialized = IsSocialized();
var enabled = ActivityStreamsEnabled();
var displayDialog;
// Omitted the setting of displayDialog for clarity
if (displayDialog) {
$("#myDialog").dialog('open');
return false;
}
else {
return true;
}
}
Then in my Javascript code that runs when the dialog is accepted, I do the following depending on how the user interacted with the dialog:
$("#myDialog").dialog('close');
__doPostBack('message', '');
The "message" above is actually different based on what message I want to send.
Back in my server-side code, I changed OnLoad from:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e)
if (IsPostBack)
{
return;
}
// OnLoad logic removed for clarity
}
To:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e)
if (IsPostBack)
{
switch (Request.Form["__EVENTTARGET"])
{
case "message1":
// We did a __doPostBack with the "message1" command provided
Page.Validate();
BtnSave_Click(this, new CommandEventArgs("message1", null));
break;
case "message2":
// We did a __doPostBack with the "message2" command provided
Page.Validate();
BtnSave_Click(this, new CommandEventArgs("message2", null));
break;
}
return;
}
// OnLoad logic removed for clarity
}
Then in BtnSave_Click method I do the following:
CommandEventArgs commandEventArgs = e as CommandEventArgs;
string message = (commandEventArgs == null) ? null : commandEventArgs.CommandName;
And finally I can provide logic based on whether or not I have a message and based on the value of that message.
Antwane's answer is correct, and this should be a comment but comments don't have enough space and do not allow formatting. :-) I just want to add that in Git, file permissions are recorded only1 as either 644
or 755
(spelled (100644
and 100755
; the 100
part means "regular file"):
diff --git a/path b/path
new file mode 100644
The former—644—means that the file should not be executable, and the latter means that it should be executable. How that turns into actual file modes within your file system is somewhat OS-dependent. On Unix-like systems, the bits are passed through your umask
setting, which would normally be 022
to remove write permission from "group" and "other", or 002
to remove write permission only from "other". It might also be 077
if you are especially concerned about privacy and wish to remove read, write, and execute permission from both "group" and "other".
1Extremely-early versions of Git saved group permissions, so that some repositories have tree entries with mode 664
in them. Modern Git does not, but since no part of any object can ever be changed, those old permissions bits still persist in old tree objects.
The change to store only 0644 or 0755 was in commit e44794706eeb57f2, which is before Git v0.99 and dated 16 April 2005.
If you have tried all these solutions, esp. increasing max_allowed_packet
up to the maximum supported amount of 1GB
and you are still seeing these errors, it might be that your server literally does not have enough free RAM memory available...
The solution = upgrade your server to more RAM memory, and try again.
Note: I'm surprised this simple solution has not been mentioned after 8+ years of discussion on this thread... sometimes we developers tend to overthink things.
I found this way of using ajax which helped me as it was better in use as not having complex json syntaxes
//fifth
function GetAjaxDataPromise(url, postData) {
debugger;
var promise = $.post(url, postData, function (promise, status) {
});
return promise;
};
$(function () {
$("#btnGet5").click(function () {
debugger;
var promises = GetAjaxDataPromise('@Url.Action("AjaxMethod", "Home")', { EmpId: $("#txtId").val(), EmpName: $("#txtName").val(), EmpSalary: $("#txtSalary").val() });
promises.done(function (response) {
debugger;
alert("Hello: " + response.EmpName + " Your Employee Id Is: " + response.EmpId + "And Your Salary Is: " + response.EmpSalary);
});
});
});
This method comes with jquery promise the best part was on controller we can received data by using separate parameters or just by using a model class.
[HttpPost]
public JsonResult AjaxMethod(PersonModel personModel)
{
PersonModel person = new PersonModel
{
EmpId = personModel.EmpId,
EmpName = personModel.EmpName,
EmpSalary = personModel.EmpSalary
};
return Json(person);
}
or
[HttpPost]
public JsonResult AjaxMethod(string empId, string empName, string empSalary)
{
PersonModel person = new PersonModel
{
EmpId = empId,
EmpName = empName,
EmpSalary = empSalary
};
return Json(person);
}
It works for both of the cases. SO you must try out this way. Got the reference from Using Ajax With Asp.Net MVC
There are few more ways of using Ajax explained there other than this one which you must try.
The methods in some of the other answers that use a regular expression do not cover all cases, particularly:
The following method handles these cases:
function getCookie(name) {
function escape(s) { return s.replace(/([.*+?\^$(){}|\[\]\/\\])/g, '\\$1'); }
var match = document.cookie.match(RegExp('(?:^|;\\s*)' + escape(name) + '=([^;]*)'));
return match ? match[1] : null;
}
This will return null
if the cookie is not found. It will return an empty string if the value of the cookie is empty.
Notes:
document.cookie
- When this appears on the right-hand side of an assignment, it represents a string containing a semicolon-separated list of cookies, which in turn are name=value
pairs. There appears to be a single space after each semicolon.String.prototype.match()
- Returns null
when no match is found. Returns an array when a match is found, and the element at index [1]
is the value of the first matching group.Regular Expression Notes:
(?:xxxx)
- forms a non-matching group.^
- matches the start of the string.|
- separates alternative patterns for the group.;\\s*
- matches one semi-colon followed by zero or more whitespace characters.=
- matches one equal sign.(xxxx)
- forms a matching group.[^;]*
- matches zero or more characters other than a semi-colon. This means it will match characters up to, but not including, a semi-colon or to the end of the string.Here is a complete method that only has one button, an 'ok', to close the UIAlert:
- (void) myAlert: (NSString*)errorMessage
{
UIAlertView *myAlert = [[UIAlertView alloc]
initWithTitle:errorMessage
message:@""
delegate:self
cancelButtonTitle:nil
otherButtonTitles:@"ok", nil];
myAlert.cancelButtonIndex = -1;
[myAlert setTag:1000];
[myAlert show];
}
SELECT t1.ColumnID,
CASE
WHEN NOT EXISTS( SELECT t2.FieldText
FROM Table t2
WHERE t2.ColumnID = t1.ColumnID)
THEN t1.FieldText
ELSE t2.FieldText
END FieldText
FROM Table1 t1, Table2 t2
start "" AcroRd32.exe /A "page=207" "C:\Users\abc\Desktop\abc xyz def\abc def xyz 2015.pdf"
You may try this, I did it finally, it works!
There is nothing like kafka --version
at this point. So you should either check the version from your kafka/libs/
folder or you can run
find ./libs/ -name \*kafka_\* | head -1 | grep -o '\kafka[^\n]*'
from your kafka folder (and it will do the same for you). It will return you something like kafka_2.9.2-0.8.1.1.jar.asc
where 0.8.1.1
is your kafka version.
In my case the problem was that I hid the file (The file had hidden atribute):
How to deal with the problem in python:
import os
# This is how to hide the file
os.system(f"attrib +h {filePath}")
file_ = open(filePath, "wb")
>>> PermissionError <<<
# and this is how to show it again making the file writable again:
os.system(f"attrib -h {filePath}")
file_ = open(filePath, "wb")
# This works
# and just to let you know there is also this way
# so you don't need to import os
import subprocess
subprocess.check_call(["attrib", "-H", _path])
In my case, I was aiming to save TimeSpan from datetimePicker tool without saving the seconds and the milliseconds, and here is the solution.
First convert the datetimePicker.value to your desired format, which mine is "HH:mm" then convert it back to TimeSpan.
var datetime = datetimepicker1.Value.ToString("HH:mm");
TimeSpan timeSpan = Convert.ToDateTime(datetime).TimeOfDay;
The simplest method is
$dateArray = explode('/', $_POST['date']);
$date = $dateArray[2].'-'.$dateArray[0].'-'.$dateArray[1];
$sql = mysql_query("INSERT INTO user_date (column,column,column) VALUES('',$name,$date)") or die (mysql_error());
Here you get all available services and their status in your local machine.
ServiceController[] services = ServiceController.GetServices();
foreach(ServiceController service in services)
{
Console.WriteLine(service.ServiceName+"=="+ service.Status);
}
You can Compare your service with service.name property inside loop and you get status of your service. For details go with the http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.aspx also http://msdn.microsoft.com/en-us/library/microsoft.windows.design.servicemanager(v=vs.90).aspx
I tried a few of the solutions from this thread. It seemed to work, but my values were always true and I also encountered the following issue: JENKINS-40235
I managed to use parameters in groovy jenkinsfile
using the following syntax: params.myVariable
Here's a working example:
print 'DEBUG: parameter isFoo = ' + params.isFoo
print "DEBUG: parameter isFoo = ${params.isFoo}"
node() {
// adds job parameters within jenkinsfile
properties([
parameters([
booleanParam(
defaultValue: false,
description: 'isFoo should be false',
name: 'isFoo'
),
booleanParam(
defaultValue: true,
description: 'isBar should be true',
name: 'isBar'
),
])
])
// test the false value
print 'DEBUG: parameter isFoo = ' + params.isFoo
print "DEBUG: parameter isFoo = ${params.isFoo}"
sh "echo sh isFoo is ${params.isFoo}"
if (params.isFoo) { print "THIS SHOULD NOT DISPLAY" }
// test the true value
print 'DEBUG: parameter isBar = ' + params.isBar
print "DEBUG: parameter isBar = ${params.isBar}"
sh "echo sh isBar is ${params.isBar}"
if (params.isBar) { print "this should display" }
}
[Pipeline] {
[Pipeline] properties
WARNING: The properties step will remove all JobPropertys currently configured in this job, either from the UI or from an earlier properties step.
This includes configuration for discarding old builds, parameters, concurrent builds and build triggers.
WARNING: Removing existing job property 'This project is parameterized'
WARNING: Removing existing job property 'Build triggers'
[Pipeline] echo
DEBUG: parameter isFoo = false
[Pipeline] echo
DEBUG: parameter isFoo = false
[Pipeline] sh
[wegotrade-test-job] Running shell script
+ echo sh isFoo is false
sh isFoo is false
[Pipeline] echo
DEBUG: parameter isBar = true
[Pipeline] echo
DEBUG: parameter isBar = true
[Pipeline] sh
[wegotrade-test-job] Running shell script
+ echo sh isBar is true
sh isBar is true
[Pipeline] echo
this should display
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
I sent a Pull Request to update the misleading pipeline tutorial#build-parameters quote that says "they are accessible as Groovy variables of the same name.". ;)
Edit: As Jesse Glick pointed out: Release notes go into more details
You should also update the Pipeline Job Plugin to 2.7 or later, so that build parameters are defined as environment variables and thus accessible as if they were global Groovy variables.
Just a note from my experience, you can find configuration file under this path /etc/mysql/mysql.conf.d/mysqld.cnf
.
(I struggled for some time to find this path)
With C# 4.0, reflection isn't necessary as the DLR can call it using runtime types. Since using the DLR library is kind of a pain dynamically (instead of the C# compiler generating code for you), the open source framework Dynamitey (.net standard 1.5) gives you easy cached run-time access to the same calls the compiler would generate for you.
var name = InvokeMemberName.Create;
Dynamic.InvokeMemberAction(this, name("GenericMethod", new[]{myType}));
var staticContext = InvokeContext.CreateStatic;
Dynamic.InvokeMemberAction(staticContext(typeof(Sample)), name("StaticMethod", new[]{myType}));
It will work perfectly with 50px. Which will act as a static and thus as min-width.
font-size: calc(50px + 5vw);
You don't need getInputDOMNode
?? in this case...
Just simply get the ref
and focus()
it when component gets mounted -- componentDidMount...
import React from 'react';
import { render } from 'react-dom';
class myApp extends React.Component {
componentDidMount() {
this.nameInput.focus();
}
render() {
return(
<div>
<input ref={input => { this.nameInput = input; }} />
</div>
);
}
}
ReactDOM.render(<myApp />, document.getElementById('root'));
You can use is_uploaded_file()
:
if(!file_exists($_FILES['myfile']['tmp_name']) || !is_uploaded_file($_FILES['myfile']['tmp_name'])) {
echo 'No upload';
}
From the docs:
Returns TRUE if the file named by filename was uploaded via HTTP POST. This is useful to help ensure that a malicious user hasn't tried to trick the script into working on files upon which it should not be working--for instance, /etc/passwd.
This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.
EDIT: I'm using this in my FileUpload class, in case it helps:
public function fileUploaded()
{
if(empty($_FILES)) {
return false;
}
$this->file = $_FILES[$this->formField];
if(!file_exists($this->file['tmp_name']) || !is_uploaded_file($this->file['tmp_name'])){
$this->errors['FileNotExists'] = true;
return false;
}
return true;
}
There are quite a few elements of the $.Ajax()
that can cause issues if they are not defined correctly. I would suggest rewritting your javascript in its most basic form, you will most likely find that it works fine.
Script example:
$.ajax({
type: "POST",
url: '/Default.aspx/TestMethod',
data: '{message: "HAI" }',
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
},
failure: function (response) {
alert(response.d);
}
});
WebMethod example:
[WebMethod]
public static string TestMethod(string message)
{
return "The message" + message;
}
If you want to find matches in the entire file (not just the tail), and you want it to sit and wait for any new matches, this works nicely:
tail -c +0 -f <file> | grep --line-buffered <pattern>
The -c +0
flag says that the output should start 0
bytes (-c
) from the beginning (+
) of the file.
And what about:
if ($('#dataTable[data-timer]').length > 0) {
// logic here
}
If you want the enum names themselves as strings, see this post.
Otherwise, a std::map<MyEnum, char const*>
will work nicely. (No point in copying your string literals to std::strings in the map)
For extra syntactic sugar, here's how to write a map_init class. The goal is to allow
std::map<MyEnum, const char*> MyMap;
map_init(MyMap)
(eValue1, "A")
(eValue2, "B")
(eValue3, "C")
;
The function template <typename T> map_init(T&)
returns a map_init_helper<T>
.
map_init_helper<T>
stores a T&, and defines the trivial map_init_helper& operator()(typename T::key_type const&, typename T::value_type const&)
. (Returning *this
from operator()
allows the chaining of operator()
, like operator<<
on std::ostream
s)
template<typename T> struct map_init_helper
{
T& data;
map_init_helper(T& d) : data(d) {}
map_init_helper& operator() (typename T::key_type const& key, typename T::mapped_type const& value)
{
data[key] = value;
return *this;
}
};
template<typename T> map_init_helper<T> map_init(T& item)
{
return map_init_helper<T>(item);
}
Since the function and helper class are templated, you can use them for any map, or map-like structure. I.e. it can also add entries to std::unordered_map
If you don't like writing these helpers, boost::assign offers the same functionality out of the box.
Android Studio is now (early 2015) out of beta. If you're using it as your development platform, the SDK Manager is probably the easiest way to see what's available. To start the SDK Manager from within Android Studio, use the menu bar: Tools > Android > SDK Manager.
This will provide not only the SDK version, but the versions of SDK Build Tools and SDK Platform Tools. It also works if you've installed them somewhere other than in Program Files.
I used this method to clear the image from picturebox. It may help some one
private void btnClear1_Click(object sender, EventArgs e)
{
img1.ImageLocation = null;
}
To just get your IP address:
echo `ifconfig eth0 2>/dev/null|awk '/inet addr:/ {print $2}'|sed 's/addr://'`
This will give you the IP address of eth0.
Edit: Due to name changes of interfaces in recent versions of Ubuntu, this doesn't work anymore. Instead, you could just use this:
hostname --all-ip-addresses
or hostname -I
, which does the same thing (gives you ALL IP addresses of the host).
In standard SQL this type of update looks like:
update a
set a.firstfield ='BIT OF TEXT' + b.something
from file1 a
join file2 b
on substr(a.firstfield,10,20) =
substr(b.anotherfield,1,10)
where a.firstfield like 'BLAH%'
With minor syntactic variations this type of thing will work on Oracle or SQL Server and (although I don't have a DB/2 instance to hand to test) will almost certainly work on DB/2.
I guess you can use the size
attribute. It works in all recent browsers.
<select name="courses" multiple="multiple" size="30" style="height: 100%;">
With pure JavaScript you can do this (such as SQL) and anything you need, basically:
<html>_x000D_
_x000D_
<body>_x000D_
_x000D_
<input type='button' value='F3' class="c2" id="btn_1">_x000D_
<input type='button' value='F3' class="c3" id="btn_2">_x000D_
<input type='button' value='F1' class="c2" id="btn_3">_x000D_
_x000D_
<input type='submit' value='F2' class="c1" id="btn_4">_x000D_
<input type='submit' value='F1' class="c3" id="btn_5">_x000D_
<input type='submit' value='F2' class="c1" id="btn_6">_x000D_
_x000D_
<br/>_x000D_
<br/>_x000D_
_x000D_
<button onclick="myFunction()">Try it</button>_x000D_
_x000D_
<script>_x000D_
function myFunction() _x000D_
{_x000D_
var arrFiltered = document.querySelectorAll('input[value=F2][type=submit][class=c1]');_x000D_
_x000D_
arrFiltered.forEach(function (el)_x000D_
{ _x000D_
var node = document.createElement("p");_x000D_
_x000D_
node.innerHTML = el.getAttribute('id');_x000D_
_x000D_
window.document.body.appendChild(node);_x000D_
});_x000D_
}_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Use:
export LANGUAGE=en_US.UTF-8
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
export LC_CTYPE=en_US.UTF-8
It works for Debian. I don't know why - but locale-gen had not results.
Important! It's a temporary solution. It has to be run for each session.
Maybe a bit late, but: instead of this:
public void onNewIntent(Intent intent){
Bundle extras = intent.getExtras();
Log.i( "dbg","onNewIntent");
if(extras != null){
Log.i( "dbg", "Extra6 bool: "+ extras.containsKey("net.dbg.android.fjol"));
Log.i( "dbg", "Extra6 val : "+ extras.getString("net.dbg.android.fjol"));
}
mTabsController.setActiveTab(TabsController.TAB_DOWNLOADS);
}
Use this:
Bundle extras = getIntent().getExtras();
if(extras !=null) {
String value = extras.getString("keyName");
}
To add to Box9's answer:
Backbone.js is dependent on underscore.js, which itself implements John Resig's original microtemplates.
If you decide to use Backbone.js with Rails, be sure to check out the Jammit gem. It provides a very clean way to manage asset packaging for templates. http://documentcloud.github.com/jammit/#jst
By default Jammit also uses JResig's microtemplates, but it also allows you to replace the templating engine.
I created a working CodePen example demonstrating how to do this the correct way in AngularJS. The Angular $window service should be used to access any global objects since directly accessing window
makes testing more difficult.
HTML:
<section ng-app="myapp" ng-controller="MainCtrl">
Value of global variable read by AngularJS: {{variable1}}
</section>
JavaScript:
// global variable outside angular
var variable1 = true;
var app = angular.module('myapp', []);
app.controller('MainCtrl', ['$scope', '$window', function($scope, $window) {
$scope.variable1 = $window.variable1;
}]);
For me it was not running the minify task after concatenation as it expects concatenated input and it was not generated some times.
I tried adding to a default task in execution order and it didn't worked. It worked after adding just a return
for each tasks and getting the minification inside gulp.start()
like below.
/**
* Concatenate JavaScripts
*/
gulp.task('concat-js', function(){
return gulp.src([
'js/jquery.js',
'js/jquery-ui.js',
'js/bootstrap.js',
'js/jquery.onepage-scroll.js',
'js/script.js'])
.pipe(maps.init())
.pipe(concat('ux.js'))
.pipe(maps.write('./'))
.pipe(gulp.dest('dist/js'));
});
/**
* Minify JavaScript
*/
gulp.task('minify-js', function(){
return gulp.src('dist/js/ux.js')
.pipe(uglify())
.pipe(rename('ux.min.js'))
.pipe(gulp.dest('dist/js'));
});
gulp.task('concat', ['concat-js'], function(){
gulp.start('minify-js');
});
gulp.task('default',['concat']);
I have found a fix
BufferedReader br = new BufferedReader(new InputStreamReader(Main.class.getResourceAsStream(path)));
Replace "Main" with the java class you coded it in. replace "path" with the path within the jar file.
for example, if you put State1.txt in the package com.issac.state, then type the path as "/com/issac/state/State1" if you run Linux or Mac. If you run Windows then type the path as "\com\issac\state\State1". Don't add the .txt extension to the file unless the File not found exception occurs.
DataTable dr_art_line_2 = ds.Tables["QuantityInIssueUnit"];
for (int i = 0; i < dr_art_line_2.Rows.Count; i++)
{
QuantityInIssueUnit_value = Convert.ToInt32(dr_art_line_2.Rows[i]["columnname"]);
//Similarly for QuantityInIssueUnit_uom.
}
When you have to go from one page to another page in android changes made in 2 files
Intent intentSignUP = new Intent(this,SignUpActivity.class);
startActivity(intentSignUP);
add activity in androidManifest file also like
<activity android:name=".SignUpActivity"></activity>
The short answer is yes, as long as it is a public IP address.
Issuance of certificates to reserved IP addresses is not allowed, and all certificates previously issued to reserved IP addresses were revoked as of 1 October 2016.
According to the CA Browser forum, there may be compatibility issues with certificates for IP addresses unless the IP address is in both the commonName
and subjectAltName
fields. This is due to legacy SSL implementations which are not aligned with RFC 5280, notably, Windows OS prior to Windows 10.
Sources:
Note: an earlier version of this answer stated that all IP address certificates would be revoked on 1 October 2016. Thanks to Navin for pointing out the error.
What is important is that the apache
user and group should have minimum read
access and in some cases execute
access. For the rest you can give 0
access.
This is the most safe setting.
self.materials
is a dict
and by default you are iterating over just the keys (which are strings).
Since self.materials
has more than two keys*, they can't be unpacked into the tuple
"k, m
", hence the ValueError
exception is raised.
In Python 2.x, to iterate over the keys and the values (the tuple
"k, m
"), we use self.materials.iteritems()
.
However, since you're throwing the key away anyway, you may as well simply iterate over the dictionary's values:
for m in self.materials.itervalues():
In Python 3.x, prefer dict.values()
(which returns a dictionary view object):
for m in self.materials.values():
As Simon says above, using drawImage shouldn't work. But, using the canvg library and:
var c = document.getElementById('canvas');
var ctx = c.getContext('2d');
ctx.drawSvg(SVG_XML_OR_PATH_TO_SVG, dx, dy, dw, dh);
This comes from the link Simon provides above, which has a number of other suggestions and points out that you want to either link to, or download canvg.js and rgbcolor.js. These allow you to manipulate and load an SVG, either via URL or using inline SVG code between svg tags, within JavaScript functions.
this
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
//toolbar.setNavigationIcon(R.drawable.ic_toolbar);
toolbar.setTitle("");
toolbar.setSubtitle("");
//toolbar.setLogo(R.drawable.ic_toolbar);
#div:before {
content:"";
position:absolute;
width:100%;
background:#fff;
height:38px;
top:1px;
right:-5px;
}