I also have the same problem, and the solution is I didn't bind the event in my onClick. so when it renders for the first time and the data is more, which ends up calling the state setter again, which triggers React to call your function again and so on.
export default function Component(props) {
function clickEvent (event, variable){
console.log(variable);
}
return (
<div>
<IconButton
key="close"
aria-label="Close"
color="inherit"
onClick={e => clickEvent(e, 10)} // or you can call like this:onClick={() => clickEvent(10)}
>
</div>
)
}
// replace
return <p>hello</p>;
// with
return <p>{JSON.stringify(movies)}</p>;
Now you should see, that your code actually does work. What does not work is the console.log(movies)
. This is because movies
points to the old state. If you move your console.log(movies)
outside of useEffect
, right above the return, you will see the updated movies object.
Upgrading the Kotlin (Plugin and stdLib) version to 1.3.1 solved that warning in my case. Update the Kotlin version in whole project by replacing existing Kotlin version with :
ext.kotlin_version = '1.3.50'
Adding productFlavors{} to the app build.gradle solved the issue for me. See below:
buildTypes {
release {
...
}
}
productFlavors {
}
I have used flavorDimensions for my application in build.gradle (Module: app)
flavorDimensions "tier"
productFlavors {
production {
flavorDimensions "tier"
//manifestPlaceholders = [appName: APP_NAME]
//signingConfig signingConfigs.config
}
staging {
flavorDimensions "tier"
//manifestPlaceholders = [appName: APP_NAME_STAGING]
//applicationIdSuffix ".staging"
//versionNameSuffix "-staging"
//signingConfig signingConfigs.config
}
}
// Specifies two flavor dimensions.
flavorDimensions "tier", "minApi"
productFlavors {
free {
// Assigns this product flavor to the "tier" flavor dimension. Specifying
// this property is optional if you are using only one dimension.
dimension "tier"
...
}
paid {
dimension "tier"
...
}
minApi23 {
dimension "minApi"
...
}
minApi18 {
dimension "minApi"
...
}
}
The second method, Task.Run
, has been introduced in a later version of the .NET framework (in .NET 4.5).
However, the first method, Task.Factory.StartNew
, gives you the opportunity to define a lot of useful things about the thread you want to create, while Task.Run
doesn't provide this.
For instance, lets say that you want to create a long running task thread. If a thread of the thread pool is going to be used for this task, then this could be considered an abuse of the thread pool.
One thing you could do in order to avoid this would be to run the task in a separate thread. A newly created thread that would be dedicated to this task and would be destroyed once your task would have been completed. You cannot achieve this with the Task.Run
, while you can do so with the Task.Factory.StartNew
, like below:
Task.Factory.StartNew(..., TaskCreationOptions.LongRunning);
As it is stated here:
So, in the .NET Framework 4.5 Developer Preview, we’ve introduced the new Task.Run method. This in no way obsoletes Task.Factory.StartNew, but rather should simply be thought of as a quick way to use Task.Factory.StartNew without needing to specify a bunch of parameters. It’s a shortcut. In fact, Task.Run is actually implemented in terms of the same logic used for Task.Factory.StartNew, just passing in some default parameters. When you pass an Action to Task.Run:
Task.Run(someAction);
that’s exactly equivalent to:
Task.Factory.StartNew(someAction,
CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
I searched for this very question and when I saw the answers I ended up creating something different (because I favor less code over most other things most of the time) that should work in the vast majority of cases. Basically turn the array into a string with array elements separated by some delimiter character, and then wrap the search value in the delimiter character and pass through instr.
Function is_in_array(value As String, test_array) As Boolean
If Not (IsArray(test_array)) Then Exit Function
If InStr(1, "'" & Join(test_array, "'") & "'", "'" & value & "'") > 0 _
Then is_in_array = True
End Function
And you'd execute the function like this:
test = is_in_array(1, array(1, 2, 3))
You can't do this: {this.state.arrayFromJson}
As your error suggests what you are trying to do is not valid. You are trying to render the whole array as a React child. This is not valid. You should iterate through the array and render each element. I use .map
to do that.
I am pasting a link from where you can learn how to render elements from an array with React.
http://jasonjl.me/blog/2015/04/18/rendering-list-of-elements-in-react-with-jsx/
Hope it helps!
in my case just
const myReducers = combineReducers({
user: UserReducer
});
const store: any = createStore(
myReducers,
applyMiddleware(thunk)
);
shallow(<Login />, { context: { store } });
The simplest way is to edit the user settings and customise workbench.colorCustomizations
There is also the option modify the current theme which will copy the current theme settings and let you save it as a *.color-theme.json
JSON5 file
check if client_id
and package_name
in the google-services.json has a correct value according to your package name.
You should add the mentioned file into the flavors directory with corresponding package name in the client_id
and package_name
field.
use this URL : "https://twitter.com/(userName)/profile_image?size=original"
If you are using TWitter SDK you can get the user name when logged in, with TWTRAPIClient
, using TWTRAuthSession
.
This is the code snipe for iOS:
if let twitterId = session.userID{
let twitterClient = TWTRAPIClient(userID: twitterId)
twitterClient.loadUser(withID: twitterId) {(user, error) in
if let userName = user?.screenName{
let url = "https://twitter.com/\(userName)/profile_image?size=original")
}
}
}
In your main.ts file bootstrap after DOMContentLoaded so angular will load when DOM is fully loaded.
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
document.addEventListener('DOMContentLoaded', () => {
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.log(err));
});
'Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object'
Your export file can have the word default
as in export default class ____....
Then your import will need to avoid using {}
around it. As in import ____ from ____
Avoid using the default word. Then your export looks like export class ____...
Then your import must use the {}
. Like import {____} from ____
I Hope this is Helpfull
Step 1: App.js is (main module) import the Login Module
import React, { Component } from 'react';
import './App.css';
import Login from './login/login';
class App extends Component {
render() {
return (
<Login />
);
}
}
export default App;
Step 2: Create Login Folder and create login.js file and customize your needs it automatically render to App.js Example Login.js
import React, { Component } from 'react';
import '../login/login.css';
class Login extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
export default Login;
Obviously, as others have mentioned previously in this thread, in React JSX props.children
cannot be of type Object. This is NOT the root cause for the issue in your specific question.
If you carefully read the error text, you will see that React has produced the error while trying to render an Object that matches the signature of a SyntheticEvent
:
Uncaught Error: Invariant Violation: Objects are not valid as a React child (found: object with keys {dispatchConfig, dispatchMarker, nativeEvent, target, currentTarget, type, eventPhase, bubbles, cancelable, timeStamp, defaultPrevented, isTrusted, view, detail, screenX, screenY, clientX, clientY, ctrlKey, shiftKey, altKey, metaKey, getModifierState, button, buttons, relatedTarget, pageX, pageY, isDefaultPrevented, isPropagationStopped, _dispatchListeners, _dispatchIDs}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of Welcome.
However, one wonders why you are trying to render a SyntheticEvent
, and this is where the real answer to your question resides. You obviously have no intention of rendering a SyntheticEvent
, but you've got your event handler parameters out of order.
In your render
method, you are binding the onItemClick
event handler to the this
of your class component and passing in item
as an argument:
render() {
const items = ['EN', 'IT', 'FR', 'GR', 'RU'].map((item) => {
return (<li onClick={this.onItemClick.bind(this, item)} key={item}>{item}</li>);
});
// ...
According to the documentation for Function.prototype.bind
, all arguments passed after the thisArg
are prepended to any arguments subsequently passed when the target function is later invoked:
arg1, arg2, ...
Arguments to prepend to arguments provided to the bound function when invoking the target function.
If we then look at the event handler, we see that the parameter e
is listed before the parameter item
.
onItemClick(e, item) {
this.setState({
lang: item,
});
}
When onItemClick(e, item)
is invoked, the item
passed in during the bind
invocation will precede the triggering event
, so parameter e
will be set to the mapped and bound item
, and parameter item
will be set to the event
.
When setState
is called, lang
will be set to the SyntheticEvent
representing the triggering onClick
event, and when you try to render the value in this.state.lang
elsewhere, you will receive the Invariant Violation error you've seen.
I had the same issue today recently installing VS2015 Community Edition Update 1.
I fixed the problem by just adding the "SQL Server Data Tools" from the VS2015 setup installer... When I ran the installer the first time I selected the "Custom" installation type instead of the "Default". I wanted to see what install options were available but not select anything different than what was already ticked. My assumption was that whatever was already ticked was essentially the default install. But its not.
If all you want is the file name without file extension
Dim fileNamesCol As New Collection
Dim MyFile As Variant 'Strings and primitive data types aren't allowed with collection
filePath = "c:\file directory" + "\"
MyFile = Dir$(filePath & "*.xlsx")
Do While MyFile <> ""
fileNamesCol.Add (Replace(MyFile, ".xlsx", ""))
MyFile = Dir$
Loop
To output to excel worksheet
Dim myWs As Worksheet: Set myWs = Sheets("SheetNameToDisplayTo")
Dim ic As Integer: ic = 1
For Each MyFile In fileNamesCol
myWs.Range("A" & ic).Value = fileNamesCol(ic)
ic = ic + 1
Next MyFile
Primarily based on the technique detailed here: https://wordmvp.com/FAQs/MacrosVBA/ReadFilesIntoArray.htm
The best way is to declare the variable as a Single
or a Double
depending on the precision you need. The data type Single
utilizes 4 Bytes and has the range of -3.402823E38 to 1.401298E45. Double
uses 8 Bytes.
You can declare as follows:
Dim decAsdf as Single
or
Dim decAsdf as Double
Here is an example which displays a message box with the value of the variable after calculation. All you have to do is put it in a module and run it.
Sub doubleDataTypeExample()
Dim doubleTest As Double
doubleTest = 0.0000045 * 0.005 * 0.01
MsgBox "doubleTest = " & doubleTest
End Sub
Compilating answers here and there, here's a complete set of arr tools to get the work done:
Function getArraySize(arr As Variant)
' returns array size for a n dimention array
' usage result(k) = size of the k-th dimension
Dim ndims As Long
Dim arrsize() As Variant
ndims = getDimensions(arr)
ReDim arrsize(ndims - 1)
For i = 1 To ndims
arrsize(i - 1) = getDimSize(arr, i)
Next i
getArraySize = arrsize
End Function
Function getDimSize(arr As Variant, dimension As Integer)
' returns size for the given dimension number
getDimSize = UBound(arr, dimension) - LBound(arr, dimension) + 1
End Function
Function getDimensions(arr As Variant) As Long
' returns number of dimension in an array (ex. sheet range = 2 dimensions)
On Error GoTo Err
Dim i As Long
Dim tmp As Long
i = 0
Do While True
i = i + 1
tmp = UBound(arr, i)
Loop
Err:
getDimensions = i - 1
End Function
If you want to access any DOM element simply add ref
attribute and you can directly access that element.
<input type="text" ref="myinput">
And then you can directly:
componentDidMount: function()
{
this.refs.myinput.select();
},
Their is no need of using ReactDOM.findDOMNode()
, if you have added a ref
to any element.
Here is how to do it programatically:
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setNavigationBarColor(getResources().getColor(R.color.your_awesome_color));
}
Using Compat library:
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setNavigationBarColor(ContextCompat.getColor(this, R.color.primary));
}
Here is how to do it with xml in the values-v21/style.xml folder:
<item name="android:navigationBarColor">@color/your_color</item>
You need to deal with the optional Rank parameter of UBound
.
Dim arr(1 To 4, 1 To 3) As Variant
Debug.Print UBound(arr, 1) '? returns 4
Debug.Print UBound(arr, 2) '? returns 3
More at: UBound Function (Visual Basic)
In my case this error was caused by hot reloading, while introducing new classes. In that stage of the project, use normal watchers to compile your code.
Go to your Android SDK installed directory then extras > android > support > v7 > appcompat.
in my case : D:\Software\adt-bundle-windows-x86-20140702\sdk\extras\android\support\v7\appcompat
once you are in appcompat folder ,check for project.properties file then change the value from default 19 to 21 as :
target=android-21.
Save the file and then refresh your project.
Then clean the project: In project tab , select clean option then select your project and clean...
This will resolve the error. If not, make sure your project also targets API 21 or higher (same steps as before, and easily forgotten when upgrading a project which targets an older version). Enjoy coding...
This seems unnecessary, but VBA is a strange place. If you declare an array variable, then set it using Array()
then pass the variable into your function, VBA will be happy.
Sub test()
Dim fString As String
Dim arr() As Variant
arr = Array("foo", "bar")
fString = processArr(arr)
End Sub
Also your function processArr()
could be written as:
Function processArr(arr() As Variant) As String
processArr = Replace(Join(arr()), " ", "")
End Function
If you are into the whole brevity thing.
Adding into this: it depends on what your array is defined as. Consider:
dim a() as integer
dim b() as string
dim c() as variant
'these doesn't work
if isempty(a) then msgbox "integer arrays can be empty"
if isempty(b) then msgbox "string arrays can be empty"
'this is because isempty can only be tested on classes which have an .empty property
'this do work
if isempty(c) then msgbox "variants can be empty"
So, what can we do? In VBA, we can see if we can trigger an error and somehow handle it, for example
dim a() as integer
dim bEmpty as boolean
bempty=false
on error resume next
bempty=not isnumeric(ubound(a))
on error goto 0
But this is really clumsy... A nicer solution is to declare a boolean variable (a public or module level is best). When the array is first initialised, then set this variable. Because it's a variable declared at the same time, if it loses it's value, then you know that you need to reinitialise your array. However, if it is initialised, then all you're doing is checking the value of a boolean, which is low cost. It depends on whether being low cost matters, and if you're going to be needing to check it often.
option explicit
'declared at module level
dim a() as integer
dim aInitialised as boolean
sub DoSomethingWithA()
if not aInitialised then InitialiseA
'you can now proceed confident that a() is intialised
end sub
sub InitialiseA()
'insert code to do whatever is required to initialise A
'e.g.
redim a(10)
a(1)=123
'...
aInitialised=true
end sub
The last thing you can do is create a function; which in this case will need to be dependent on the clumsy on error method.
function isInitialised(byref a() as variant) as boolean
isInitialised=false
on error resume next
isinitialised=isnumeric(ubound(a))
end function
I searched for many pages of the web through of the Google and here on the Stack Overflow, but nothing suggested resolved my problem.
After many attempts, I've changed my way of to test that controller. Then I have discovered that the problem occurs always which I reopened the page through of the Ctrl + Shift + T
shortcut in Chrome. So the page ran, but without a parent window reference, and because this can't be closed.
For me the error was:
Error: unexpected input in "?"
and the fix was opening the script in a hex editor and removing the first 3 characters from the file. The file was starting with an UTF-8 BOM and it seems that Rscript can't read that.
EDIT: OP requested an example. Here it goes.
? ~ cat a.R
cat('hello world\n')
? ~ xxd a.R
00000000: efbb bf63 6174 2827 6865 6c6c 6f20 776f ...cat('hello wo
00000010: 726c 645c 6e27 290a rld\n').
? ~ R -f a.R
R version 3.4.4 (2018-03-15) -- "Someone to Lean On"
Copyright (C) 2018 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.
Natural language support but running in an English locale
R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.
Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.
> cat('hello world\n')
Error: unexpected input in "?"
Execution halted
ls -l --block-size=M
will give you a long format listing (needed to actually see the file size) and round file sizes up to the nearest MiB. If you want MB (10^6 bytes) rather than MiB (2^20 bytes) units, use --block-size=MB instead.
Or
ls -lah
-h When used with the -l option, use unit suffixes: Byte, Kilobyte, Megabyte, Gigabyte, Terabyte and Petabyte in order to reduce the number of digits to three or less using base 2 for sizes.
man ls
If you simply want to go to another page, then what you might need is a link that looks like a button with a href like so:
<a href="/#/somepage.html" class="button">Back to Listings</a>
Hope this helps.
Swift
Following UIView Extension will remove all Edge constraints of a view:
extension UIView {
func removeAllConstraints() {
if let _superview = self.superview {
self.removeFromSuperview()
_superview.addSubview(self)
}
}
}
I had this problem too. I made it to work by changing Log On account to Local System Account. In my project I had it setup to run as Local Service account. So when I installed it, by default it was using Local Service. I'm using .net 2.0 and VS 2005. So installing .net 1.1 SP1 wouldn't have helped.
***Try this***
buildTypes {
release {
lintOptions {
disable 'MissingTranslation'
checkReleaseBuilds false
abortOnError false
}
minifyEnabled false
signingConfig signingConfigs.release
}
}
Looking at Apple's sample code I came across this pattern. I'm not sure how Swift deals with statics, but this would be thread safe in C#. I include both the property and method for Objective-C interop.
struct StaticRank {
static let shared = RankMapping()
}
class func sharedInstance() -> RankMapping {
return StaticRank.shared
}
class var shared:RankMapping {
return StaticRank.shared
}
You get the error because if
can only evaluate a logical
vector of length 1.
Maybe you miss the difference between &
(|
) and &&
(||
). The shorter version works element-wise and the longer version uses only the first element of each vector, e.g.:
c(TRUE, TRUE) & c(TRUE, FALSE)
# [1] TRUE FALSE
# c(TRUE, TRUE) && c(TRUE, FALSE)
[1] TRUE
You don't need the if
statement at all:
mut1 <- trip$Ref.y=='G' & trip$Variant.y=='T'|trip$Ref.y=='C' & trip$Variant.y=='A'
trip[mut1, "mutType"] <- "G:C to T:A"
Closed formula for the longest int
(I used int
here, but works for any signed integral type):
1 + (int) ceil((8*sizeof(int)-1) * log10(2))
Explanation:
sizeof(int) // number bytes in int
8*sizeof(int) // number of binary digits (bits)
8*sizeof(int)-1 // discount one bit for the negatives
(8*sizeof(int)-1) * log10(2) // convert to decimal, because:
// 1 bit == log10(2) decimal digits
(int) ceil((8*sizeof(int)-1) * log10(2)) // round up to whole digits
1 + (int) ceil((8*sizeof(int)-1) * log10(2)) // make room for the minus sign
For an int
type of 4 bytes, the result is 11. An example of 4 bytes int
with 11 decimal digits is: "-2147483648".
If you want the number of decimal digits of some int
value, you can use the following function:
unsigned base10_size(int value)
{
if(value == 0) {
return 1u;
}
unsigned ret;
double dval;
if(value > 0) {
ret = 0;
dval = value;
} else {
// Make room for the minus sign, and proceed as if positive.
ret = 1;
dval = -double(value);
}
ret += ceil(log10(dval+1.0));
return ret;
}
I tested this function for the whole range of int
in g++ 9.3.0 for x86-64.
My own implementation of generic restTemplate call:
private <REQ, RES> RES queryRemoteService(String url, HttpMethod method, REQ req, Class reqClass) {
RES result = null;
try {
long startMillis = System.currentTimeMillis();
// Set the Content-Type header
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(new MediaType("application","json"));
// Set the request entity
HttpEntity<REQ> requestEntity = new HttpEntity<>(req, requestHeaders);
// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();
// Add the Jackson and String message converters
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
// Make the HTTP POST request, marshaling the request to JSON, and the response to a String
ResponseEntity<RES> responseEntity = restTemplate.exchange(url, method, requestEntity, reqClass);
result = responseEntity.getBody();
long stopMillis = System.currentTimeMillis() - startMillis;
Log.d(TAG, method + ":" + url + " took " + stopMillis + " ms");
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
return result;
}
To add some context, I'm consuming RESTful service with this, hence all requests and responses are wrapped into small POJO like this:
public class ValidateRequest {
User user;
User checkedUser;
Vehicle vehicle;
}
and
public class UserResponse {
User user;
RequestResult requestResult;
}
Method which calls this is the following:
public User checkUser(User user, String checkedUserName) {
String url = urlBuilder()
.add(USER)
.add(USER_CHECK)
.build();
ValidateRequest request = new ValidateRequest();
request.setUser(user);
request.setCheckedUser(new User(checkedUserName));
UserResponse response = queryRemoteService(url, HttpMethod.POST, request, UserResponse.class);
return response.getUser();
}
And yes, there's a List dto-s as well.
I just solved it. You need to install Entity Framework again in your solution. Follow any of the approaches.
First = Right Click your Solution or Project root and click Manage NuGet Packages
. Select 'EntityFramework', select the appropriate Projects and click Ok.
or
Second = Go to Console Package Manager and run Install-Package EntityFramework
.
Hope it helps.
Just for fun, here's a sample with a recursive function which (I hope) should be a bit simpler to understand and to use with your code:
Function Recurse(sPath As String) As String
Dim FSO As New FileSystemObject
Dim myFolder As Folder
Dim mySubFolder As Folder
Set myFolder = FSO.GetFolder(sPath)
For Each mySubFolder In myFolder.SubFolders
Call TestSub(mySubFolder.Path)
Recurse = Recurse(mySubFolder.Path)
Next
End Function
Sub TestR()
Call Recurse("D:\Projets\")
End Sub
Sub TestSub(ByVal s As String)
Debug.Print s
End Sub
Edit: Here's how you can implement this code in your workbook to achieve your objective.
Sub TestSub(ByVal s As String)
Dim FSO As New FileSystemObject
Dim myFolder As Folder
Dim myFile As File
Set myFolder = FSO.GetFolder(s)
For Each myFile In myFolder.Files
If myFile.Name = Range("E1").Value Then
Debug.Print myFile.Name 'Or do whatever you want with the file
End If
Next
End Sub
Here, I just debug the name of the found file, the rest is up to you. ;)
Of course, some would say it's a bit clumsy to call twice the FileSystemObject so you could simply write your code like this (depends on wether you want to compartmentalize or not):
Function Recurse(sPath As String) As String
Dim FSO As New FileSystemObject
Dim myFolder As Folder
Dim mySubFolder As Folder
Dim myFile As File
Set myFolder = FSO.GetFolder(sPath)
For Each mySubFolder In myFolder.SubFolders
For Each myFile In mySubFolder.Files
If myFile.Name = Range("E1").Value Then
Debug.Print myFile.Name & " in " & myFile.Path 'Or do whatever you want with the file
Exit For
End If
Next
Recurse = Recurse(mySubFolder.Path)
Next
End Function
Sub TestR()
Call Recurse("D:\Projets\")
End Sub
packagingOptions {
exclude 'META-INF/DEPENDENCIES.txt'
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/dependencies.txt'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/LICENSE'
exclude 'META-INF/license.txt'
exclude 'META-INF/LGPL2.1'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/notice.txt'
}
I've been playing around a little bit and came up with a simplified, more generic solution:
private static string sendHttpRequest(string url, NameValueCollection values, NameValueCollection files = null)
{
string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
// The first boundary
byte[] boundaryBytes = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
// The last boundary
byte[] trailer = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
// The first time it itereates, we need to make sure it doesn't put too many new paragraphs down or it completely messes up poor webbrick
byte[] boundaryBytesF = System.Text.Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
// Create the request and set parameters
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
// Get request stream
Stream requestStream = request.GetRequestStream();
foreach (string key in values.Keys)
{
// Write item to stream
byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}", key, values[key]));
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
requestStream.Write(formItemBytes, 0, formItemBytes.Length);
}
if (files != null)
{
foreach(string key in files.Keys)
{
if(File.Exists(files[key]))
{
int bytesRead = 0;
byte[] buffer = new byte[2048];
byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n", key, files[key]));
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
requestStream.Write(formItemBytes, 0, formItemBytes.Length);
using (FileStream fileStream = new FileStream(files[key], FileMode.Open, FileAccess.Read))
{
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
// Write file content to stream, byte by byte
requestStream.Write(buffer, 0, bytesRead);
}
fileStream.Close();
}
}
}
}
// Write trailer and close stream
requestStream.Write(trailer, 0, trailer.Length);
requestStream.Close();
using (StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream()))
{
return reader.ReadToEnd();
};
}
You can use it like this:
string fileLocation = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + Path.DirectorySeparatorChar + "somefile.jpg";
NameValueCollection values = new NameValueCollection();
NameValueCollection files = new NameValueCollection();
values.Add("firstName", "Alan");
files.Add("profilePicture", fileLocation);
sendHttpRequest("http://example.com/handler.php", values, files);
And in the PHP script you could handle data like this:
echo $_POST['firstName'];
$name = $_POST['firstName'];
$image = $_FILES['profilePicture'];
$ds = DIRECTORY_SEPARATOR;
move_uploaded_file($image['tmp_name'], realpath(dirname(__FILE__)) . $ds . "uploads" . $ds . $image['name']);
None of the above answers worked for me. I was going crazy until I found this solution below!
Simply run:
sudo apt install python-opencv
You can declare trk by the following ways : - either
trk : [{
lat : String,
lng : String
}]
or
trk : { type : Array , "default" : [] }
In the second case during insertion make the object and push it into the array like
db.update({'Searching criteria goes here'},
{
$push : {
trk : {
"lat": 50.3293714,
"lng": 6.9389939
} //inserted data is the object to be inserted
}
});
or you can set the Array of object by
db.update ({'seraching criteria goes here ' },
{
$set : {
trk : [ {
"lat": 50.3293714,
"lng": 6.9389939
},
{
"lat": 50.3293284,
"lng": 6.9389634
}
]//'inserted Array containing the list of object'
}
});
The Material Design Typography page has demos for some of these fonts and suggestions on choosing fonts and styles.
For code sleuths: fonts.xml
is the definitive and ever-expanding list of Android fonts.
Set the android:fontFamily
and android:textStyle
attributes, e.g.
<!-- Roboto Bold -->
<TextView
android:fontFamily="sans-serif"
android:textStyle="bold" />
to the desired values from this table:
Font | android:fontFamily | android:textStyle
-------------------------|-----------------------------|-------------------
Roboto Thin | sans-serif-thin |
Roboto Light | sans-serif-light |
Roboto Regular | sans-serif |
Roboto Bold | sans-serif | bold
Roboto Medium | sans-serif-medium |
Roboto Black | sans-serif-black |
Roboto Condensed Light | sans-serif-condensed-light |
Roboto Condensed Regular | sans-serif-condensed |
Roboto Condensed Medium | sans-serif-condensed-medium |
Roboto Condensed Bold | sans-serif-condensed | bold
Noto Serif | serif |
Noto Serif Bold | serif | bold
Droid Sans Mono | monospace |
Cutive Mono | serif-monospace |
Coming Soon | casual |
Dancing Script | cursive |
Dancing Script Bold | cursive | bold
Carrois Gothic SC | sans-serif-smallcaps |
(Noto Sans is a fallback font; you can't specify it directly)
Note: this table is derived from fonts.xml
. Each font's family name and style is listed in fonts.xml, e.g.
<family name="serif-monospace">
<font weight="400" style="normal">CutiveMono.ttf</font>
</family>
serif-monospace
is thus the font family, and normal
is the style.
Based on the log of fonts.xml and the former system_fonts.xml, you can see when each font was added:
It is nice that REST brings meaning to HTTP verbs (as they defined) but I prefer to agree with Scott Peal.
Here is also item from WIKI's extended explanation on POST request:
There are times when HTTP GET is less suitable even for data retrieval. An example of this is when a great deal of data would need to be specified in the URL. Browsers and web servers can have limits on the length of the URL that they will handle without truncation or error. Percent-encoding of reserved characters in URLs and query strings can significantly increase their length, and while Apache HTTP Server can handle up to 4,000 characters in a URL,[5] Microsoft Internet Explorer is limited to 2,048 characters in any URL.[6] Equally, HTTP GET should not be used where sensitive information, such as user names and passwords, have to be submitted along with other data for the request to complete. Even if HTTPS is used, preventing the data from being intercepted in transit, the browser history and the web server's logs will likely contain the full URL in plaintext, which may be exposed if either system is hacked. In these cases, HTTP POST should be used.[7]
I could only suggest to REST team to consider more secure use of HTTP protocol to avoid making consumers struggle with non-secure "good practice".
There are two issues here. The first is to access fields in the array returned by your JSON parse, the second is to rename collections/fields (like sentences) away from VBA reserved names.
Let's address the second concern first. You were on the right track. First, replace all instances of sentences
with jsentences
If text within your JSON also contains the word sentences, then figure out a way to make the replacement unique, such as using "sentences":[
as the search string. You can use the VBA Replace
method to do this.
Once that's done, so VBA will stop renaming sentences to Sentences, it's just a matter of accessing the array like so:
'first, declare the variables you need:
Dim jsent as Variant
'Get arr all setup, then
For Each jsent in arr.jsentences
MsgBox(jsent.orig)
Next
Try setting a custom CultureInfo for CurrentCulture and CurrentUICulture.
Globalization.CultureInfo customCulture = new Globalization.CultureInfo("en-US", true);
customCulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd h:mm tt";
System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = customCulture;
DateTime newDate = System.Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd h:mm tt"));
As message shows that we need to add provider System.Data.SqlClient that's why we need to install nuget package of EntityFramework that has two dll but if we are developing only console application then we just need to add reference of EntityFramework.SqlServer.dll
You don't need bindingSource1
Just set dataGridView1.DataSource = table;
JS:
$scope.options = [
{
name: "a",
id: 1
},
{
name: "b",
id: 2
}
];
$scope.selectedOption = $scope.options[1];
I was able to do this
>>> [x if x % 2 != 0 else x * 100 for x in range(1,10)]
[1, 200, 3, 400, 5, 600, 7, 800, 9]
>>>
In static class, if you are getting information from xml or reg, class tries to initialize all properties. therefore, you should control if the config variable is there otherwise properties will not initialize so the class.
Check xml referance variable is there, Check reg referance variable is is there, Make sure you handle if they are not there.
Don't use iterators to do this. Maintain your own loop by incrementing a counter in the callback, and recursively calling the operation on the next item.
$.each(myMap, function(_, arr) {
processArray(arr, 0);
});
function processArray(arr, i) {
if (i >= arr.length) return;
setTimeout(function () {
$('#variant').fadeOut("slow", function () {
$(this).text(i + "-" + arr[i]).fadeIn("slow");
// Handle next iteration
processArray(arr, ++i);
});
}, 6000);
}
Though there's a logic error in your code. You're setting the same container to more than one different value at (roughly) the same time. Perhaps you mean for each one to update its own container.
I know the question has been answered, but in my case I was trying to send the content of a text file to the Slack Webhook api and for some reason the above answer did not work. Anywho, this is what finally did the trick for me:
curl -X POST -H --silent --data-urlencode "payload={\"text\": \"$(cat file.txt | sed "s/\"/'/g")\"}" https://hooks.slack.com/services/XXX
First off target refers to the BlockID found in either HTML code or chromes developer tools that you are trying to link to. Each code is different and you will need to do some digging to find the ID you are trying to reference. It should look something like div class="page-container drawer-page-content" id"PageContainer"
Note that this is the format for the whole referenced section, not an individual text or image. To do that you would need to find the same piece of code but relating to your target block. For example dv id="your-block-id"
Anyways I was just reading over this thread and an idea came to my mind, if you are a Shopify user and want to do this it is pretty much the same thing as stated.
But instead of
> http://url.to.site/index.html#target
You would put
> http://storedomain.com/target
For example, I am setting up a disclaimer page with links leading to a newsletter signup and shopping blocks on my home page so I insert https://mystore-classifier.com/#shopify-section-1528945200235
for my hyperlink.
Please note that the -classifier is for my internal use and doesn't apply to you. This is just so I can keep track of my stores.
If you want to link to something other than your homepage you would put
> http://mystore-classifier.com/pagename/#BlockID
I hope someone found this useful, if there is something wrong with my explanation please let me know as I am not an HTML programmer my language is C#!
along with these two variants, there is also jade.renderFile
which generates html that need not be passed to the client.
usage-
var jade = require('jade');
exports.getJson = getJson;
function getJson(req, res) {
var html = jade.renderFile('views/test.jade', {some:'json'});
res.send({message: 'i sent json'});
}
getJson()
is available as a route in app.js.
class FlagAction(argparse.Action):
# From http://bugs.python.org/issue8538
def __init__(self, option_strings, dest, default=None,
required=False, help=None, metavar=None,
positive_prefixes=['--'], negative_prefixes=['--no-']):
self.positive_strings = set()
self.negative_strings = set()
for string in option_strings:
assert re.match(r'--[A-z]+', string)
suffix = string[2:]
for positive_prefix in positive_prefixes:
self.positive_strings.add(positive_prefix + suffix)
for negative_prefix in negative_prefixes:
self.negative_strings.add(negative_prefix + suffix)
strings = list(self.positive_strings | self.negative_strings)
super(FlagAction, self).__init__(option_strings=strings, dest=dest,
nargs=0, const=None, default=default, type=bool, choices=None,
required=required, help=help, metavar=metavar)
def __call__(self, parser, namespace, values, option_string=None):
if option_string in self.positive_strings:
setattr(namespace, self.dest, True)
else:
setattr(namespace, self.dest, False)
No need for array. Just use something like this:
Sub ARRAYER()
Dim Rng As Range
Dim Number_of_Sims As Long
Dim i As Long
Number_of_Sims = 10
Set Rng = Range("C4:G4")
For i = 1 To Number_of_Sims
Rng.Offset(i, 0).Value = Rng.Value
Worksheets("Sheetname").Calculate 'replacing Sheetname with name of your sheet
Next
End Sub
You can redirect stdout to nul
to hide it.
COPY %scriptDirectory%test.bat %scriptDirectory%test2.bat >nul
Just add >nul
to the commands you want to hide the output from.
Here you can see all the different ways of redirecting the std streams.
Late to the party, but the top voted answers all seemed like hacks to me.
All I did was remove the following from my app.config in the test project. Worked.
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:
Sub FilterAndCopy()
Dim LastRow As Long
Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
.Range("$A:$E").AutoFilter
.Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
.Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
.Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
.Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
.Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub
As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.
You may try the following:
System.Globalization.CultureInfo cultureinfo =
new System.Globalization.CultureInfo("nl-NL");
DateTime dt = DateTime.Parse(date, cultureinfo);
You're getting errors because you're attempting to read post variables that haven't been set, they only get set on form submission. Wrap your php code at the bottom in an
if ($_SERVER['REQUEST_METHOD'] === 'POST') { ... }
Also, your code is ripe for SQL injection. At the very least use mysql_real_escape_string
on the post vars before using them in SQL queries. mysql_real_escape_string
is not good enough for a production site, but should score you extra points in class.
Not for entire application or particular class.
CurrentUICulture and CurrentCulture are settable per thread as discussed here Is there a way of setting culture for a whole application? All current threads and new threads?. You can't change InvariantCulture
at all.
Sample code to change cultures for current thread:
CultureInfo ci = new CultureInfo(theCultureString);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
For class you can set/restore culture inside critical methods, but it would be significantly safe to use appropriate overrides for most formatting related methods that take culture as one of arguments:
(3.3).ToString(new CultureInfo("fr-FR"))
String test = DateTime.Now.ToString("dd.MM.yyy");
use Request.Form
to get the Data
Controller:
[HttpPost]
public ActionResult Index(int? id)
{
string jsonData= Request.Form[0]; // The data from the POST
}
I write this to try
View:
<input type="button" value="post" id="btnPost" />
<script type="text/javascript">
$(function () {
var test = {
number: 456,
name: "Ryu"
}
$("#btnPost").click(function () {
$.post('@Url.Action("Index", "Home")', JSON.stringify(test));
});
});
</script>
and write Request.Form[0]
or Request.Params[0]
in controller can get the data.
I don't write <form> tag
in view.
I just wrote this function that does what you want; try it out let me know if it doesn't work correctly for you:
// Test with an element.
var initElement = document.getElementsByTagName("html")[0];
var json = mapDOM(initElement, true);
console.log(json);
// Test with a string.
initElement = "<div><span>text</span>Text2</div>";
json = mapDOM(initElement, true);
console.log(json);
function mapDOM(element, json) {
var treeObject = {};
// If string convert to document Node
if (typeof element === "string") {
if (window.DOMParser) {
parser = new DOMParser();
docNode = parser.parseFromString(element,"text/xml");
} else { // Microsoft strikes again
docNode = new ActiveXObject("Microsoft.XMLDOM");
docNode.async = false;
docNode.loadXML(element);
}
element = docNode.firstChild;
}
//Recursively loop through DOM elements and assign properties to object
function treeHTML(element, object) {
object["type"] = element.nodeName;
var nodeList = element.childNodes;
if (nodeList != null) {
if (nodeList.length) {
object["content"] = [];
for (var i = 0; i < nodeList.length; i++) {
if (nodeList[i].nodeType == 3) {
object["content"].push(nodeList[i].nodeValue);
} else {
object["content"].push({});
treeHTML(nodeList[i], object["content"][object["content"].length -1]);
}
}
}
}
if (element.attributes != null) {
if (element.attributes.length) {
object["attributes"] = {};
for (var i = 0; i < element.attributes.length; i++) {
object["attributes"][element.attributes[i].nodeName] = element.attributes[i].nodeValue;
}
}
}
}
treeHTML(element, treeObject);
return (json) ? JSON.stringify(treeObject) : treeObject;
}
Working example: http://jsfiddle.net/JUSsf/ (Tested in Chrome, I can't guarantee full browser support - you will have to test this).
?It creates an object that contains the tree structure of the HTML page in the format you requested and then uses JSON.stringify()
which is included in most modern browsers (IE8+, Firefox 3+ .etc); If you need to support older browsers you can include json2.js.
It can take either a DOM element or a string
containing valid XHTML as an argument (I believe, I'm not sure whether the DOMParser()
will choke in certain situations as it is set to "text/xml"
or whether it just doesn't provide error handling. Unfortunately "text/html"
has poor browser support).
You can easily change the range of this function by passing a different value as element
. Whatever value you pass will be the root of your JSON map.
unset()
and initialization:unset($_POST);
$_POST = array();
Or in a single statement:
unset($_POST) ? $_POST = array() : $_POST = array();
But what is the reason you want to do this?
I ran into this same issue, it was because I was working with non-semantic html
<!--incorrect-->
<ul class="my-custom-font">
<button>
<a>user agent styles applied instead of my-custom-font</a>
<button>
</ul>
<!--correct-->
<ul class="my-custom-font">
<li>
<a>now inherits from from my-custom-font</a>
</li>
</ul>
Once the HTML was updated, styles were applied correctly
Ran into this issue today (Excel crashes on adding rows using .ListRows.Add
).
After reading this post and checking my table, I realized the calculations of the formula's in some of the cells in the row depend on a value in other cells.
In my case of cells in a higher column AND even cells with a formula!
The solution was to fill the new added row from back to front, so calculations would not go wrong.
Excel normally can deal with formula's in different cells, but it seems adding a row in a table kicks of a recalculation in order of the columns (A,B,C,etc..).
Hope this helps clearing issues with .ListRows.Add
You can use virtualenv --clear
. which won't install any packages, then install the ones you want.
var i2 = JsonConvert.DeserializeObject(obj["id"].ToString(), type);
throws a parsing exception due to missing quotes around the first argument (I think). I got it to work by adding the quotes:
var i2 = JsonConvert.DeserializeObject("\"" + obj["id"].ToString() + "\"", type);
To treat both , and . as decimal point you must not only replace one with the other, but also make sure the Culture used parsing interprets it as a decimal point.
text = text.Replace(',', '.');
return double.TryParse(text, NumberStyles.Any, CultureInfo.InvariantCulture, out value);
Adding to assylias's answer - assylias shows us D.ITEMS is a method that returns an array. Knowing that, we don't need the variant array a(i) [See caveat below]. We just need to use the proper array syntax.
For i = 0 To d.Count - 1
s = d.Items()(i)
Debug.Print s
Next i()
KEYS works the same way
For i = 0 To d.Count - 1
Debug.Print d.Keys()(i), d.Items()(i)
Next i
This syntax is also useful for the SPLIT function which may help make this clearer. SPLIT also returns an array with lower bounds at 0. Thus, the following prints "C".
Debug.Print Split("A,B,C,D", ",")(2)
SPLIT is a function. Its parameters are in the first set of parentheses. Methods and Functions always use the first set of parentheses for parameters, even if no parameters are needed. In the example SPLIT returns the array {"A","B","C","D"}. Since it returns an array we can use a second set of parentheses to identify an element within the returned array just as we would any array.
Caveat: This shorter syntax may not be as efficient as using the variant array a() when iterating through the entire dictionary since the shorter syntax invokes the dictionary's Items method with each iteration. The shorter syntax is best for plucking a single item by number from a dictionary.
There are many ways you can import Text file to the current sheet. Here are three (including the method that you are using above)
Cells.Copy
Using a QueryTable
Here is a simple macro that I recorded. Please amend it to suit your needs.
Sub Sample()
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Sample.txt", Destination:=Range("$A$1") _
)
.Name = "Sample"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
Open the text file in memory
Sub Sample()
Dim MyData As String, strData() As String
Open "C:\Sample.txt" For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
Close #1
strData() = Split(MyData, vbCrLf)
End Sub
Once you have the data in the array you can export it to the current sheet.
Using the method that you are already using
Sub Sample()
Dim wbI As Workbook, wbO As Workbook
Dim wsI As Worksheet
Set wbI = ThisWorkbook
Set wsI = wbI.Sheets("Sheet1") '<~~ Sheet where you want to import
Set wbO = Workbooks.Open("C:\Sample.txt")
wbO.Sheets(1).Cells.Copy wsI.Cells
wbO.Close SaveChanges:=False
End Sub
FOLLOWUP
You can use the Application.GetOpenFilename
to choose the relevant file. For example...
Sub Sample()
Dim Ret
Ret = Application.GetOpenFilename("Prn Files (*.prn), *.prn")
If Ret <> False Then
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & Ret, Destination:=Range("$A$1"))
'~~> Rest of the code
End With
End If
End Sub
Since there doesn't seem to be a .Net-culture that yields the correct ISO-8601 week number, I'd rather bypass the built-in week determination altogether, and do the calculation manually, instead of attempting to correct a partially correct result.
What I ended up with is the following extension method:
/// <summary>
/// Converts a date to a week number.
/// ISO 8601 week 1 is the week that contains the first Thursday that year.
/// </summary>
public static int ToIso8601Weeknumber(this DateTime date)
{
var thursday = date.AddDays(3 - date.DayOfWeek.DayOffset());
return (thursday.DayOfYear - 1) / 7 + 1;
}
/// <summary>
/// Converts a week number to a date.
/// Note: Week 1 of a year may start in the previous year.
/// ISO 8601 week 1 is the week that contains the first Thursday that year, so
/// if December 28 is a Monday, December 31 is a Thursday,
/// and week 1 starts January 4.
/// If December 28 is a later day in the week, week 1 starts earlier.
/// If December 28 is a Sunday, it is in the same week as Thursday January 1.
/// </summary>
public static DateTime FromIso8601Weeknumber(int weekNumber, int? year = null, DayOfWeek day = DayOfWeek.Monday)
{
var dec28 = new DateTime((year ?? DateTime.Today.Year) - 1, 12, 28);
var monday = dec28.AddDays(7 * weekNumber - dec28.DayOfWeek.DayOffset());
return monday.AddDays(day.DayOffset());
}
/// <summary>
/// Iso8601 weeks start on Monday. This returns 0 for Monday.
/// </summary>
private static int DayOffset(this DayOfWeek weekDay)
{
return ((int)weekDay + 6) % 7;
}
First of all, ((int)date.DayOfWeek + 6) % 7)
determines the weekday number, 0=monday, 6=sunday.
date.AddDays(-((int)date.DayOfWeek + 6) % 7)
determines the date of the monday preceiding the requested week number.
Three days later is the target thursday, which determines what year the week is in.
If you divide the (zero based) day-number within the year by seven (round down), you get the (zero based) week number in the year.
In c#, integer calculation results are round down implicitly.
Using the code from my answer to a very similar question:
Sub DoSomething()
Dim Mainfram(4) As String
Dim cell As Excel.Range
Mainfram(0) = "apple"
Mainfram(1) = "pear"
Mainfram(2) = "orange"
Mainfram(3) = "fruit"
For Each cell In Selection
If IsInArray(cell.Value, MainFram) Then
Row(cell.Row).Style = "Accent1"
End If
Next cell
End Sub
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function
You have to select the sheet before you can select the range.
I've simplified the example to isolate the problem. Try this:
Option Explicit
Sub RangeError()
Dim sourceBook As Workbook
Dim sourceSheet As Worksheet
Dim sourceSheetSum As Worksheet
Set sourceBook = ActiveWorkbook
Set sourceSheet = sourceBook.Sheets("Sheet1")
Set sourceSheetSum = sourceBook.Sheets("Sheet2")
sourceSheetSum.Select
sourceSheetSum.Range("C3").Select 'THIS IS THE PROBLEM LINE
End Sub
Replace Sheet1 and Sheet2 with your sheet names.
IMPORTANT NOTE: Using Variants is dangerous and can lead to difficult-to-kill bugs. Use them only if you have a very specific reason for doing so.
Dir seems to be very fast.
Sub LoopThroughFiles()
Dim MyObj As Object, MySource As Object, file As Variant
file = Dir("c:\testfolder\")
While (file <> "")
If InStr(file, "test") > 0 Then
MsgBox "found " & file
Exit Sub
End If
file = Dir
Wend
End Sub
Referring to the answers above, I am only adding this to help clarify things. It is possible to use HttpClient from .Net 4.0, and you have to install the package from here
However, the text is very confusion and contradicts itself.
This package is not supported in Visual Studio 2010, and is only required for projects targeting .NET Framework 4.5, Windows 8, or Windows Phone 8.1 when consuming a library that uses this package.
But underneath it states that these are the supported platforms.
Supported Platforms:
.NET Framework 4
Windows 8
Windows Phone 8.1
Windows Phone Silverlight 7.5
Silverlight 4
Portable Class Libraries
Ignore what it ways about targeting .Net 4.5. This is wrong. The package is all about using HttpClient in .Net 4.0. However, you may need to use VS2012 or higher. Not sure if it works in VS2010, but that may be worth testing.
With Java 8 it is so simple so it doesn't even need separate method anymore:
List<Integer> range = IntStream.rangeClosed(start, end)
.boxed().collect(Collectors.toList());
You can use zip
:
>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> for x, y in zip(a, b):
... print x, y
...
1 a
2 b
3 c
Below config worked for me. Refer this link for more details.
<dependency>
<groupId>com.oracle.jdbc</groupId>
<artifactId>ojdbc7</artifactId>
<version>12.1.0.2</version>
</dependency>
This variant looks more simple and elegant.
CollectionType typeReference =
TypeFactory.defaultInstance().constructCollectionType(List.class, Dto.class);
List<Dto> resultDto = objectMapper.readValue(content, typeReference);
For things like numbers (decimal points, commas in amounts), they are usually preferred in the specific culture.
A appropriate way to do this would be set it at the culture level (for German) like this:
Thread.CurrentThread.CurrentCulture.NumberFormat = new CultureInfo("de").NumberFormat;
If your 13 digit "number" is really text, that is you don't intend to do any math on it, you can precede it with an apostrophe
Sheet3.Range("c" & k).Value = "'" & Sheet2.Range("c" & i).Value
But I don't see how a 13 digit number would ever get past the If statement because it would always be greater than 1000. Here's an alternate version
Sub CommandClick()
Dim rCell As Range
Dim rNext As Range
For Each rCell In Sheet2.Range("C1:C30000").Cells
If rCell.Value >= 100 And rCell.Value < 1000 Then
Set rNext = Sheet3.Cells(Sheet3.Rows.Count, 1).End(xlUp).Offset(1, 0)
rNext.Resize(1, 3).Value = rCell.Offset(0, -2).Resize(1, 3).Value
End If
Next rCell
End Sub
I would write GetValue
as below
public static T GetValue<T>(this JToken jToken, string key, T defaultValue = default(T))
{
dynamic ret = jToken[key];
if (ret == null) return defaultValue;
if (ret is JObject) return JsonConvert.DeserializeObject<T>(ret.ToString());
return (T)ret;
}
This way you can get the value of not only the basic types but also complex objects. Here is a sample
public class ClassA
{
public int I;
public double D;
public ClassB ClassB;
}
public class ClassB
{
public int I;
public string S;
}
var jt = JToken.Parse("{ I:1, D:3.5, ClassB:{I:2, S:'test'} }");
int i1 = jt.GetValue<int>("I");
double d1 = jt.GetValue<double>("D");
ClassB b = jt.GetValue<ClassB>("ClassB");
This function reads a CSV file of 15MB and copies its content into a sheet in about 3 secs. What is probably taking a lot of time in your code is the fact that you copy data cell by cell instead of putting the whole content at once.
Option Explicit
Public Sub test()
copyDataFromCsvFileToSheet "C:\temp\test.csv", ",", "Sheet1"
End Sub
Private Sub copyDataFromCsvFileToSheet(parFileName As String, parDelimiter As String, parSheetName As String)
Dim data As Variant
data = getDataFromFile(parFileName, parDelimiter)
If Not isArrayEmpty(data) Then
With Sheets(parSheetName)
.Cells.ClearContents
.Cells(1, 1).Resize(UBound(data, 1), UBound(data, 2)) = data
End With
End If
End Sub
Public Function isArrayEmpty(parArray As Variant) As Boolean
'Returns false if not an array or dynamic array that has not been initialised (ReDim) or has been erased (Erase)
If IsArray(parArray) = False Then isArrayEmpty = True
On Error Resume Next
If UBound(parArray) < LBound(parArray) Then isArrayEmpty = True: Exit Function Else: isArrayEmpty = False
End Function
Private Function getDataFromFile(parFileName As String, parDelimiter As String, Optional parExcludeCharacter As String = "") As Variant
'parFileName is supposed to be a delimited file (csv...)
'parDelimiter is the delimiter, "," for example in a comma delimited file
'Returns an empty array if file is empty or can't be opened
'number of columns based on the line with the largest number of columns, not on the first line
'parExcludeCharacter: sometimes csv files have quotes around strings: "XXX" - if parExcludeCharacter = """" then removes the quotes
Dim locLinesList() As Variant
Dim locData As Variant
Dim i As Long
Dim j As Long
Dim locNumRows As Long
Dim locNumCols As Long
Dim fso As Variant
Dim ts As Variant
Const REDIM_STEP = 10000
Set fso = CreateObject("Scripting.FileSystemObject")
On Error GoTo error_open_file
Set ts = fso.OpenTextFile(parFileName)
On Error GoTo unhandled_error
'Counts the number of lines and the largest number of columns
ReDim locLinesList(1 To 1) As Variant
i = 0
Do While Not ts.AtEndOfStream
If i Mod REDIM_STEP = 0 Then
ReDim Preserve locLinesList(1 To UBound(locLinesList, 1) + REDIM_STEP) As Variant
End If
locLinesList(i + 1) = Split(ts.ReadLine, parDelimiter)
j = UBound(locLinesList(i + 1), 1) 'number of columns
If locNumCols < j Then locNumCols = j
i = i + 1
Loop
ts.Close
locNumRows = i
If locNumRows = 0 Then Exit Function 'Empty file
ReDim locData(1 To locNumRows, 1 To locNumCols + 1) As Variant
'Copies the file into an array
If parExcludeCharacter <> "" Then
For i = 1 To locNumRows
For j = 0 To UBound(locLinesList(i), 1)
If Left(locLinesList(i)(j), 1) = parExcludeCharacter Then
If Right(locLinesList(i)(j), 1) = parExcludeCharacter Then
locLinesList(i)(j) = Mid(locLinesList(i)(j), 2, Len(locLinesList(i)(j)) - 2) 'If locTempArray = "", Mid returns ""
Else
locLinesList(i)(j) = Right(locLinesList(i)(j), Len(locLinesList(i)(j)) - 1)
End If
ElseIf Right(locLinesList(i)(j), 1) = parExcludeCharacter Then
locLinesList(i)(j) = Left(locLinesList(i)(j), Len(locLinesList(i)(j)) - 1)
End If
locData(i, j + 1) = locLinesList(i)(j)
Next j
Next i
Else
For i = 1 To locNumRows
For j = 0 To UBound(locLinesList(i), 1)
locData(i, j + 1) = locLinesList(i)(j)
Next j
Next i
End If
getDataFromFile = locData
Exit Function
error_open_file: 'returns empty variant
unhandled_error: 'returns empty variant
End Function
Extending the accepted answer for a common usecase. In particular:
View the circles at a natural aspect ratio.
Automatically extend the axes limits to include the newly plotted circles.
Self-contained example:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.add_patch(plt.Circle((0, 0), 0.2, color='r', alpha=0.5))
ax.add_patch(plt.Circle((1, 1), 0.5, color='#00ffff', alpha=0.5))
ax.add_artist(plt.Circle((1, 0), 0.5, color='#000033', alpha=0.5))
#Use adjustable='box-forced' to make the plot area square-shaped as well.
ax.set_aspect('equal', adjustable='datalim')
ax.plot() #Causes an autoscale update.
plt.show()
Note the difference between ax.add_patch(..)
and ax.add_artist(..)
: of the two, only the former makes autoscaling machinery take the circle into account (reference: discussion), so after running the above code we get:
See also: set_aspect(..)
documentation.
I edited the method created by batbaatar above so it accepts the Configuration object as a parameter:
public static SessionFactory createSessionFactory(Configuration configuration) {
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
factory = configuration.buildSessionFactory(serviceRegistry);
return factory;
}
In the main class I did:
private static SessionFactory factory;
private static Configuration configuration
...
configuration = new Configuration();
configuration.configure().addAnnotatedClass(Employee.class);
// Other configurations, then
factory = createSessionFactory(configuration);
Your format string is wrong. Change it to
insert = DateTime.ParseExact(line[i], "M/d/yyyy hh:mm", CultureInfo.InvariantCulture);
This blog post explains very well:
(just replace 9.X by your version. e.g: 9.6)
A. If installed PostgreSQL with homebrew, enter brew uninstall postgresql
B. If you used the EnterpriseDB installer, follow the following step.
Run the uninstaller on terminal window: sudo /Library/PostgreSQL/9.X/uninstall-postgresql.app/Contents/MacOS/installbuilder.sh
C. If installed with Postgres Installer, do:
open /Library/PostgreSQL/9.X/uninstall-postgresql.app
Remove the PostgreSQL and data folders. The Wizard will notify you that these were not removed.
sudo rm -rf /Library/PostgreSQL
Remove the ini file:
sudo rm /etc/postgres-reg.ini
Remove the PostgreSQL user using System Preferences -> Users & Groups.
Unlock the settings panel by clicking on the padlock and entering your password.
Select the PostgreSQL user and click on the minus button.
Restore your shared memory settings: sudo rm /etc/sysctl.conf
Add bottom:100%
to your #menu:hover ul li:hover ul
rule
#menu:hover ul li:hover ul {
position: absolute;
margin-top: 1px;
font: 10px;
bottom: 100%; /* added this attribute */
}
Or better yet to prevent the submenus from having the same effect, just add this rule
#menu>ul>li:hover>ul {
bottom:100%;
}
source: http://jsfiddle.net/W5FWW/4/
And to get back the border you can add the following attribute
#menu>ul>li:hover>ul {
bottom:100%;
border-bottom: 1px solid transparent
}
Here's the issue: You can't specify font weights that don't exist in the font set from Google. Click on the SEE SPECIMEN link below the font, then scroll down to the STYLES section. There you'll see each of the "styles" available for that particular font. Sadly Google doesn't list the CSS font weights for each style. Here's how the names map to CSS font weight numbers:
Thin 100
Extra Light 200
Light 300
Regular 400
Medium 500
Semi-Bold 600
Bold 700
Extra-Bold 800
Black 900
Note that very few fonts come in all 9 weights.
Assign the onclick like this:
divTag.onclick = printWorking;
The onclick property will not take a string when assigned. Instead, it takes a function reference (in this case, printWorking
).
The onclick attribute can be a string when assigned in HTML, e.g. <div onclick="func()"></div>
, but this is generally not recommended.
I had a similer problem with SqlClient on WCF service. My solution was to put that lines in client app.config
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
</startup>
Hopes it helps for someone..
It doesn't work because it doesn't make sense (so little sense that HTML 5 explicitly forbids it).
To fix it, decide if you want a link or a submit button and use whichever one you actually want (Hint: You don't have a form, so a submit button is nonsense).
My general answer to this kind of question on "efficiency" is almost always, which ever version of the code is most readable, is the most efficient.
That being said, I think (val.ToLowerCase() == "astringvalue")
is pretty understandable at a glance by most people.
The efficience I refer to is not necesseraly in the execution of the code but rather in the maintanance and generally readability of the code in question.
Actually I don't see any nulls:
given:
static void Main()
{
string[] testArray = new string[]
{
"aa",
"ab",
"ac",
"ad",
"ab",
"af"
};
Array.Sort(testArray, StringComparer.InvariantCulture);
Array.ForEach(testArray, x => Console.WriteLine(x));
}
I obtained:
Usually assertions don't survive the contact with real world data. It's a part of the process of software engineering to decide, with which data you want to deal and which are out of scope.
Regarding family "trees" (in fact it are full blown graphs, including cycles), there is a nice anecdote:
I married a widow who had a grown daughter. My father, who often visited us, fell in love with my step-daughter and married her. As a result, my father became my son, and my daughter became my mother. Some time later, I gave my wife a son, who was the brother of my father, and my uncle. My father's wife (who is also my daughter and my mother) got a son. As a result, I got a brother and a grandson in the same person. My wife is now my grandmother, because she is my mother's mother. So I am the husband of my wife, and at the same time the step-grandson of my wife. In other words, I'm my own grandpa.
Things get even more strange, when you take surrogates or "fuzzy fatherhood" into account.
You could decide that your software should not deal with such rare cases. If such a case occurs, the user should use a different product. This makes dealing with the more common cases much more robust, because you can keep more assertions and a simpler data model.
In this case, add some good import and export features to your software, so the user can easily migrate to a different product when necessary.
You could allow the user to add manual relations. These relations are not "first-class citizens", i.e. the software takes them as-is, doesn't check them and doesn't handle them in the main data model.
The user can then handle rare cases by hand. Your data model will still stay quite simple and your assertions will survive.
Be careful with manual relations. There is a temptation to make them completely configurable and hence create a fully configurable data model. This will not work: Your software will not scale, you will get strange bugs and finally the user interface will become unusable. This anti-pattern is called "soft coding", and "The daily WTF" is full of examples for that.
The last resort would be making your data model more flexible. You would have to skip nearly all assertions and base your data model on a full blown graph. As the above example shows, it is easily possible to be your own grandfather, so you can even have cycles.
In this case, you should extensively test your software. You had to skip nearly all assertions, so there is a good chance for additional bugs.
Use a test data generator to check unusual test cases. There are quick check libraries for Haskell, Erlang or C. For Java / Scala there are ScalaCheck and Nyaya. One test idea would be to simulate a random population, let it interbreed at random, then let your software first import and then export the result. The expectation would be, that all connections in the output are also in the input and vice verse.
A case, where a property stays the same is called an invariant. In this case, the invariant is the set of "romantic relations" between the individuals in the simulated population. Try to find as much invariants as possible and test them with randomly generated data. Invariants can be functional, e.g.:
Or they can be technical:
By running the simulated tests, you will find lots of strange corner cases. Fixing them will take a lot of time. Also you will lose a lot of optimizations, your software will run much slower. You have to decide, if it is worth it and if this is in the scope of your software.
This might help you out:
Sub SelectFolder()
Dim diaFolder As FileDialog
Dim Fname As String
Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
diaFolder.AllowMultiSelect = False
diaFolder.Show
Fname = diaFolder.SelectedItems(1)
ActiveSheet.Range("B9") = Fname
End Sub
Further to RolandTumble's answer to Cody Gray's answer, both fine answers, here is another very simple and flexible way, when you know all of the array contents at coding time - e.g. you just want to build an array that contains 1, 10, 20 and 50. This also uses variant declaration, but doesn't use ReDim. Like in Roland's answer, the enumerated count of the number of array elements need not be specifically known, but is obtainable by using uBound.
sub Demo_array()
Dim MyArray as Variant, MyArray2 as Variant, i as Long
MyArray = Array(1, 10, 20, 50) 'The key - the powerful Array() statement
MyArray2 = Array("Apple", "Pear", "Orange") 'strings work too
For i = 0 to UBound(MyArray)
Debug.Print i, MyArray(i)
Next i
For i = 0 to UBound(MyArray2)
Debug.Print i, MyArray2(i)
Next i
End Sub
I love this more than any of the other ways to create arrays. What's great is that you can add or subtract members of the array right there in the Array statement, and nothing else need be done to code. To add Egg to your 3 element food array, you just type
, "Egg"
in the appropriate place, and you're done. Your food array now has the 4 elements, and nothing had to be modified in the Dim, and ReDim is omitted entirely.
If a 0-based array is not desired - i.e., using MyArray(0) - one solution is just to jam a 0 or "" for that first element.
Note, this might be regarded badly by some coding purists; one fair objection would be that "hard data" should be in Const statements, not code statements in routines. Another beef might be that, if you stick 36 elements into an array, you should set a const to 36, rather than code in ignorance of that. The latter objection is debatable, because it imposes a requirement to maintain the Const with 36 rather than relying on uBound. If you add a 37th element but leave the Const at 36, trouble is possible.
From python 3.4.4, you can use multiprocessing.get_context() to obtain a context object to use multiple start methods:
import multiprocessing as mp
def foo(q, h, w):
q.put(h + ' ' + w)
print(h + ' ' + w)
if __name__ == '__main__':
ctx = mp.get_context('spawn')
q = ctx.Queue()
p = ctx.Process(target=foo, args=(q,'hello', 'world'))
p.start()
print(q.get())
p.join()
Or you just simply replace
pool.map(harvester(text,case),case, 1)
by:
pool.apply_async(harvester(text,case),case, 1)
Small change to @Chris Lang answer. if you want Monday as the first day use this.
Date.prototype.GetFirstDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay()+ (this.getDay() == 0 ? -6:1) )));
}
Date.prototype.GetLastDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay() +7)));
}
var today = new Date();
alert(today.GetFirstDayOfWeek());
alert(today.GetLastDayOfWeek());
Thaks @Chris Lang
Improved Lukas Knuth's version:
public class TweakedWebView extends WebView {
private ZoomButtonsController zoomButtons;
public TweakedWebView(Context context) {
super(context);
init();
}
public TweakedWebView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public TweakedWebView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
getSettings().setBuiltInZoomControls(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getSettings().setDisplayZoomControls(false);
} else {
try {
Method method = getClass()
.getMethod("getZoomButtonsController");
zoomButtons = (ZoomButtonsController) method.invoke(this);
} catch (Exception e) {
// pass
}
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
boolean result = super.onTouchEvent(ev);
if (zoomButtons != null) {
zoomButtons.setVisible(false);
zoomButtons.getZoomControls().setVisibility(View.GONE);
}
return result;
}
}
I found the solution.
As said in the EDIT of my answer, a <div>
is misfunctioning in a <table>
.
So I wrote this code instead :
<tr id="hidden" style="display:none;">
<td class="depot_table_left">
<label for="sexe">Sexe</label>
</td>
<td>
<select type="text" name="sexe">
<option value="1">Sexe</option>
<option value="2">Joueur</option>
<option value="3">Joueuse</option>
</select>
</td>
</tr>
And this is working fine.
Thanks everybody ;)
Running PHP as a CGI means that you basically tell your web server the location of the PHP executable file, and the server runs that executable
whereas
PHP FastCGI Process Manager (PHP-FPM) is an alternative FastCGI daemon for PHP that allows a website to handle strenuous loads. PHP-FPM maintains pools (workers that can respond to PHP requests) to accomplish this. PHP-FPM is faster than traditional CGI-based methods, such as SUPHP, for multi-user PHP environments
However, there are pros and cons to both and one should choose as per their specific use case.
I found info on this link for fastcgi vs fpm quite helpful in choosing which handler to use in my scenario.
This method is easy to understand and works fine. The argument to the script ($1
) is a reference (tag, hash, ...) to the commit starting from which you want to keep your history.
#!/bin/bash
git checkout --orphan temp $1 # create a new branch without parent history
git commit -m "Truncated history" # create a first commit on this branch
git rebase --onto temp $1 master # now rebase the part of master branch that we want to keep onto this branch
git branch -D temp # delete the temp branch
# The following 2 commands are optional - they keep your git repo in good shape.
git prune --progress # delete all the objects w/o references
git gc --aggressive # aggressively collect garbage; may take a lot of time on large repos
NOTE that old tags will still remain present; so you might need to remove them manually
remark: I know this is almost the same aswer as @yoyodin, but there are some important extra commands and informations here. I tried to edit the answer, but since it is a substantial change to @yoyodin's answer, my edit was rejected, so here's the information!
Hmm... I can't reproduce this:
using System;
class Test
{
static void Main()
{
decimal d = decimal.Parse("1200.00");
Console.WriteLine(d); // Prints 1200.00
}
}
Are you sure it's not some other part of your code normalizing the decimal value later?
Just in case it's cultural issues, try this version which shouldn't depend on your locale at all:
using System;
using System.Globalization;
class Test
{
static void Main()
{
decimal d = decimal.Parse("1200.00", CultureInfo.InvariantCulture);
Console.WriteLine(d.ToString(CultureInfo.InvariantCulture));
}
}
You are using:
expect(fn).toThrow(e)
But if you'll have a look on the function comment (expected is string):
294 /**
295 * Matcher that checks that the expected exception was thrown by the actual.
296 *
297 * @param {String} expected
298 */
299 jasmine.Matchers.prototype.toThrow = function(expected) {
I suppose you should probably write it like this (using lambda - anonymous function):
expect(function() { parser.parse(raw); } ).toThrow("Parsing is not possible");
This is confirmed in the following example:
expect(function () {throw new Error("Parsing is not possible")}).toThrow("Parsing is not possible");
Douglas Crockford strongly recommends this approach, instead of using "throw new Error()" (prototyping way):
throw {
name: "Error",
message: "Parsing is not possible"
}
You can simply use decimal.ToString()
For two decimals
myDecimal.ToString("0.00");
For four decimals
myDecimal.ToString("0.0000");
This gives dot as decimal separator, and no thousand separator regardless of culture.
My favorite answer is as what the first sentence in this thread suggested. Use an Adjacency List to maintain the hierarchy and use Nested Sets to query the hierarchy.
The problem up until now has been that the coversion method from an Adjacecy List to Nested Sets has been frightfully slow because most people use the extreme RBAR method known as a "Push Stack" to do the conversion and has been considered to be way to expensive to reach the Nirvana of the simplicity of maintenance by the Adjacency List and the awesome performance of Nested Sets. As a result, most people end up having to settle for one or the other especially if there are more than, say, a lousy 100,000 nodes or so. Using the push stack method can take a whole day to do the conversion on what MLM'ers would consider to be a small million node hierarchy.
I thought I'd give Celko a bit of competition by coming up with a method to convert an Adjacency List to Nested sets at speeds that just seem impossible. Here's the performance of the push stack method on my i5 laptop.
Duration for 1,000 Nodes = 00:00:00:870
Duration for 10,000 Nodes = 00:01:01:783 (70 times slower instead of just 10)
Duration for 100,000 Nodes = 00:49:59:730 (3,446 times slower instead of just 100)
Duration for 1,000,000 Nodes = 'Didn't even try this'
And here's the duration for the new method (with the push stack method in parenthesis).
Duration for 1,000 Nodes = 00:00:00:053 (compared to 00:00:00:870)
Duration for 10,000 Nodes = 00:00:00:323 (compared to 00:01:01:783)
Duration for 100,000 Nodes = 00:00:03:867 (compared to 00:49:59:730)
Duration for 1,000,000 Nodes = 00:00:54:283 (compared to something like 2 days!!!)
Yes, that's correct. 1 million nodes converted in less than a minute and 100,000 nodes in under 4 seconds.
You can read about the new method and get a copy of the code at the following URL. http://www.sqlservercentral.com/articles/Hierarchy/94040/
I also developed a "pre-aggregated" hierarchy using similar methods. MLM'ers and people making bills of materials will be particularly interested in this article. http://www.sqlservercentral.com/articles/T-SQL/94570/
If you do stop by to take a look at either article, jump into the "Join the discussion" link and let me know what you think.
You can use the expandable list view explained in API demos to show groups
To animate the list items motion, you will have to override the getView method and apply translate animation on each list item. The values for animation depend on the position of each list item. This was something which i tried on a simple list view long time back.
At the moment I write this, TCPDF only supports padding for tables.
You can define and assign value as shown below in one line. I have given an example of two variables declared and assigned in single line. if the data type of multiple variables are same
Dim recordStart, recordEnd As Integer: recordStart = 935: recordEnd = 946
In simple words, a loop invariant is some predicate (condition) that holds for every iteration of the loop. For example, let's look at a simple for
loop that looks like this:
int j = 9;
for(int i=0; i<10; i++)
j--;
In this example it is true (for every iteration) that i + j == 9
. A weaker invariant that is also true is that
i >= 0 && i <= 10
.
For deleting a dynamic array in VBA use the instruction Erase
.
Example:
Dim ArrayDin() As Integer
ReDim ArrayDin(10) 'Dynamic allocation
Erase ArrayDin 'Erasing the Array
Hope this help!
Neither code is always better. They do different things, so they are good at different things.
InvariantCultureIgnoreCase
uses comparison rules based on english, but without any regional variations. This is good for a neutral comparison that still takes into account some linguistic aspects.
OrdinalIgnoreCase
compares the character codes without cultural aspects. This is good for exact comparisons, like login names, but not for sorting strings with unusual characters like é
or ö
. This is also faster because there are no extra rules to apply before comparing.
Two of them always produce the same answer:
COUNT(*)
counts the number of rowsCOUNT(1)
also counts the number of rowsAssuming the pk
is a primary key and that no nulls are allowed in the values, then
COUNT(pk)
also counts the number of rowsHowever, if pk
is not constrained to be not null, then it produces a different answer:
COUNT(possibly_null)
counts the number of rows with non-null values in the column possibly_null
.
COUNT(DISTINCT pk)
also counts the number of rows (because a primary key does not allow duplicates).
COUNT(DISTINCT possibly_null_or_dup)
counts the number of distinct non-null values in the column possibly_null_or_dup
.
COUNT(DISTINCT possibly_duplicated)
counts the number of distinct (necessarily non-null) values in the column possibly_duplicated
when that has the NOT NULL
clause on it.
Normally, I write COUNT(*)
; it is the original recommended notation for SQL. Similarly, with the EXISTS
clause, I normally write WHERE EXISTS(SELECT * FROM ...)
because that was the original recommend notation. There should be no benefit to the alternatives; the optimizer should see through the more obscure notations.
The simple answer is to use the HttpRequest.UserHostAddress property.
Example: From within a Controller:
using System;
using System.Web.Mvc;
namespace Mvc.Controllers
{
public class HomeController : ClientController
{
public ActionResult Index()
{
string ip = Request.UserHostAddress;
...
}
}
}
Example: From within a helper class:
using System.Web;
namespace Mvc.Helpers
{
public static class HelperClass
{
public static string GetIPHelper()
{
string ip = HttpContext.Current.Request.UserHostAddress;
..
}
}
}
BUT, if the request has been passed on by one, or more, proxy servers then the IP address returned by HttpRequest.UserHostAddress property will be the IP address of the last proxy server that relayed the request.
Proxy servers MAY use the de facto standard of placing the client's IP address in the X-Forwarded-For HTTP header. Aside from there is no guarantee that a request has a X-Forwarded-For header, there is also no guarantee that the X-Forwarded-For hasn't been SPOOFED.
Original Answer
Request.UserHostAddress
The above code provides the Client's IP address without resorting to looking up a collection. The Request property is available within Controllers (or Views). Therefore instead of passing a Page class to your function you can pass a Request object to get the same result:
public static string getIPAddress(HttpRequestBase request)
{
string szRemoteAddr = request.UserHostAddress;
string szXForwardedFor = request.ServerVariables["X_FORWARDED_FOR"];
string szIP = "";
if (szXForwardedFor == null)
{
szIP = szRemoteAddr;
}
else
{
szIP = szXForwardedFor;
if (szIP.IndexOf(",") > 0)
{
string [] arIPs = szIP.Split(',');
foreach (string item in arIPs)
{
if (!isPrivateIP(item))
{
return item;
}
}
}
}
return szIP;
}
To have font variation working correctly, I had to reverse the order of @font-face in CSS.
@font-face {
font-family: "DejaVuMono";
src: url("styles/DejaVuSansMono-BoldOblique.ttf");
font-weight: bold;
font-style: italic, oblique;
}
@font-face {
font-family: "DejaVuMono";
src: url("styles/DejaVuSansMono-Oblique.ttf");
font-style: italic, oblique;
}
@font-face {
font-family: "DejaVuMono";
src: url("styles/DejaVuSansMono-Bold.ttf");
font-weight: bold;
}
@font-face {
font-family: "DejaVuMono";
src: url("styles/DejaVuSansMono.ttf");
}
Here's yet another way (using a negative look-ahead):
^/(?!ignoreme|ignoreme2|ignoremeN)([a-z0-9]+)$
Note: There's only one capturing expression: ([a-z0-9]+)
.
I tried the code provided above, but it gave an error 9 for me. I made this code, and it worked fine for my purposes. I hope others find it useful as well.
Function mergeArrays(ByRef arr1() As Variant, arr2() As Variant) As Variant
Dim returnThis() As Variant
Dim len1 As Integer, len2 As Integer, lenRe As Integer, counter As Integer
len1 = UBound(arr1)
len2 = UBound(arr2)
lenRe = len1 + len2
ReDim returnThis(1 To lenRe)
counter = 1
Do While counter <= len1 'get first array in returnThis
returnThis(counter) = arr1(counter)
counter = counter + 1
Loop
Do While counter <= lenRe 'get the second array in returnThis
returnThis(counter) = arr2(counter - len1)
counter = counter + 1
Loop
mergeArrays = returnThis
End Function
Try
Date.ParseExact("9/1/2009", "M/d/yyyy", new CultureInfo("en-US"))
In your example propertyInfo.GetValue(this, null)
should work. Consider altering GetNamesAndTypesAndValues()
as follows:
public void GetNamesAndTypesAndValues()
{
foreach (PropertyInfo propertyInfo in allClassProperties)
{
Console.WriteLine("{0} [type = {1}] [value = {2}]",
propertyInfo.Name,
propertyInfo.PropertyType,
propertyInfo.GetValue(this, null));
}
}
I just timed some functions out of curiosity. In these tests I'm removing non-alphanumeric characters from the string string.printable
(part of the built-in string
module). The use of compiled '[\W_]+'
and pattern.sub('', str)
was found to be fastest.
$ python -m timeit -s \
"import string" \
"''.join(ch for ch in string.printable if ch.isalnum())"
10000 loops, best of 3: 57.6 usec per loop
$ python -m timeit -s \
"import string" \
"filter(str.isalnum, string.printable)"
10000 loops, best of 3: 37.9 usec per loop
$ python -m timeit -s \
"import re, string" \
"re.sub('[\W_]', '', string.printable)"
10000 loops, best of 3: 27.5 usec per loop
$ python -m timeit -s \
"import re, string" \
"re.sub('[\W_]+', '', string.printable)"
100000 loops, best of 3: 15 usec per loop
$ python -m timeit -s \
"import re, string; pattern = re.compile('[\W_]+')" \
"pattern.sub('', string.printable)"
100000 loops, best of 3: 11.2 usec per loop
Use both. In fact refer a guide like the OWASP XSS Prevention cheat sheet, on the possible cases for usage of output encoding and input validation.
Input validation helps when you cannot rely on output encoding in certain cases. For instance, you're better off validating inputs appearing in URLs rather than encoding the URLs themselves (Apache will not serve a URL that is url-encoded). Or for that matter, validate inputs that appear in JavaScript expressions.
Ultimately, a simple thumb rule will help - if you do not trust user input enough or if you suspect that certain sources can result in XSS attacks despite output encoding, validate it against a whitelist.
Do take a look at the OWASP ESAPI source code on how the output encoders and input validators are written in a security library.
Regarding building a DLL using MinGW, here are some very brief instructions.
First, you need to mark your functions for export, so they can be used by callers of the DLL. To do this, modify them so they look like (for example)
__declspec( dllexport ) int add2(int num){
return num + 2;
}
then, assuming your functions are in a file called funcs.c, you can compile them:
gcc -shared -o mylib.dll funcs.c
The -shared flag tells gcc to create a DLL.
To check if the DLL has actually exported the functions, get hold of the free Dependency Walker tool and use it to examine the DLL.
For a free IDE which will automate all the flags etc. needed to build DLLs, take a look at the excellent Code::Blocks, which works very well with MinGW.
Edit: For more details on this subject, see the article Creating a MinGW DLL for Use with Visual Basic on the MinGW Wiki.
The following 2-stage approach works for me (VS2010, ASP.NET MVC3, SQL Server 2008, Linq to SQL):
result = entRepos.FindAllEntities()
.Where(e => e.EntitySearchText.Contains(item));
if (caseSensitive)
{
result = result
.Where(e => e.EntitySearchText.IndexOf(item, System.StringComparison.CurrentCulture) >= 0);
}
Maybe the "K" format specifier would be of some use. This is the only one that seems to mention the use of capital "Z".
"Z" is kind of a unique case for DateTimes. The literal "Z" is actually part of the ISO 8601 datetime standard for UTC times. When "Z" (Zulu) is tacked on the end of a time, it indicates that that time is UTC, so really the literal Z is part of the time. This probably creates a few problems for the date format library in .NET, since it's actually a literal, rather than a format specifier.
In typer ...
is used to create required parameters: The Argument
class expects a default value, and if you pass the ...
it will complain if the user does not pass the particular argument.
You could use None
for the same if Ellipsis
was not there, but this would remove the opportunity to express that None
is the default value, in case that made any sense in your program.
int i = myObject.myField.CastTo<int>();
AFAIK, you don't need to map the UNC path to a drive letter in order to establish credentials for a server. I regularly used batch scripts like:
net use \\myserver /user:username password
:: do something with \\myserver\the\file\i\want.xml
net use /delete \\my.server.com
However, any program running on the same account as your program would still be able to access everything that username:password
has access to. A possible solution could be to isolate your program in its own local user account (the UNC access is local to the account that called NET USE
).
Note: Using SMB accross domains is not quite a good use of the technology, IMO. If security is that important, the fact that SMB lacks encryption is a bit of a damper all by itself.
Why not just add Labels to the top of the Listbox and if changes are needed, the only thing you need to programmatically change are the labels.
The concept of a HOME directory seems to be a bit vague when it comes to Windows. If the environment variables (HOMEDRIVE/HOMEPATH/USERPROFILE) aren't enough, you may have to resort to using native functions via JNI or JNA. SHGetFolderPath allows you to retrieve special folders, like My Documents (CSIDL_PERSONAL) or Local Settings\Application Data (CSIDL_LOCAL_APPDATA).
Sample JNA code:
public class PrintAppDataDir {
public static void main(String[] args) {
if (com.sun.jna.Platform.isWindows()) {
HWND hwndOwner = null;
int nFolder = Shell32.CSIDL_LOCAL_APPDATA;
HANDLE hToken = null;
int dwFlags = Shell32.SHGFP_TYPE_CURRENT;
char[] pszPath = new char[Shell32.MAX_PATH];
int hResult = Shell32.INSTANCE.SHGetFolderPath(hwndOwner, nFolder,
hToken, dwFlags, pszPath);
if (Shell32.S_OK == hResult) {
String path = new String(pszPath);
int len = path.indexOf('\0');
path = path.substring(0, len);
System.out.println(path);
} else {
System.err.println("Error: " + hResult);
}
}
}
private static Map<String, Object> OPTIONS = new HashMap<String, Object>();
static {
OPTIONS.put(Library.OPTION_TYPE_MAPPER, W32APITypeMapper.UNICODE);
OPTIONS.put(Library.OPTION_FUNCTION_MAPPER,
W32APIFunctionMapper.UNICODE);
}
static class HANDLE extends PointerType implements NativeMapped {
}
static class HWND extends HANDLE {
}
static interface Shell32 extends Library {
public static final int MAX_PATH = 260;
public static final int CSIDL_LOCAL_APPDATA = 0x001c;
public static final int SHGFP_TYPE_CURRENT = 0;
public static final int SHGFP_TYPE_DEFAULT = 1;
public static final int S_OK = 0;
static Shell32 INSTANCE = (Shell32) Native.loadLibrary("shell32",
Shell32.class, OPTIONS);
/**
* see http://msdn.microsoft.com/en-us/library/bb762181(VS.85).aspx
*
* HRESULT SHGetFolderPath( HWND hwndOwner, int nFolder, HANDLE hToken,
* DWORD dwFlags, LPTSTR pszPath);
*/
public int SHGetFolderPath(HWND hwndOwner, int nFolder, HANDLE hToken,
int dwFlags, char[] pszPath);
}
}
No need to use fancy unicode char exmaples to show the difference. Here's one simple example I found out today which is surprising, consisting of only ASCII characters.
According to the ASCII table, 0
(0x48) is smaller than _
(0x95) when compared ordinally. InvariantCulture would say the opposite (PowerShell code below):
PS> [System.StringComparer]::Ordinal.Compare("_", "0")
47
PS> [System.StringComparer]::InvariantCulture.Compare("_", "0")
-1
I think points one (somebody else using your lock) and two (all methods using the same lock needlessly) can happen in any fairly large application. Especially when there's no good communication between developers.
It's not cast in stone, it's mostly an issue of good practice and preventing errors.
SQL Server and the .NET Framework are based on different type systems. For example, the .NET Framework Decimal structure has a maximum scale of 28, whereas the SQL Server decimal and numeric data types have a maximum scale of 38. Click Here's a link! for detail
https://msdn.microsoft.com/en-us/library/cc716729(v=vs.110).aspx
If you use the BOOLEAN type, this is aliased to TINYINT(1). This is best if you want to use standardised SQL and don't mind that the field could contain an out of range value (basically anything that isn't 0 will be 'true').
ENUM('False', 'True') will let you use the strings in your SQL, and MySQL will store the field internally as an integer where 'False'=0 and 'True'=1 based on the order the Enum is specified.
In MySQL 5+ you can use a BIT(1) field to indicate a 1-bit numeric type. I don't believe this actually uses any less space in the storage but again allows you to constrain the possible values to 1 or 0.
All of the above will use approximately the same amount of storage, so it's best to pick the one you find easiest to work with.
The %~dp0 piece was mentioned already, but there is actually more to it:
the character(s) after the ~ define the information that is extracted.
No letter result in the return of the patch file name
d - returns the drive letter
p - returns the path
s - returns the short path
x - returns the file extension
So if you execute the script test.bat below from the c:\Temp\long dir name\ folder,
@echo off
echo %0
echo %~d0
echo %~p0
echo %~dp0
echo %~x0
echo %~s0
echo %~sp0
you get the following output
test c: \Temp\long dir name\ c:\Temp\long dir name\ .bat c:\Temp\LONGDI~1\test.bat \Temp\LONGDI~1\
And if a parameter is passed into your script as in
test c:\temp\mysrc\test.cpp
the same manipulations can be done with the %1 variable.
But the result of the expansion of %0 depends on the location!
At the "top level" of the batch it expands to the current batch filename.
In a function (call), it expands to the function name.
@echo off
echo %0
call :test
goto :eof
:test
echo %0
echo %~0
echo %~n0
The output is (the batchfile is started with myBatch.bat )
myBatch.bat
:test
:test
myBatch
Look @ this one.
grep --exclude="*\.svn*" -rn "foo=" * | grep -v Binary | grep -v tags
if Ubound(yourArray)>-1 then
debug.print "The array is not empty"
else
debug.print "EMPTY"
end if
With Objective C class methods, we can just avoid using the singleton pattern the usual way, from:
[[Librarian sharedInstance] openLibrary]
to:
[Librarian openLibrary]
by wrapping the class inside another class that just has Class Methods, that way there is no chance of accidentally creating duplicate instances, as we're not creating any instance!
I wrote a more detailed blog here :)
Sorry for the short answer but it is late. Google "oracle event 10046 sql trace". It would be best to trace an individual session because figuring which SQL belongs to which session from v$sql is no easy if it is shared sql and being used by multiple users.
If you want to impress your Oracle DBA friends, learn how to set an oracle trace with event 10046, interpret the meaning of the wait events and find the top cpu consumers.
Quest had a free product that allowed you to capture the SQL as it went out from the client side but not sure if it works with your product/version of Oracle. Google "quest oracle sql monitor" for this.
Good night.
For windows I went this way.
com.sun.management.OperatingSystemMXBean os = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
long physicalMemorySize = os.getTotalPhysicalMemorySize();
long freePhysicalMemory = os.getFreePhysicalMemorySize();
long freeSwapSize = os.getFreeSwapSpaceSize();
long commitedVirtualMemorySize = os.getCommittedVirtualMemorySize();
Here is the link with details.
Eric Petroelje almost has it right:
SELECT * FROM TableA
WHERE ROWID IN ( SELECT MAX(ROWID) FROM TableA GROUP BY Language )
Note: using ROWID (row unique id), not ROWNUM (which gives the row number within the result set)
I agree with erickson's answer, with one caveat: for password authentication purposes, bcrypt is far better than a single iteration of SHA-512 - simply because it is far slower. If you don't get why slowness is an advantage in this particular game, read the article you linked to again (scroll down to "Speed is exactly what you don’t want in a password hash function.").
You can of course build a secure password hashing algorithm around SHA-512 by iterating it thousands of times, just like the way PHK's MD5 algorithm works. Ulrich Drepper did exactly this, for glibc's crypt(). There's no particular reason to do this, though, if you already have a tested bcrypt implementation available.
You should include the two items (a and b) as hidden input elements as well as C.
Nowadays we have to use match_parent
:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/background">
</RelativeLayout>
objdump -TC /usr/lib/libexample.so
This would replicate exactly perl's chomp (minus behavior on arrays) for "\n" line terminator:
def chomp(x):
if x.endswith("\r\n"): return x[:-2]
if x.endswith("\n") or x.endswith("\r"): return x[:-1]
return x
(Note: it does not modify string 'in place'; it does not strip extra trailing whitespace; takes \r\n in account)
Select select = new Select(driver.findElement(By.id("searchDropdownBox")));
select.getOptions();//will get all options as List<WebElement>
#include <stdio.h>
#include <string.h>
int main(void) {
char buf[BUFSIZ] = { 0 };
char str[] = "Hello";
char fill = '#';
int width = 20; /* or whatever you need but less than BUFSIZ ;) */
printf("%s%s\n", (char*)memset(buf, fill, width - strlen(str)), str);
return 0;
}
Output:
$ gcc -Wall -ansi -pedantic padding.c
$ ./a.out
###############Hello
double scale = 1.0 / ((double) RAND_MAX + 1.0);
int min, max;
...
rval = (int)(rand() * scale * (max - min + 1) + min);
word.matches("^[0-9,;]+$");
you were almost there
Its similar to select, But datalist has additional functionalities like auto suggest. You can even type and see suggestions as and when you type.
User will also be able to write items which is not there in list.
Because if a factor is greater than the square root of n, the other factor that would multiply with it to equal n is necessarily less than the square root of n.
You can use the CLI too, like:
ng build -prod --output-path=production
# or
ng serve --output-path=devroot
Use the onsubmit
event to execute JavaScript code when the form is submitted. You can then return false or call the passed event's preventDefault
method to disable the form submission.
For example:
<script>
function doSomething() {
alert('Form submitted!');
return false;
}
</script>
<form onsubmit="return doSomething();" class="my-form">
<input type="submit" value="Submit">
</form>
This works, but it's best not to litter your HTML with JavaScript, just as you shouldn't write lots of inline CSS rules. Many Javascript frameworks facilitate this separation of concerns. In jQuery you bind an event using JavaScript code like so:
<script>
$('.my-form').on('submit', function () {
alert('Form submitted!');
return false;
});
</script>
<form class="my-form">
<input type="submit" value="Submit">
</form>
I installed IntelliJ IDEA community version from http://www.jetbrains.com/idea/download/
I tried opening my project that I started in Android studio but it failed when at gradle build. I instead opened both android studio and intellij at same time and placed one screen next to the other and simply drag and dropped my java files, xml layouts, drawables, and manifest into the project hiearchy of a new project started in IntelliJ. It worked around the gradle build issues and now I can start a new project in IntelliJ and design either an android app or a basic Java app. Thankfully this worked because I hated having so many IDEs on my pc.
Option 1: Put this in your procedure to print 'comment' to stdout when it runs.
SELECT 'Comment';
Option 2: Put this in your procedure to print a variable with it to stdout:
declare myvar INT default 0;
SET myvar = 5;
SELECT concat('myvar is ', myvar);
This prints myvar is 5
to stdout when the procedure runs.
Option 3, Create a table with one text column called tmptable
, and push messages to it:
declare myvar INT default 0;
SET myvar = 5;
insert into tmptable select concat('myvar is ', myvar);
You could put the above in a stored procedure, so all you would have to write is this:
CALL log(concat('the value is', myvar));
Which saves a few keystrokes.
Option 4, Log messages to file
select "penguin" as log into outfile '/tmp/result.txt';
There is very heavy restrictions on this command. You can only write the outfile to areas on disk that give the 'others' group create and write permissions. It should work saving it out to /tmp directory.
Also once you write the outfile, you can't overwrite it. This is to prevent crackers from rooting your box just because they have SQL injected your website and can run arbitrary commands in MySQL.
Given that most recommended error mode for PDO is ERRMODE_EXCEPTION
, no direct execute()
result verification will ever work. As the code execution won't even reach the condition offered in other answers.
So, there are three possible scenarios to handle the query execution result in PDO:
try..catch
operator.For a regular PHP user it sounds a bit alien - how's that, not to verify the direct result of the operation? - but this is exactly how exceptions work - you check the error somewhere else. Once for all. Extremely convenient.
So, in a nutshell: in a regular code you don't need any error handling at all. Just keep your code as is:
$stmt->bindParam(':field1', $field1, PDO::PARAM_STR);
$stmt->bindParam(':field2', $field2, PDO::PARAM_STR);
$stmt->execute();
echo "Success!"; // whatever
On success it will tell you so, on error it will show you the regular error page that your application is showing for such an occasion.
Only in case you have a handling scenario other than just reporting the error, put your insert statement in a try..catch
operator, check whether it was the error you expected and handle it; or - if the error was any different - re-throw the exception, to make it possible to be handled by the site-wide error handler usual way. Below is the example code from my article on error handling with PDO:
try {
$pdo->prepare("INSERT INTO users VALUES (NULL,?,?,?,?)")->execute($data);
} catch (PDOException $e) {
if ($e->getCode() == 1062) {
// Take some action if there is a key constraint violation, i.e. duplicate name
} else {
throw $e;
}
}
echo "Success!";
In the code above we are checking for the particular error to take some action and re-throwing the exception for the any other error (no such table for example) which will be reported to a programmer.
While again - just to tell a user something like "Your insert was successful" no condition is ever needed.
Yes, in AndroidManifest.xml
, declare your Activity
like so: <activity ... android:screenOrientation="landscape" .../>
Try this
myApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
Just setting useXDomain = true is not enough. AJAX request are also send with the X-Requested-With header, which indicate them as being AJAX. Removing the header is necessary, so the server is not rejecting the incoming request.
One more solution that I've discovered by accident, and may help someone:
In my case, it was a project that got corrupted, and not the entire workspace (attempting to import said project into a fresh workspace caused it to fail as well). So, I've started to search for the faulty project - instead, I got the result described above.
If you want exactly one byte, uint8_t defined in cstdint would be the most expressive.
If you want to input a description you can use this. This works on IE 9 and all other browsers.
<input type="text" onclick="if(this.value=='CVC2: '){this.value='';}" onblur="if(this.value==''){this.value='CVC2: ';}" value="CVC2: "/>
Entire request and response is encrypted, including URL.
Note that when you use a HTTP Proxy, it knows the address (domain) of the target server, but doesn't know the requested path on this server (i.e. request and response are always encrypted).
If you don't want to pass interface state or props model you can try this
class App extends React.Component <any, any>
To disable the warning while connecting to a database in Java, use the below concept -
autoReconnect=true&useSSL=false
Just need to change connectionURL like :
String connectionURL = jdbc:mysql://localhost:3306/Peoples?autoReconnect=true&useSSL=false
This will disable SSL and also suppress the SSL errors.
In the relevant page which makes a mixed content https to http call which is not accessible we can add the following entry in the relevant and get rid of the mixed content error.
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
Take a look at the FormBorderStyle property
form1.FormBorderStyle = FormBorderStyle.FixedSingle;
You may also want to remove the minimize and maximize buttons:
form1.MaximizeBox = false;
form1.MinimizeBox = false;
The latest version of Genymotion (2.10.0 onwards) now allows you to install GApps from the emulator toolbar:
Click the GApps button the toolbar
Accept the Terms and Conditions
Your download of google apps will then begin
Once the download is complete simply restart the virtual device!
<?php
if (isset($_POST['birthdate'])) {
$timestamp = strtotime($_POST['birthdate']);
$date=date('d',$timestamp);
$month=date('m',$timestamp);
$year=date('Y',$timestamp);
}
?>
req.query
will return a JS object after the query string is parsed.
/user?name=tom&age=55 - req.query
would yield {name:"tom", age: "55"}
req.params
will return parameters in the matched route.
If your route is /user/:id and you make a request to /user/5 - req.params
would yield {id: "5"}
req.param
is a function that peels parameters out of the request. All of this can be found here.
UPDATE
If the verb is a POST
and you are using bodyParser
, then you should be able to get the form body in you function with req.body
. That will be the parsed JS version of the POST
ed form.
This query will list missing indexes on foreign keys, original source.
Edit: Note that it will not check small tables (less then 9 MB) and some other cases. See final WHERE
statement.
-- check for FKs where there is no matching index
-- on the referencing side
-- or a bad index
WITH fk_actions ( code, action ) AS (
VALUES ( 'a', 'error' ),
( 'r', 'restrict' ),
( 'c', 'cascade' ),
( 'n', 'set null' ),
( 'd', 'set default' )
),
fk_list AS (
SELECT pg_constraint.oid as fkoid, conrelid, confrelid as parentid,
conname, relname, nspname,
fk_actions_update.action as update_action,
fk_actions_delete.action as delete_action,
conkey as key_cols
FROM pg_constraint
JOIN pg_class ON conrelid = pg_class.oid
JOIN pg_namespace ON pg_class.relnamespace = pg_namespace.oid
JOIN fk_actions AS fk_actions_update ON confupdtype = fk_actions_update.code
JOIN fk_actions AS fk_actions_delete ON confdeltype = fk_actions_delete.code
WHERE contype = 'f'
),
fk_attributes AS (
SELECT fkoid, conrelid, attname, attnum
FROM fk_list
JOIN pg_attribute
ON conrelid = attrelid
AND attnum = ANY( key_cols )
ORDER BY fkoid, attnum
),
fk_cols_list AS (
SELECT fkoid, array_agg(attname) as cols_list
FROM fk_attributes
GROUP BY fkoid
),
index_list AS (
SELECT indexrelid as indexid,
pg_class.relname as indexname,
indrelid,
indkey,
indpred is not null as has_predicate,
pg_get_indexdef(indexrelid) as indexdef
FROM pg_index
JOIN pg_class ON indexrelid = pg_class.oid
WHERE indisvalid
),
fk_index_match AS (
SELECT fk_list.*,
indexid,
indexname,
indkey::int[] as indexatts,
has_predicate,
indexdef,
array_length(key_cols, 1) as fk_colcount,
array_length(indkey,1) as index_colcount,
round(pg_relation_size(conrelid)/(1024^2)::numeric) as table_mb,
cols_list
FROM fk_list
JOIN fk_cols_list USING (fkoid)
LEFT OUTER JOIN index_list
ON conrelid = indrelid
AND (indkey::int2[])[0:(array_length(key_cols,1) -1)] @> key_cols
),
fk_perfect_match AS (
SELECT fkoid
FROM fk_index_match
WHERE (index_colcount - 1) <= fk_colcount
AND NOT has_predicate
AND indexdef LIKE '%USING btree%'
),
fk_index_check AS (
SELECT 'no index' as issue, *, 1 as issue_sort
FROM fk_index_match
WHERE indexid IS NULL
UNION ALL
SELECT 'questionable index' as issue, *, 2
FROM fk_index_match
WHERE indexid IS NOT NULL
AND fkoid NOT IN (
SELECT fkoid
FROM fk_perfect_match)
),
parent_table_stats AS (
SELECT fkoid, tabstats.relname as parent_name,
(n_tup_ins + n_tup_upd + n_tup_del + n_tup_hot_upd) as parent_writes,
round(pg_relation_size(parentid)/(1024^2)::numeric) as parent_mb
FROM pg_stat_user_tables AS tabstats
JOIN fk_list
ON relid = parentid
),
fk_table_stats AS (
SELECT fkoid,
(n_tup_ins + n_tup_upd + n_tup_del + n_tup_hot_upd) as writes,
seq_scan as table_scans
FROM pg_stat_user_tables AS tabstats
JOIN fk_list
ON relid = conrelid
)
SELECT nspname as schema_name,
relname as table_name,
conname as fk_name,
issue,
table_mb,
writes,
table_scans,
parent_name,
parent_mb,
parent_writes,
cols_list,
indexdef
FROM fk_index_check
JOIN parent_table_stats USING (fkoid)
JOIN fk_table_stats USING (fkoid)
WHERE table_mb > 9
AND ( writes > 1000
OR parent_writes > 1000
OR parent_mb > 10 )
ORDER BY issue_sort, table_mb DESC, table_name, fk_name;
PHP Folks:
print_r(preg_match('/^(?:[0-9A-F]{2}[:]?){5}(?:[0-9A-F]{2}?)$/i', '00:25:90:8C:B8:59'));
Need Explanation: http://regex101.com/r/wB0eT7
getJSON will evaluate the data to JSON for you, as long as the correct content-type is used. Make sure that the server is returning the data as application/json.
String anotherPalindrome = "Niagara. O roar again!";
String roar = anotherPalindrome.substring(11, 15);
You can also do like these
The full error message sounds:
ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key
So add primary key
to the auto_increment
field:
CREATE TABLE book (
id INT AUTO_INCREMENT primary key NOT NULL,
accepted_terms BIT(1) NOT NULL,
accepted_privacy BIT(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
upper answer only near solving the Problem. heres your answer:
Integer.decode(Character.toString(char c));
Many functions are vectorization already, and so there is no need for any iterations (neither for
loops or *pply
functions). Your testFunc
is one such example. You can simply call:
testFunc(df[, "x"], df[, "z"])
In general, I would recommend trying such vectorization approaches first and see if they get you your intended results.
Alternatively, if you need to pass multiple arguments to a function which is not vectorized, mapply
might be what you are looking for:
mapply(power.t.test, df[, "x"], df[, "z"])
Depending on your exact needs, you may consider using BitTorrent Sync. Create a shared folder on your home PC and your work PC. Edit the files on your home PC (using Sublime or whatever you like), and they will sync automatically when you save. BitTorrent Sync does not rely on a central server storing the files (a la Dropbox and the like), so you should in theory be clear of any issues due to a third party storing sensitive info.
long int n;
scanf("%ld", &n);
printf("%ld", n);
long long int n;
scanf("%lld", &n);
printf("%lld", n);
Hope you've cleared..
If you are uploading a zip file. Make sure that you are zipping the contents of the directory and not the directory itself.
You can use plain javascript, this will call your_func once, after 5 seconds:
setTimeout(function() { your_func(); }, 5000);
If your function has no parameters and no explicit receiver you can call directly setTimeout(func, 5000)
There is also a plugin I've used once. It has oneTime
and everyTime
methods.
try this
<div ng-app="myApp" ng-controller="customersCtrl">
<div ng-include="'myTable.htm'"></div>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("customers.php").then(function (response) {
$scope.names = response.data.records;
});
});
</script>
Here is a trick for getting automatic keyboard dismissal behavior with no code at all. In the nib, edit the First Responder proxy object in the Identity inspector, adding a new first responder action; let's call it dummy:
. Now hook the Did End on Exit event of the text field to the dummy:
action of the First Responder proxy object. That's it! Since the text field's Did End on Exit event now has an action–target pair, the text field automatically dismisses its keyboard when the user taps Return; and since there is no penalty for not finding a handler for a message sent up the responder chain, the app doesn't crash even though there is no implementation of dummy:
anywhere.
There are probably as many naming conventions as there are individuals, the debate being as endless (and sterile) as to which brace style to use and so forth.
So I'll have 2 advices:
The rest is up to you.
In SSRS 2016 There is an option under the properties header "Localization" called "Calendar
", if you click on this it gives you these 2 options:
This works brilliantly when referencing data from a tables aswell
alternatively if this does not work for you, specify one of these formats under "Number" and in the cell "Format
":
dd/MM/yyyy
or MM/dd/yyyy
One important use of explicit interface implementation is when in need to implement interfaces with mixed visibility.
The problem and solution are well explained in the article C# Internal Interface.
For example, if you want to protect leakage of objects between application layers, this technique allows you to specify different visibility of members that could cause the leakage.
Be sure to have both objects created in controller: @post
and @comment
for the post, eg:
@post = Post.find params[:post_id]
@comment = Comment.new(:post=>@post)
Then in view:
<%= form_for([@post, @comment]) do |f| %>
Be sure to explicitly define the array in the form_for, not just comma separated like you have above.
The first part is to get the element from the drop down menu which may look like this:
<select id="cycles_list"> <option value="10">10</option> <option value="100">100</option> <option value="1000">1000</option> <option value="10000">10000</option> </select>
To capture via jQuery you can do something like so:
$('#cycles_list').change(function() { var mylist = document.getElementById("cycles_list"); iterations = mylist.options[mylist.selectedIndex].text; });
Once you have stored the value in your variable, the next step would be to send the information stored in the variable to the form field or HTML element of your choosing. It may be a div p or custom element.
i.e.
<p></p> OR <div></div>
You would use:
$('p').html(iterations); OR $('div').html(iterations);
If you wish to populate a text field such as:
<input type="text" name="textform" id="textform"></input>
You would use:
$('#textform').text = iterations;
Of course you can do all of the above in less steps, I just believe it helps people to learn when you break it all down into easy to understand steps... Hope this helps!
It's not easy to find a full solution of the problem of a convertion of an arbitrary HTML to PDF with non-english letters in Android. I test it for russian unicode letters.
We use three libraries:
(1) Jsoup (jsoup-1.7.3.jar) for a convertion from HTML to XHTML,
(2) iTextPDF (itextpdf-5.5.0.jar),
(3) XMLWorker (xmlworker-5.5.1.jar).
public boolean createPDF(String rawHTML, String fileName, ContextWrapper context){
final String APPLICATION_PACKAGE_NAME = context.getBaseContext().getPackageName();
File path = new File( Environment.getExternalStorageDirectory(), APPLICATION_PACKAGE_NAME );
if ( !path.exists() ){ path.mkdir(); }
File file = new File(path, fileName);
try{
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
document.open();
// ?????????????? HTML
String htmlText = Jsoup.clean( rawHTML, Whitelist.relaxed() );
InputStream inputStream = new ByteArrayInputStream( htmlText.getBytes() );
// ???????? ???????? PDF
XMLWorkerHelper.getInstance().parseXHtml(writer, document,
inputStream, null, Charset.defaultCharset(), new MyFont());
document.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (DocumentException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
The difficult problem is to display russian letters in PDF by using iTextPDF XMLWorker library. For this we should create our own implementation of FontProvider interface:
public class MyFont implements FontProvider{
private static final String FONT_PATH = "/system/fonts/DroidSans.ttf";
private static final String FONT_ALIAS = "my_font";
public MyFont(){ FontFactory.register(FONT_PATH, FONT_ALIAS); }
@Override
public Font getFont(String fontname, String encoding, boolean embedded,
float size, int style, BaseColor color){
return FontFactory.getFont(FONT_ALIAS, BaseFont.IDENTITY_H,
BaseFont.EMBEDDED, size, style, color);
}
@Override
public boolean isRegistered(String name) { return name.equals( FONT_ALIAS ); }
}
Here we use the standard Android font Droid Sans, which is located in the system folder:
private static final String FONT_PATH = "/system/fonts/DroidSans.ttf";
Just to extend the answer above you can also index your columns rather than specifying the column names which can also be useful depending on what you're doing. Given that your location is the first field it would look like this:
bar <- foo[foo[ ,1] == "there", ]
This is useful because you can perform operations on your column value, like looping over specific columns (and you can do the same by indexing row numbers too).
This is also useful if you need to perform some operation on more than one column because you can then specify a range of columns:
foo[foo[ ,c(1:N)], ]
Or specific columns, as you would expect.
foo[foo[ ,c(1,5,9)], ]
How about
if value in my_array[:, col_num]:
do_whatever
Edit: I think __contains__
is implemented in such a way that this is the same as @detly's version
' Trying to find the amount of "." in the text
' if txtName looks like "hi...hi" then intdots will = 3
Dim test As String = txtName.Text
Dim intdots As Integer = 0
For i = 1 To test.Length
Dim inta As Integer = 0 + 1
Dim stra As String = test.Substring(inta)
If stra = "." Then
intdots = intdots + 1
End If
Next
txttest.text = intdots
var str = "123, 124, 234,252";
var arr = str.split(",");
for(var i=0;i<arr.length;i++) {
arr[i] = ++arr[i];
}
To achieve this in PyCharm set 'Environment Variables' section to:
PYTHONUNBUFFERED=1;
FLASK_DEBUG=1
For Flask 'run / debug configurations'.
You can use System.in
to read from the standard input. It works just like entering it from a keyboard. The OS handles going from file to standard input.
class MyProg {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Printing the file passed in:");
while(sc.hasNextLine()) System.out.println(sc.nextLine());
}
}
I think what you want is mapply. You could apply the function to all columns, and then just drop the columns you don't want. However, if you are applying different functions to different columns, it seems likely what you want is mutate, from the dplyr package.
I wanted to check if a port is open on one of our linux test servers. I was able to do that by trying to connect with telnet from my dev machine to the test server. On you dev machine try to run:
$ telnet test2.host.com 8080
Trying 05.066.137.184...
Connected to test2.host.com
In this example I want to check if port 8080 is open on host test2.host.com
You are trying to access the struct statically with a .
instead of ::
, nor are its members static
. Either instantiate ReducedForm
:
ReducedForm rf;
rf.iSimplifiedNumerator = 5;
or change the members to static
like this:
struct ReducedForm
{
static int iSimplifiedNumerator;
static int iSimplifiedDenominator;
};
In the latter case, you must access the members with ::
instead of .
I highly doubt however that the latter is what you are going for ;)
What worked for me was to rename the project by removing the special characters.
Example: "project_marketplace" to "projectmarketplace"
In this case, I redid the project with react-native init and copied the src and package.json folder.
sed -i s/$/:80/ file.txt
sed
stream editor
-i
in-place (edit file in place)s
substitution command/replacement_from_reg_exp/replacement_to_text/
statement$
matches the end of line (replacement_from_reg_exp):80
text you want to add at the end of every line (replacement_to_text)file.txt
the file nameAlthough you can "replace" a button with an image using the following CSS...
.className {
background: url(http://sstatic.net/so/img/logo.png) no-repeat 0 0;
border: 0;
height: 61px;
width: 250px
}
...the best thing to do here is use an ImageButton control because it will allow you to use alternate text (for accessibility).
I want to clarify some things here for the original poster which others have alluded to but haven't really explicitly stated. When you say that you want a Unique List, that is the very definition of an Ordered Set. Some other key differences between the Set Interface and the List interface are that List allows you to specify the insert index. So, the question is do you really need the List Interface (i.e. for compatibility with a 3rd party library, etc.), or can you redesign your software to use the Set interface? You also have to consider what you are doing with the interface. Is it important to find elements by their index? How many elements do you expect in your set? If you are going to have many elements, is ordering important?
If you really need a List which just has a unique constraint, there is the Apache Common Utils class org.apache.commons.collections.list.SetUniqueList which will provide you with the List interface and the unique constraint. Mind you, this breaks the List interface though. You will, however, get better performance from this if you need to seek into the list by index. If you can deal with the Set interface, and you have a smaller data set, then LinkedHashSet might be a good way to go. It just depends on the design and intent of your software.
Again, there are certain advantages and disadvantages to each collection. Some fast inserts but slow reads, some have fast reads but slow inserts, etc. It makes sense to spend a fair amount of time with the collections documentation to fully learn about the finer details of each class and interface.
This works for me in chrome
$('#input').focus(function() {
setTimeout( function() {
document.getElementById('input').selectionStart = 4;
document.getElementById('input').selectionEnd = 4;
}, 1);
});
Apparently you need a delay of a microsecond or more, because usually a user focusses on the text field by clicking at some position in the text field (or by hitting tab) which you want to override, so you have to wait till the position is set by the user click and then change it.
Some people like to use the Paint
, CellPainting
or CellFormatting
events, but note that changing a style in these events causes recursive calls. If you use DataBindingComplete
it will execute only once. The argument for CellFormatting
is that it is called only on visible cells, so you don't have to format non-visible cells, but you format them multiple times.
Since you mentioned you use a proxy, try setting up the firefox driver with a proxy by following the answer given here proxy selenium python firefox
I recently came across Python 3 interpreter at CompileOnline.
Building on what is mentioned in the comments, the simplest solution would be:
@RequestMapping(method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Collection<BudgetDTO> updateConsumerBudget(@RequestBody SomeDto someDto) throws GeneralException, ParseException {
//whatever
}
class SomeDto {
private List<WhateverBudgerPerDateDTO> budgetPerDate;
//getters setters
}
The solution assumes that the HTTP request you are creating actually has
Content-Type:application/json
instead of text/plain
As per this answer:
TimeZone tz = TimeZone.getTimeZone("EST");
boolean inDs = tz.inDaylightTime(new Date());
If you google for javascript callback function example
you will get Getting a better understanding of callback functions in JavaScript
This is how to do a callback function:
function f() {
alert('f was called!');
}
function callFunction(func) {
func();
}
callFunction(f);
You can download in the various way you can follow my way. Though files may not download due to 'allow-popups' permission is not set but in your environment, this will work perfectly
<div className="col-6">_x000D_
<a download href="https://www.w3schools.com/images/myw3schoolsimage.jpg" >Test Download </a>_x000D_
</div>
_x000D_
another one this one will also fail due to 'X-Frame-Options' to 'sameorigin'.
<a href="https://www.w3schools.com/images/myw3schoolsimage.jpg" download>_x000D_
<img src="https://www.w3schools.com/images/myw3schoolsimage.jpg" alt="W3Schools" width="104" height="142">_x000D_
</a>
_x000D_
Günter's answer is great (question is asking for dynamic class attribute) but I thought I would add just for completeness...
If you're looking for a quick and clean way to add one or more static classes to the host element of your component (i.e., for theme-styling purposes) you can just do:
@Component({
selector: 'my-component',
template: 'app-element',
host: {'class': 'someClass1'}
})
export class App implements OnInit {
...
}
And if you use a class on the entry tag, Angular will merge the classes, i.e.,
<my-component class="someClass2">
I have both someClass1 & someClass2 applied to me
</my-component>
I resolved this problem by doing 2 things:
For Each is much faster than for I=1 to X, for some reason. Just try to go through the same dictionary,
once with for each Dkey in dDict,
and once with for Dkey = lbound(dDict.keys) to ubound(dDict.keys)
=>You will notice a huge difference, even though you are going through the same construct.
You can also use the 'sed' function that's part of ShellJS ...
$ npm install [-g] shelljs
require('shelljs/global');
sed('-i', 'search_pattern', 'replace_pattern', file);
Visit ShellJs.org for more examples.
The problem is where you are executing:
rankings[kvp.Key] = rankings[kvp.Key] + 4;
You cannot modify the collection you are iterating through in a foreach loop. A foreach loop requires the loop to be immutable during iteration.
Instead, use a standard 'for' loop or create a new loop that is a copy and iterate through that while updating your original.
@jasonk - if you want to have "or" then negate all conditions since (A and B) <=> ~(~A or ~B)
but if you have values other than boolean try using type converters:
<MultiDataTrigger.Conditions>
<Condition Value="True">
<Condition.Binding>
<MultiBinding Converter="{StaticResource conditionConverter}">
<Binding Path="Name" />
<Binding Path="State" />
</MultiBinding>
</Condition.Binding>
<Setter Property="Background" Value="Cyan" />
</Condition>
</MultiDataTrigger.Conditions>
you can use the values in Convert method any way you like to produce a condition which suits you.
public class ListOfLists<T> : List<List<T>>
{
}
var myList = new ListOfLists<string>();
var i2 = JsonConvert.DeserializeObject(obj["id"].ToString(), type);
throws a parsing exception due to missing quotes around the first argument (I think). I got it to work by adding the quotes:
var i2 = JsonConvert.DeserializeObject("\"" + obj["id"].ToString() + "\"", type);
I know this will not work for everyone, but I thought it interesting that just adding a Divider solves for this.
struct DividerTest: View {
var body: some View {
VStack(alignment: .leading) {
Text("Foo")
Text("Bar")
Divider()
}.background(Color.red)
}
}
to anyone looking for solution to the flickering/blinking issue when you already have DividerItemDecoration
. i seem to have solved it like this:
override fun onDrawOver(...)
{
//code from before
//do NOT return on null
val childInContact = getChildInContact(recyclerView, currentHeader.bottom)
//add null check
if (childInContact != null && mHeaderListener.isHeader(recyclerView.getChildAdapterPosition(childInContact)))
{
moveHeader(...)
return
}
drawHeader(...)
}
this seems to be working but can anyone confirm i did not break anything else?
all you are right! other way to getting !
https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/locales/bootstrap-datepicker.ru.min.js
You can find out all languages on there https://cdnjs.com/libraries/bootstrap-datepicker
https://labs.maarch.org/maarch/maarchRM/commit/3299d1e7ed25018b48715e16a42d52c288b4da3e
You can also try using flex-box
<head><style>
body {
color:white;
font-family:arial;
font-size:1.2em;
}
form {
margin:0 auto;
padding:20px;
background:#444;
}
.input-group {
margin-top:10px;
width:60%;
display:flex;
justify-content:space-between;
flex-wrap:wrap;
}
label, input {
flex-basis:100px;
}
</style></head>
<body>
<form>
<div class="wrapper">
<div class="input-group">
<label for="user_name">name:</label>
<input type="text" id="user_name">
</div>
<div class="input-group">
<label for="user_pass">Password:</label>
<input type="password" id="user_pass">
</div>
</div>
</form>
</body>
</html>
See ngOptions
ngOptions(optional) – {
comprehension_expression=
} – in one of the following forms:For array data sources:
label for value in array
select as label for value in array
label group by group for value in array
select as label group by group for value in array track by trackexpr
For object data sources:label for (key , value) in object
select as label for (key , value) in object
label group by group for (key, value) in object
select as label group by group for (key, value) in object
In your case, it should be
array = [{ "value": 1, "text": "1st" }, { "value": 2, "text": "2nd" }];
<select ng-options="obj.value as obj.text for obj in array"></select>
With the updates on AngularJS, it is now possible to set the actual value for the value
attribute of select
element with track by
expression.
<select ng-options="obj.text for obj in array track by obj.value">
</select>
To all the people who are having hard time to remember this syntax form: I agree this isn't the most easiest or beautiful syntax. This syntax is kind of an extended version of Python's list comprehensions and knowing that helps me to remember the syntax very easily. It's something like this:
Python code:
my_list = [x**2 for x in [1, 2, 3, 4, 5]]
> [1, 4, 9, 16, 25]
# Let people to be a list of person instances
my_list2 = [person.name for person in people]
> my_list2 = ['Alice', 'Bob']
This is actually the same syntax as the first one listed above. However, in <select>
we usually need to differentiate between the actual value in code and the text shown (the label) in a <select>
element.
Like, we need person.id
in the code, but we don't want to show the id
to the user; we want to show its name. Likewise, we're not interested in the person.name
in the code. There comes the as
keyword to label stuff. So it becomes like this:
person.id as person.name for person in people
Or, instead of person.id
we could need the person
instance/reference itself. See below:
person as person.name for person in people
For JavaScript objects, the same method applies as well. Just remember that the items in the object is deconstructed with (key, value)
pairs.
You can inject values into a Map from the properties file using the @Value
annotation like this.
The property in the properties file.
propertyname={key1:'value1',key2:'value2',....}
In your code.
@Value("#{${propertyname}}") private Map<String,String> propertyname;
Note the hashtag as part of the annotation.
It means that the number of values specified in your VALUES
clause on the INSERT
statement is not equal to the total number of columns in the table. You must specify the columnname if you only try to insert on selected columns.
Another one, since you are using ADO.Net
, always parameterized your query to avoid SQL Injection
. What you are doing right now is you are defeating the use of sqlCommand
.
ex
Dim query as String = String.Empty
query &= "INSERT INTO student (colName, colID, colPhone, "
query &= " colBranch, colCourse, coldblFee) "
query &= "VALUES (@colName,@colID, @colPhone, @colBranch,@colCourse, @coldblFee)"
Using conn as New SqlConnection("connectionStringHere")
Using comm As New SqlCommand()
With comm
.Connection = conn
.CommandType = CommandType.Text
.CommandText = query
.Parameters.AddWithValue("@colName", strName)
.Parameters.AddWithValue("@colID", strId)
.Parameters.AddWithValue("@colPhone", strPhone)
.Parameters.AddWithValue("@colBranch", strBranch)
.Parameters.AddWithValue("@colCourse", strCourse)
.Parameters.AddWithValue("@coldblFee", dblFee)
End With
Try
conn.open()
comm.ExecuteNonQuery()
Catch(ex as SqlException)
MessageBox.Show(ex.Message.ToString(), "Error Message")
End Try
End Using
End USing
PS: Please change the column names specified in the query to the original column found in your table.
Using the system
scope. ${basedir}
is the directory of your pom.
<dependency>
<artifactId>..</artifactId>
<groupId>..</groupId>
<scope>system</scope>
<systemPath>${basedir}/lib/dependency.jar</systemPath>
</dependency>
However it is advisable that you install your jar in the repository, and not commit it to the SCM - after all that's what maven tries to eliminate.
You can use:
adb shell monkey -p com.package.name -c android.intent.category.LAUNCHER 1
This will start the LAUNCHER Activity of the application using monkeyrunner test tool.
Here is my solution. @Maxim Shoustin's solution has some issue with sorting. I also wrap the whole thing to a directive. The only dependency is UI.Bootstrap.pagination, which did a great job on pagination.
Here is the plunker
Here is the github source code.
There are two commands, which you can use to check the version of redis
redis-server -v
or
redis-server --version
As an alternative solution you can use a LIFO structure (like a stack) to store all the strings and when you are done just take them all out and put them into the StringBuilder. It naturally reverses the order of the items (strings) placed in it.
Stack<String> textStack = new Stack<String>();
// push the strings to the stack
while(!isReadingTextDone()) {
String text = readText();
textStack.push(text);
}
// pop the strings and add to the text builder
String builder = new StringBuilder();
while (!textStack.empty()) {
builder.append(textStack.pop());
}
// get the final string
String finalText = builder.toString();
For SQL 2008 and newer, a more concise method, coding-wise, to detect index existence is by using the INDEXPROPERTY
built-in function:
INDEXPROPERTY ( object_ID , index_or_statistics_name , property )
The simplest usage is with the IndexID
property:
If IndexProperty(Object_Id('MyTable'), 'MyIndex', 'IndexID') Is Null
If the index exists, the above will return its ID; if it doesn't, it will return NULL
.
Try this to get the month in number form:
Month(DateAdd("m", -3, Now))
It will give you 12
for December.
So in your case you would use Month(DateAdd("m", -1, Now))
to just subract one month.
The new
keyword allocates memory on the Java heap. The heap is the main pool of memory, accessible to the whole of the application. If there is not enough memory available to allocate for that object, the JVM attempts to reclaim some memory from the heap with a garbage collection. If it still cannot obtain enough memory, an OutOfMemoryError
is thrown, and the JVM exits.
The heap is split into several different sections, called generations. As objects survive more garbage collections, they are promoted into different generations. The older generations are not garbage collected as often. Because these objects have already proven to be longer lived, they are less likely to be garbage collected.
When objects are first constructed, they are allocated in the Eden Space. If they survive a garbage collection, they are promoted to Survivor Space, and should they live long enough there, they are allocated to the Tenured Generation. This generation is garbage collected much less frequently.
There is also a fourth generation, called the Permanent Generation, or PermGen. The objects that reside here are not eligible to be garbage collected, and usually contain an immutable state necessary for the JVM to run, such as class definitions and the String constant pool. Note that the PermGen space is planned to be removed from Java 8, and will be replaced with a new space called Metaspace, which will be held in native memory. reference:http://www.programcreek.com/2013/04/jvm-run-time-data-areas/
I know that this is old, but I've found that (while using Pillow) opening the file by using open(fp, 'w')
and then saving the file will work. E.g:
with open(fp, 'w') as f:
result.save(f)
fp
being the file path, of course.
Unless there is a single row in the ASSIGNMENT
table and ASSIGNMENT_20081120
is a local PL/SQL variable of type ASSIGNMENT%ROWTYPE
, this is not what you want.
Assuming you are trying to create a new table and copy the existing data to that new table
CREATE TABLE assignment_20081120
AS
SELECT *
FROM assignment
All the solutions above mentioned will work only when you have a local webserver running on your local host. If you want to achieve this with out a web server, you might need to put in some manual effort by uploading the JSON file using file upload control. The browser will not offer this functionality with out a local server because of security risks.
You can parse the uploaded file with out a local webserver as well. Here is the sample code I have achieved a solution similar problem.
<div id="content">
<input type="file" name="inputfile" id="inputfile">
<br>
<h2>
<pre id="output"></pre>
</h2>
</div>
<script type="text/javascript">
document.getElementById('inputfile')
.addEventListener('change', function () {
let fileReader = new FileReader();
fileReader.onload = function () {
let parsedJSON = JSON.parse(fileReader.result);
console.log(parsedJSON);
// your code to consume the json
}
fileReader.readAsText(this.files[0]);
})
</script>
In my case I want to read a local JSON file and show it in a html file on my desktop, that's all I have to do.
Note: Don't try to automate the file uploading using JavaScript, even that's also not allowed due the same security restrictions imposed by browsers.
Where is the file that you're running? If it is in your public html folder, you can do echo dirname(__FILE__);
Try phoneNumber.setVisibility(View.GONE);
I actually found a better way using the jQuery approach
var box = {
config:{
color: 'red'
},
init:function(config){
$.extend(this.config,config);
}
};
var myBox = box.init({
color: blue
});
perlfaq5: How do I select a random line from a file? Here's a reservoir-sampling algorithm from the Camel Book:
perl -e 'srand; rand($.) < 1 && ($line = $_) while <>; print $line;' file
This has a significant advantage in space over reading the whole file in. You can find a proof of this method in The Art of Computer Programming, Volume 2, Section 3.4.2, by Donald E. Knuth.
As mentioned many times in the thread above, it's dependent on the framework in use. .Net Framework 3 and above has the .Contains() or Exists() methods for arrays. For other frameworks below, can do the following trick instead of looping through array...
((IList<string>)"Your String Array Here").Contains("Your Search String Here")
Not too sure on efficiency... Dave
Apart from the DATEDIFF you can also use the TIMEDIFF function or the TIMESTAMPDIFF.
EXAMPLE
SET @date1 = '2010-10-11 12:15:35', @date2 = '2010-10-10 00:00:00';
SELECT
TIMEDIFF(@date1, @date2) AS 'TIMEDIFF',
TIMESTAMPDIFF(hour, @date1, @date2) AS 'Hours',
TIMESTAMPDIFF(minute, @date1, @date2) AS 'Minutes',
TIMESTAMPDIFF(second, @date1, @date2) AS 'Seconds';
RESULTS
TIMEDIFF : 36:15:35
Hours : -36
Minutes : -2175
Seconds : -130535
Do you want to do something like this ?
JTextField mTextField = new JTextField();
mTextField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER){
// something like...
//mTextField.getText();
// or...
//mButton.doClick();
}
}
});
Use kscript
kscript 'lines.split().select(-1,-2).print()' file
go 1.13
(exec from module root directory)
Update specified dependencies:
go get -u <package-name>
Update all direct and indirect dependencies to latest minor or patch upgrades (pre-releases are ignored):
go get -u ./...
# or
go get -u=patch ./...
Reference:
https://github.com/golang/go/wiki/Modules#daily-workflow
go help get
The .clone()
thing does not work in Opera (and possibly others). It keeps the content.
The closest method here for me was Jonathan's earlier, however ensuring that the field preserved its name, classes, etc made for messy code in my case.
Something like this might work well (thanks to Quentin too):
function clearInput($source) {
var $form = $('<form>')
var $targ = $source.clone().appendTo($form)
$form[0].reset()
$source.replaceWith($targ)
}
First, run npm install expo-linear-gradient --save
You don't need to use an animated tag, but this is what I was using in my code.
inside colors={[ put your gradient colors ]}
then you can use something like this:
import { LinearGradient } from "expo-linear-gradient";
import { Animated } from "react-native";
<AnimatedLinearGradient
colors={["rgba(255,255,255, 0)", "rgba(255,255,255, 1)"]}
style={{ your styles go here }}/>
const AnimatedLinearGradient = Animated.createAnimatedComponent(LinearGradient);
Below code works for me
public static void sftpsript(String filepath) {
try {
String user ="demouser"; // username for remote host
String password ="demo123"; // password of the remote host
String host = "demo.net"; // remote host address
JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect();
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
sftpChannel.disconnect();
session.disconnect();
}catch(Exception ex){
ex.printStackTrace();
}
}
OR using StrictHostKeyChecking as "NO" (security consequences)
public static void sftpsript(String filepath) {
try {
String user ="demouser"; // username for remote host
String password ="demo123"; // password of the remote host
String host = "demo.net"; // remote host address
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);;
session.setPassword(password);
System.out.println("user=="+user+"\n host=="+host);
session.connect();
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
sftpChannel.disconnect();
session.disconnect();
}catch(Exception ex){
ex.printStackTrace();
}
}
I'm not sure what you want to accomplish, but in this case just adding width: 100%;
to your ul#slideshow li
will do the trick.
The img
tags are inline-block elements. This means that they flow inline like text, but also have a width and height like block elements. In your css there are two text-align: center;
rules applied to the <body>
and to the #slideshowWrapper
(which is redundant btw) this makes all inline and inline-block child elements to be centered in their closest block elements, in your code these are li
tags. All block elements have width: 100%
if they are the static flow (position: static;
), which is default. The problem is that when you tell li
tags to be position: absolute;
, you take them out of normal static flow, and this causes them to shrink their size to just fit their inner content, in other words they kind of "lose" their width: 100%
property.
You could simply use the +
or +=
operator as follows:
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
Or:
c = []
a = [1, 2, 3]
b = [4, 5, 6]
c += (a + b)
Also, if you want the values in the merged list to be unique you can do:
c = list(set(a + b))
I had this problem with local var and i just detach it like this:
if (ModelState.IsValid)
{
var old = db.Channel.Find(channel.Id);
if (Request.Files.Count > 0)
{
HttpPostedFileBase objFiles = Request.Files[0];
using (var binaryReader = new BinaryReader(objFiles.InputStream))
{
channel.GateImage = binaryReader.ReadBytes(objFiles.ContentLength);
}
}
else
channel.GateImage = old.GateImage;
var cat = db.Category.Find(CatID);
if (cat != null)
channel.Category = cat;
db.Entry(old).State = EntityState.Detached; // just added this line
db.Entry(channel).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(channel);
Problem causes of loaded objects with same Key, so first we will detach that object and do the the updating to avoid conflict between two object with the same Key
The easiest solution is to use $stateChangeStart
and event.preventDefault()
to cancel the state change when the user is not authenticated and redirect him to the auth state that is the login page.
angular
.module('myApp', [
'ui.router',
])
.run(['$rootScope', 'User', '$state',
function ($rootScope, User, $state) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
if (toState.name !== 'auth' && !User.authenticaded()) {
event.preventDefault();
$state.go('auth');
}
});
}]
);
Arrays can't be passed as function parameters by value in C.
You can put the array in a struct:
typedef struct type24 {
char byte[3];
} type24;
and then pass that by value, but of course then it's less convenient to use: x.byte[0]
instead of x[0]
.
Your function type24_to_int32(char value[3])
actually passes by pointer, not by value. It's exactly equivalent to type24_to_int32(char *value)
, and the 3
is ignored.
If you're happy passing by pointer, you could stick with the array and do:
type24_to_int32(const type24 *value);
This will pass a pointer-to-array, not pointer-to-first-element, so you use it as:
(*value)[0]
I'm not sure that's really a gain, since if you accidentally write value[1]
then something stupid happens.
load data infile '/root/source/in.txt' into table employee;
==> Error Code:13
load data infile '/tmp/in.txt' into table employee;
==> works
CentOS release 6.6 (Final) - 5.5.32 MySQL Community Server (GPL)
something related to Linux file permissions
Try this (subquery):
SELECT * FROM terms WHERE id IN
(SELECT term_id FROM terms_relation WHERE taxonomy = "categ")
Or you can try this (JOIN):
SELECT t.* FROM terms AS t
INNER JOIN terms_relation AS tr
ON t.id = tr.term_id AND tr.taxonomy = "categ"
If you want to receive all fields from two tables:
SELECT t.id, t.name, t.slug, tr.description, tr.created_at, tr.updated_at
FROM terms AS t
INNER JOIN terms_relation AS tr
ON t.id = tr.term_id AND tr.taxonomy = "categ"
If you wanna get the uploaded file name, use $_FILES["file"]["name"]
But If you wanna read the uploaded file you should use $_FILES["file"]["tmp_name"]
, because tmp_name is a temporary copy of your uploaded file and it's easier than using
$_FILES["file"]["name"] // This name includes a file path, which makes file read process more complex
For Firefox you need to go a little deeper with this:
var imgs = document.getElementsByTagName('img');
// loop through fetched images
for (i = 0; i < imgs.length; i++) {
// and define onmousedown event handler
imgs[i].onmousedown = disableDragging;
}
function disableDragging(e) {
e.preventDefault();
}
Enjoy.
Adapted from this answer to a very similar question:
FORFILES /S /D -10 /C "cmd /c IF @isdir == TRUE rd /S /Q @path"
You should run this command from within your d:\study
folder. It will delete all subfolders which are older than 10 days.
The /S /Q
after the rd
makes it delete folders even if they are not empty, without prompting.
I suggest you put the above command into a .bat file, and save it as d:\study\cleanup.bat
.
You can also do it at run time as follows :
HomePage.WindowState = WindowState.Maximized;
Action Filters, jquery stringify, bleh...
Peter, this functionality is native to MVC. That's one of things that makes MVC so great.
$.post('SomeController/Batch', { 'ids': ['1', '2', '3']}, function (r) {
...
});
And in the action,
[HttpPost]
public ActionResult Batch(string[] ids)
{
}
Works like a charm:
If you're using jQuery 1.4+, then you want to look into setting traditional mode:
jQuery.ajaxSettings.traditional = true;
As described here: http://www.dovetailsoftware.com/blogs/kmiller/archive/2010/02/24/jquery-1-4-breaks-asp-net-mvc-actions-with-array-parameters
This even works for complex objects. If you're interested, you should look into the MVC documentation about Model Binding: http://msdn.microsoft.com/en-us/library/dd410405.aspx
Tested on Ubuntu Server 10.04. I hope it helps you also on Arch Linux.
In PHP use shell_exec function:
Execute command via shell and return the complete output as a string.
It returns the output from the executed command or NULL if an error occurred or the command produces no output.
<?php
$command = escapeshellcmd('/usr/custom/test.py');
$output = shell_exec($command);
echo $output;
?>
In Python file test.py
, verify this text in first line: (see shebang explain):
#!/usr/bin/env python
Also Python file must have correct privileges (execution for user www-data / apache if PHP script runs in browser or curl)
and/or must be "executable". Also all commands into .py
file must have correct privileges:
Taken from php manual:
Just a quick reminder for those trying to use shell_exec on a unix-type platform and can't seem to get it to work. PHP executes as the web user on the system (generally www for Apache), so you need to make sure that the web user has rights to whatever files or directories that you are trying to use in the shell_exec command. Other wise, it won't appear to be doing anything.
To make executable a file on unix-type platforms:
chmod +x myscript.py
I know this is quite an old answer.
Here is a faster solution without using foreach
:
Use array_column
print_r(array_column($array, 'firstname')); #returns the value associated with that key 'firstname'
Also you can check before executing the above operation
if(array_key_exists('firstname', $array)){
print_r(array_column($array, 'firstname'));
}
A simple increment should do the trick.
UPDATE mytable
SET logins = logins + 1
WHERE id = 12
If you would like to update a previously existing row, or insert it if it doesn't already exist, you can use the REPLACE
syntax or the INSERT...ON DUPLICATE KEY UPDATE
option (As Rob Van Dam demonstrated in his answer).
Or perhaps you're looking for something like INSERT...MAX(logins)+1
? Essentially you'd run a query much like the following - perhaps a bit more complex depending on your specific needs:
INSERT into mytable (logins)
SELECT max(logins) + 1
FROM mytable
Its workaround.
If you not push to server, you will clone into new folder else washout(delete all files) from your repository folder and clone new.
In newer JavaScript standards like ES5 and ES6 you can just say
> Boolean(0) //false
> Boolean(null) //false
> Boolean(undefined) //false
all return false, which is similar to Python's check of empty variables. So if you want to write conditional logic around a variable, just say
if (Boolean(myvar)){
// Do something
}
here "null" or "empty string" or "undefined" will be handled efficiently.
git pull -s recursive -X theirs <remoterepo or other repo>
Or, simply, for the default repository:
git pull -X theirs
If you're already in conflicted state...
git checkout --theirs path/to/file
OVERKILL!
public static class AwesomeExtensions
{
public static bool IsPositive(this int number)
{
return number > 0;
}
public static bool IsNegative(this int number)
{
return number < 0;
}
public static bool IsZero(this int number)
{
return number == 0;
}
public static bool IsAwesome(this int number)
{
return IsNegative(number) && IsPositive(number) && IsZero(number);
}
}
What you are trying to achieve is equivalent to
interface Event {
name: string;
dateCreated: string;
type: string;
}
interface UserEvent extends Event {
UserId: string;
}
The way you defined the types does not allow for specifying inheritance, however you can achieve something similar using intersection types, as artem pointed out.
With something like this:
String mDrawableName = "myappicon";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
You can add a div
to the td
, then style that. It should work as you expected.
<td><div>AAAAAAAAAAAAAAAAAAA</div></td>
Then the css.
td div { width: 50px; overflow: hidden; }
You can find remainder using modulo operator Example
a=14
b=10
print(a%b)
It will print 4
@import url("http://netdna.bootstrapcdn.com/bootstrap/3.0.0-wip/css/bootstrap.min.css");
.row {
height: 100px;
background-color: green;
}
.container {
margin-top: 50px;
box-shadow: 0 0 30px black;
padding:0 15px 0 15px;
}
<div class="container">
<div class="row">one</div>
<div class="row">two</div>
<div class="row">three</div>
</div>
</body>
I managed to get it working by following Option 2 on the Windows installation instructions on the following page: https://github.com/nodejs/node-gyp.
I had to close the current command line interface and reopen it after doing the installation on another one logged in as Administrator.
On iOS5 only if you plan to let the users zoom the webview contents (e.i.: double tap) the bounce setting isn't enough. You need to set also alwaysBounceHorizontal and alwaysBounceVertical properties to NO, else when they zoom-out (another double tap...) to default it will bounce again.
There is an codeproject project avaliable HERE that provides this functuanility.
Following many threads here on SO and other boards this cant be done with the normal MessageBox.
Edit:
I have an idea that is a bit ehmmm yeah..
Use a timer and start in when the MessageBox appears.
If your MessageBox only listens to the OK Button (only 1 possibility) then use the OnTick-Event to emulate an ESC-Press with SendKeys.Send("{ESC}");
and then stop the timer.
Another solution:
def permutation(flag, k =1 ):
N = len(flag)
for i in xrange(0, N):
if flag[i] != 0:
continue
flag[i] = k
if k == N:
print flag
permutation(flag, k+1)
flag[i] = 0
permutation([0, 0, 0])
I know it's an old post. But it happens that I had a query that used group by just to return distinct values when using that query in toad and oracle reports everything worked fine, I mean a good response time. When we migrated from Oracle 9i to 11g the response time in Toad was excellent but in the reporte it took about 35 minutes to finish the report when using previous version it took about 5 minutes.
The solution was to change the group by and use DISTINCT and now the report runs in about 30 secs.
I hope this is useful for someone with the same situation.
You are missing the event parameter on your function.
$(document).on("click",".appDetails", function (event) {
alert(event.target.id);
});
Something else to check is make sure viewstate is on (I just solved this yesterday). If you don't have viewstate on, the gridview will be blank until you load it again.
By mid-2016 the Chromium engine (v53) supports just 3 emphasis styles:
Plain text, bold, and super-bold...
<div style="font:normal 400 14px Arial;">Testing</div>
<div style="font:normal 700 14px Arial;">Testing</div>
<div style="font:normal 800 14px Arial;">Testing</div>
For Example :
http://character-code.com/arrows-html-codes.php
Example: If you want select your character , I selected "↬" "↬" (We use HEX values)
.breadcrumbs a:before {
content: '\0021ac';
}
Result : ↬
Thats it :)
You can use jsoup
to parse any kind of web page. Here you can find the jsoup library and full source code.
Here is an example: http://desicoding.blogspot.com/2011/03/how-to-parse-html-in-java-jsoup.html
To install in Eclipse:
You can parse according to tag/parent/child very comfortably
The way I use is:
git submodule update --init --recursive
git submodule foreach --recursive git fetch
git submodule foreach git merge origin master
$('#item1').text(); or $('#item1').html();
works fine for id="item1"
Try this:
<img style="display: inline;" src="img/logo.png" alt="logo" />
<h1 style="display: inline;">My website name</h1>
Found another solution for the same. It will be more helpful.
START C:\"Program Files (x86)"\Test\"Test Automation"\finger.exe ConfigFile="C:\Users\PCName\Desktop\Automation\Documents\Validation_ZoneWise_Default.finger.Config"
finger.exe is a parent program that is calling config solution. Note: if your path folder name consists of spaces, then do not forget to add "".
[INFO] BUILD SUCCESS
Anyway, it works for me:)
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF8
And for those of you using an anonymous expression:
await Task.Run(async () =>
{
SQLLiteUtils slu = new SQLiteUtils();
await slu.DeleteGroupAsync(groupname);
});
Here is some SQL that actually make sense:
SELECT m.id FROM match m LEFT JOIN email e ON e.id = m.id WHERE e.id IS NULL
Simple is always better.
Tail the log as a background job (&) and it will interleave with rspec output.
tail -f log/test.log &
bundle exec rspec
I had this issue and it was actually caused by something different - I had the 'IIS APPPOOL\ASP.NET v4.0' user in my database but it still wasn't working.
I had recently upgraded my SQL Server Install and in the process the User had become disconnected from the Login - so there was an 'IIS APPPOOL\ASP.NET v4.0' under Database -> Security -> Users BUT no User not under Security -> Logins.
Added the Login 'IIS APPPOOL\ASP.NET v4.0' to Security -> Logins, SQL Server automatically mapped it to the User in the database (this used to have to be done manually) and problem fixed.
try .includes()
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
[1, 2, 3].includes(3, 3); // false
[1, 2, 3].includes(3, -1); // true
[1, 2, NaN].includes(NaN); // true
so something like
const array = [1, 3];
if (!array.includes(2))
array.push(2);
note the browser compatibility at the bottom of the page, however.
Im a bit late to the party and I know the OP said html, but if you needed to do this in MVC you can set true
in the third param.
eg:
<p>Option One :@Html.RadioButton("options", "option1", true})</p>
// true will set it checked
<p>Option Two :@Html.RadioButton("options", "option2"})</p>
//nothing will leave it unchecked
You could use :before
and content:
bearing in mind that this is not supported in IE 7 or below. If you're OK with that then this is your best solution. See the Can I Use or QuirksMode CSS compatibility tables for full details.
A slightly nastier solution that should work in older browsers is to use an image for the bullet point and just make the image look like a dash. See the W3C list-style-image
page for examples.
A note for others who may be using Owl Carousel v 1.3.2:
You can replace the navigation text in the settings where you're enabling the navigation.
navigation:true,
navigationText: [
"<i class='fa fa-chevron-left'></i>",
"<i class='fa fa-chevron-right'></i>"
]
When you use ng-options to populate a select list, it uses the entire object as the selected value, not just the single value you see in the select list. So in your case, you'd need to set
$scope.object.setDefault = {
id:600,
name:"def"
};
or
$scope.object.setDefault = $scope.selectItems[1];
I also recommend just outputting the value of $scope.object.setDefault in your template to see what I'm talking about getting selected.
<pre>{{object.setDefault}}</pre>
Inspired by Enigmativity's answer - let's assume you have two (or more) classes, like
public class Bar { }
public class Square { }
and you want to call the method Foo<T>
with Bar
and Square
, which is declared as
public class myClass
{
public void Foo<T>(T item)
{
Console.WriteLine(typeof(T).Name);
}
}
Then you can implement an Extension method like:
public static class Extension
{
public static void InvokeFoo<T>(this T t)
{
var fooMethod = typeof(myClass).GetMethod("Foo");
var tType = typeof(T);
var fooTMethod = fooMethod.MakeGenericMethod(new[] { tType });
fooTMethod.Invoke(new myClass(), new object[] { t });
}
}
With this, you can simply invoke Foo
like:
var objSquare = new Square();
objSquare.InvokeFoo();
var objBar = new Bar();
objBar.InvokeFoo();
which works for every class. In this case, it will output:
Square
Bar
The code pasted by Rivers is great. Thanks a lot! I'm new here and can't comment, I'd just want to answer to the question from javiervd (How would you set the screen_name and count with this approach?), as I've lost a lot of time to figure it out.
You need to add the parameters both to the URL and to the signature creating process. Creating a signature is the article that helped me. Here is my code:
$oauth = array(
'screen_name' => 'DwightHoward',
'count' => 2,
'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0'
);
$options = array(
CURLOPT_HTTPHEADER => $header,
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url . '?screen_name=DwightHoward&count=2',
CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false
);
IE has a setting, located in Tools
/ Internet options
/ Advanced
/ Browsing
, called Reuse windows for launching shortcuts
, which is checked by default. For IE versions that support tabbed browsing, this option is relevant only when tab browsing is turned off (in fact, IE9 Beta explicitly mentions this). However, since IE6 does not have tabbed browsing, this option does affect opening URLs through the shell (as in your example).
You can use this, in a controller method or in an inline function of a route:
try {
DB::connection()->getPdo();
if(DB::connection()->getDatabaseName()){
echo "Yes! Successfully connected to the DB: " . DB::connection()->getDatabaseName();
}else{
die("Could not find the database. Please check your configuration.");
}
} catch (\Exception $e) {
die("Could not open connection to database server. Please check your configuration.");
}
It does not sound like you imported the library right especially when you say at the point Add the library to your application project: I felt lost .. basically because I don't have the "add" option by itself .. however I clicked on "add library" and moved on ..
in eclipse you need to right click on the project, go to Properties, select Android in the list then Add to add the library
follow this tutorial in the docs
http://developer.android.com/tools/support-library/setup.html
I found this quite useful in my case after the button click.
$('#buttonId').blur();
Your json -
{
"title":"Free Music Archive - Genres",
"message":"",
"errors":[
],
"total":"163",
"total_pages":82,
"page":1,
"limit":"2",
"dataset":[
{
"genre_id":"1",
"genre_parent_id":"38",
"genre_title":"Avant-Garde",
"genre_handle":"Avant-Garde",
"genre_color":"#006666"
},
{
"genre_id":"2",
"genre_parent_id":null,
"genre_title":"International",
"genre_handle":"International",
"genre_color":"#CC3300"
}
]
}
Using the JSON library from json.org
-
JSONObject o = new JSONObject(jsonString);
NOTE:
The following information will be helpful to you - json.org.
UPDATE:
import org.json.JSONObject;
//Other lines of code
URL seatURL = new URL("http://freemusicarchive.org/
api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2");
//Return the JSON Response from the API
BufferedReader br = new BufferedReader(new
InputStreamReader(seatURL.openStream(),
Charset.forName("UTF-8")));
String readAPIResponse = " ";
StringBuilder jsonString = new StringBuilder();
while((readAPIResponse = br.readLine()) != null){
jsonString.append(readAPIResponse);
}
JSONObject jsonObj = new JSONObject(jsonString.toString());
System.out.println(jsonString);
System.out.println("---------------------------");
System.out.println(jsonObj);
The .push
method can take multiple arguments. You can use the spread operator to pass all the elements of the second array as arguments to .push
:
>>> a.push(...b)
If your browser does not support ECMAScript 6, you can use .apply
instead:
>>> a.push.apply(a, b)
Or perhaps, if you think it's clearer:
>>> Array.prototype.push.apply(a,b)
Please note that all these solutions will fail with a stack overflow error if array b
is too long (trouble starts at about 100,000 elements, depending on the browser).
If you cannot guarantee that b
is short enough, you should use a standard loop-based technique described in the other answer.
If your current min. API level is 23, you can simply use getColor()
like we are using for getString()
:
//example
textView.setTextColor(getColor(R.color.green));
// if context is not available(ex: not in activity) use with context.getColor()
If you want below API level 23
, just use this:
textView.setTextColor(getResources().getColor(R.color.green));
But note that getResources().getColor()
is deprecated in API Level 23
. In that case replace above with:
textView.setTextColor(ContextCompat.getColor(this /*context*/, R.color.green)) //Im in an activity, so I can use `this`
ContextCompat: Helper for accessing features in Context
If You want, you can constraint with SDK_INT
like below:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
textView.setTextColor(getColor(R.color.green));
} else {
textView.setTextColor(getResources().getColor(R.color.green));
}
A programming language implementation is a system for executing computer programs.
There are two general approaches to programming language implementation:
Python is an interpreted high-level programming language created by Guido van Rossum in 1991.
CPython is reference version of the Python computing language, which is written in C created by Guido van Rossum too.
To get the currently logged in user:
System.getProperty("user.name");
To get the host name of the machine:
InetAddress.getLocalHost().getHostName();
To answer the last part of your question, the Java API says that getHostName() will return
the host name for this IP address, or if the operation is not allowed by the security check, the textual representation of the IP address.
The json.dumps method can accept an optional parameter called default which is expected to be a function. Every time JSON tries to convert a value it does not know how to convert it will call the function we passed to it. The function will receive the object in question, and it is expected to return the JSON representation of the object.
def myconverter(o):
if isinstance(o, datetime.datetime):
return o.__str__()
print(json.dumps(d, default = myconverter))
since your over
div doesn't have a positioning, the z-index doesn't know where and how to position it (and with respect to what?). Just change your over div's position to relative, so there is no side effects on that div and then the under div will obey to your will.
here is your example on jsfiddle: Fiddle
edit: I see someone already mentioned this answer!
ul li{
display: inline;
}
For more see the basic list options and a basic horizontal list at listamatic. (thanks to Daniel Straight below for the links).
Also, as pointed out in the comments, you probably want styling on the ul and whatever elements go inside the li's and the li's themselves to get things to look nice.
Here's a solution using the new async/await syntax.
Be sure to check browser support as this is a language feature introduced with ECMAScript 6.
Utility function:
const delay = ms => new Promise(res => setTimeout(res, ms));
Usage:
const yourFunction = async () => {
await delay(5000);
console.log("Waited 5s");
await delay(5000);
console.log("Waited an additional 5s");
};
The advantage of this approach is that it makes your code look and behave like synchronous code.
The error you quote has nothing to do with pg_hba.conf
; it's failing to connect, not failing to authorize the connection.
Do what the error message says:
Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections
You haven't shown the command that produces the error. Assuming you're connecting on localhost
port 5432
(the defaults for a standard PostgreSQL install), then either:
PostgreSQL isn't running
PostgreSQL isn't listening for TCP/IP connections (listen_addresses
in postgresql.conf
)
PostgreSQL is only listening on IPv4 (0.0.0.0
or 127.0.0.1
) and you're connecting on IPv6 (::1
) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.
PostgreSQL is listening on a different port to the one you're connecting on
(unlikely) there's an iptables
rule blocking loopback connections
(If you are not connecting on localhost
, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).
So ... check those:
ps -f -u postgres
should list postgres
processes
sudo lsof -n -u postgres |grep LISTEN
or sudo netstat -ltnp | grep postgres
should show the TCP/IP addresses and ports PostgreSQL is listening on
BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:
$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 12345?
This should be the Unix load average. Wikipedia has a nice article about this.
The numbers show the average load of the CPU in different time intervals. From left to right: last minute/last five minutes/last fifteen minutes
Note that this answer is outdated! The mysql extension is no longer available out of the box as of PHP7. If you want to use the old mysql functions in PHP7, you will have to compile ext/mysql from PECL. See the other answers for more current solutions.
This would work, see more documentation here : http://php.net/manual/en/function.mysql-fetch-array.php
$result = mysql_query("SELECT names FROM Customers");
$storeArray = Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[] = $row['names'];
}
// now $storeArray will have all the names.
Usually sqlcmd
comes with bcp
utility (as part of mssql-tools
) which exports into CSV by default.
Usage:
bcp {dbtable | query} {in | out | queryout | format} datafile
For example:
bcp.exe MyTable out data.csv
To dump all tables into corresponding CSV files, here is the Bash script:
#!/usr/bin/env bash
# Script to dump all tables from SQL Server into CSV files via bcp.
# @file: bcp-dump.sh
server="sql.example.com" # Change this.
user="USER" # Change this.
pass="PASS" # Change this.
dbname="DBNAME" # Change this.
creds="-S '$server' -U '$user' -P '$pass' -d '$dbname'"
sqlcmd $creds -Q 'SELECT * FROM sysobjects sobjects' > objects.lst
sqlcmd $creds -Q 'SELECT * FROM information_schema.routines' > routines.lst
sqlcmd $creds -Q 'sp_tables' | tail -n +3 | head -n -2 > sp_tables.lst
sqlcmd $creds -Q 'SELECT name FROM sysobjects sobjects WHERE xtype = "U"' | tail -n +3 | head -n -2 > tables.lst
for table in $(<tables.lst); do
sqlcmd $creds -Q "exec sp_columns $table" > $table.desc && \
bcp $table out $table.csv -S $server -U $user -P $pass -d $dbname -c
done
You can't style combos very well using CSS.
The guys at FogBugz made a pretty good custom combo using JavaScript, so it is possible, it just takes a lot of work to get it right.
Better to stick with the standard one for version 1, then see if it's worth updating it once your app is in the wild.
find . -type d > list.txt
Will list all directories and subdirectories under the current path. If you want to list all of the directories under a path other than the current one, change the .
to that other path.
If you want to exclude certain directories, you can filter them out with a negative condition:
find . -type d ! -name "~snapshot" > list.txt
to hide the horizontal scrollbars, you can set overflow-x to hidden, like this:
overflow-x: hidden;
Go to project then
Right click on project---> Build Path-->Configure build path
Now there are 4 tabs Source, Projects, Libraries, Order and Export
Go to
Libraries tab --> Click on Add Library (shown at the right side) -->
select JRE System Library --> Next-->click Alternate JRE --> select
Installed JRE--> Finish --> Apply--> OK.
Worth noting (from this issue) that if you're attaching events to document
, e.stopPropagation()
isn't going to help. As a workaround, you can use window.addEventListener()
instead of document.addEventListener
, then event.stopPropagation()
will stop event from propagating to the window.
I would try the following syntax - it works for me.
msiexec /x filename.msi /q
Because the act of acquiring the position and getting the element from the given position naturally requires some locking (you can't have the list have structural changes between those two operations).
The very idea of a concurrent collection is that each operation on its own is atomic and can be done without explicit locking/synchronization.
Therefore getting the element at position n
from a given List
as an atomic operation doesn't make too much sense in a situation where concurrent access is anticipated.
You can also run ->select('DISTINCT `field`', FALSE)
and the second parameter tells CI
not to escape the first argument.
With the second parameter as false
, the output would be SELECT DISTINCT `field`
instead of without the second parameter, SELECT `DISTINCT` `field`
With postgres 9.3 use -> for object access. 4 example
seed.rb
se = SmartElement.new
se.data =
{
params:
[
{
type: 1,
code: 1,
value: 2012,
description: 'year of producction'
},
{
type: 1,
code: 2,
value: 30,
description: 'length'
}
]
}
se.save
rails c
SELECT data->'params'->0 as data FROM smart_elements;
returns
data
----------------------------------------------------------------------
{"type":1,"code":1,"value":2012,"description":"year of producction"}
(1 row)
You can continue nesting
SELECT data->'params'->0->'type' as data FROM smart_elements;
return
data
------
1
(1 row)
I was having the similar issue when using VirtualBox on Ubuntu 12.04LTS. Now if anyone is using or has ever used Ubuntu, you might be aware that how things are hard sometimes when using shortcut keys in Ubuntu. For me, when i was trying to revert back the Host key, it was just not happening and the shortcut keys won't just work. I even tried the command line option to revert back the scale mode and it won't work either. Finally i found the following when all the other options fails:
Fix the Scale Mode Issue in Oracle VirtualBox in Ubuntu using the following steps:
Find your machine config files (i.e. /home/<username>/VirtualBox VMs/ANKSVM
) where ANKSVM is your VM Name and edit and change the following
in ANKSVM.vbox
and ANKSVM.vbox-prev
files:
Edit the line: <ExtraDataItem name="GUI/Scale" value="on"/>
to
<ExtraDataItem name="GUI/Scale" value="off"/>
Restart VirtualBox
You are done.
This works every time specially when all other options fails like how it happened for me.
It's really simple,just add image to background of you button and give text to titlelabel of button for uicontrolstatenormal. That's it.
[btn setBackgroundImage:[UIImage imageNamed:@"img.png"] forState:UIControlStateNormal];
[btn setContentVerticalAlignment:UIControlContentVerticalAlignmentBottom];
[btn setTitle:@"Click Me" forState:UIControlStateNormal];
If you are using macOS sierra there is a update in PHP version. you need to have Entrust.net Certificate Authority (2048) file added to the PHP code. more info check accepted answer here Push Notification in PHP using PEM file
$type_array = array();
while($row = mysql_fetch_assoc($result)) {
$type_array[] = $row['type'];
}
This means that you must declare strict mode by writing "use strict"
at the beginning of the file or the function to use block-scope declarations.
EX:
function test(){
"use strict";
let a = 1;
}
See here: Search Path
Summary:
#include <stdio.h>
When the include file is in brackets the preprocessor first searches in paths specified via the -I flag. Then it searches the standard include paths (see the above link, and use the -v flag to test on your system).
#include "myFile.h"
When the include file is in quotes the preprocessor first searches in the current directory, then paths specified by -iquote, then -I paths, then the standard paths.
-nostdinc can be used to prevent the preprocessor from searching the standard paths at all.
Environment variables can also be used to add search paths.
When compiling if you use the -v flag you can see the search paths used.
If your ajax response are containing html form inputs for instance, than this would be great:
$(document).on("change", 'input[type=radio][name=fieldLoadedFromAjax]', function(event) {
if (this.value == 'Yes') {
// do something here
} else if (this.value == 'No') {
// do something else here.
} else {
console.log('The new input field from an ajax response has this value: '+ this.value);
}
});
use Date.prototype.toLocaleTimeString()
as documented here
please note the locale example en-US in the url.
If you have a large index, you should use a default value
<field ... default="EMPTY" />
and then query for this default value. This is much more efficient than q=-id:["" TO *]
Microsoft has listened to the cry for supporting installers (MSI) in Visual Studio and release the Visual Studio Installer Projects Extension. You can now create installers in VS2013, download the extension here from the visualstudiogallery.
You just have to set UIFileSharingEnabled
(Application Supports iTunes file sharing
) key in the info plist of your app. Here's a link for the documentation. Scroll down to the file sharing support part.
In the past, it was also necessary to define CFBundleDisplayName
(Bundle Display Name
), if it wasn't already there. More details here.
You can bind to the DOMNodeRemoved event (part of DOM Level 3 WC3 spec).
Works in IE9, latest releases of Firefox and Chrome.
Example:
$(document).bind("DOMNodeRemoved", function(e)
{
alert("Removed: " + e.target.nodeName);
});
You can also get notification when elements are inserting by binding to DOMNodeInserted
I did this using a python script and google drive api, You can try out this snippet:
//using chunk download
file_id = 'someid'
request = drive_service.files().get_media(fileId=file_id)
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
print "Download %d%%." % int(status.progress() * 100)
here is our Regex for this case:
@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
@".)+))([a-zA-Z]{2,6}|[0-9]{1,3})(\]?)$",
there are three parts, which are checcked. the last one is propably the one you need. the specific term {2,6} indicates you the min/max length of the TLD at the end. HTH