Abstract classes/methods are generally used when a class provides some high level functionality but leaves out certain details to be implemented by derived classes. Making the class/method abstract ensures that it cannot be used on its own, but must be specialized to define the details that have been left out of the high level implementation. This is most often used with the template method pattern:
Select-Object returns a custom PSObject with just the properties specified. Even with a single property, you don't get the ACTUAL variable; it is wrapped inside the PSObject.
Instead, do:
Get-Date | Select-Object -ExpandProperty DayOfWeek
That will get you the same result as:
(Get-Date).DayOfWeek
The difference is that if Get-Date returns multiple objects, the pipeline way works better than the parenthetical way as (Get-ChildItem)
, for example, is an array of items. This has changed in PowerShell v3 and (Get-ChildItem).FullPath
works as expected and returns an array of just the full paths.
There's actually a very little known class in the BCL for this purpose exactly: CommaDelimitedStringCollectionConverter. It serves as a middle ground of sorts between having a ConfigurationElementCollection
(as in Richard's answer) and parsing the string yourself (as in Adam's answer).
For example, you could write the following configuration section:
public class MySection : ConfigurationSection
{
[ConfigurationProperty("MyStrings")]
[TypeConverter(typeof(CommaDelimitedStringCollectionConverter))]
public CommaDelimitedStringCollection MyStrings
{
get { return (CommaDelimitedStringCollection)base["MyStrings"]; }
}
}
You could then have an app.config that looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="foo" type="ConsoleApplication1.MySection, ConsoleApplication1"/>
</configSections>
<foo MyStrings="a,b,c,hello,world"/>
</configuration>
Finally, your code would look like this:
var section = (MySection)ConfigurationManager.GetSection("foo");
foreach (var s in section.MyStrings)
Console.WriteLine(s); //for example
Try running all targets individually to check that all are running correct
run ant target name to run a target individually
e.g. ant build-project
Also the default target you specified is
project basedir="." default="build" name="iControlSilk4J"
This will only execute build-subprojects,build-project and init
UEFA or FIFA don't seem to provide any API to get the information you want. However, there are some third-party services which support that:
OPTA - Both commercial and free. They have incredible database about matches. Whoscored.com currently uses it.
Others: livescoreboards, xmlsoccer, ...
delete
operator is used to remove
an object property
.
delete
operator does not returns the new object, only returns a boolean
: true or false.
In the other hand, after interpreter executes var updatedjsonobj = delete myjsonobj['otherIndustry'];
, updatedjsonobj
variable will store a boolean
value.
How to remove Json object specific key and its value ?
You just need to know the property name in order to delete it from the object's properties.
delete myjsonobj['otherIndustry'];
let myjsonobj = {
"employeeid": "160915848",
"firstName": "tet",
"lastName": "test",
"email": "[email protected]",
"country": "Brasil",
"currentIndustry": "aaaaaaaaaaaaa",
"otherIndustry": "aaaaaaaaaaaaa",
"currentOrganization": "test",
"salary": "1234567"
}
delete myjsonobj['otherIndustry'];
console.log(myjsonobj);
_x000D_
If you want to remove a key
when you know the value you can use Object.keys
function which returns an array of a given object's own enumerable properties.
let value="test";
let myjsonobj = {
"employeeid": "160915848",
"firstName": "tet",
"lastName": "test",
"email": "[email protected]",
"country": "Brasil",
"currentIndustry": "aaaaaaaaaaaaa",
"otherIndustry": "aaaaaaaaaaaaa",
"currentOrganization": "test",
"salary": "1234567"
}
Object.keys(myjsonobj).forEach(function(key){
if (myjsonobj[key] === value) {
delete myjsonobj[key];
}
});
console.log(myjsonobj);
_x000D_
The accept
attribute is incredibly useful. It is a hint to browsers to only show files that are allowed for the current input
. While it can typically be overridden by users, it helps narrow down the results for users by default, so they can get exactly what they're looking for without having to sift through a hundred different file types.
Note: These examples were written based on the current specification and may not actually work in all (or any) browsers. The specification may also change in the future, which could break these examples.
h1 { font-size: 1em; margin:1em 0; }_x000D_
h1 ~ h1 { border-top: 1px solid #ccc; padding-top: 1em; }
_x000D_
<h1>Match all image files (image/*)</h1>_x000D_
<p><label>image/* <input type="file" accept="image/*"></label></p>_x000D_
_x000D_
<h1>Match all video files (video/*)</h1>_x000D_
<p><label>video/* <input type="file" accept="video/*"></label></p>_x000D_
_x000D_
<h1>Match all audio files (audio/*)</h1>_x000D_
<p><label>audio/* <input type="file" accept="audio/*"></label></p>_x000D_
_x000D_
<h1>Match all image files (image/*) and files with the extension ".someext"</h1>_x000D_
<p><label>.someext,image/* <input type="file" accept=".someext,image/*"></label></p>_x000D_
_x000D_
<h1>Match all image files (image/*) and video files (video/*)</h1>_x000D_
<p><label>image/*,video/* <input type="file" accept="image/*,video/*"></label></p>
_x000D_
The
accept
attribute may be specified to provide user agents with a hint of what file types will be accepted.If specified, the attribute must consist of a set of comma-separated tokens, each of which must be an ASCII case-insensitive match for one of the following:
The string
audio/*
- Indicates that sound files are accepted.
The string
video/*
- Indicates that video files are accepted.
The string
image/*
- Indicates that image files are accepted.
A valid MIME type with no parameters
- Indicates that files of the specified type are accepted.
A string whose first character is a U+002E FULL STOP character (.)
- Indicates that files with the specified file extension are accepted.
You have to enable the executable bit for the program.
chmod +x script.sh
Then you can use ./script.sh
You can add the folder to the PATH in your .bashrc
file (located in your home directory).
Add this line to the end of the file:
export PATH=$PATH:/your/folder/here
Here is my Suggestion:
First:
1. Add display: block or table
2. Add position: relative
3. Add width:(percentage also works fine)
Second:
if above trick not works then you have to add float:none;
You can download the wheel corresponding to your configuration here ("Pillow-4.1.1-cp36-cp36m-win_amd64.whl" in your case) and install it with:
pip install some-package.whl
If you have problem to install the wheel read this answer
summation
and your other functions are defined after they're used in main
, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.
You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.
Either move the function bodies before main
, or include method signatures before main
, e.g.:
#include <stdio.h>
int summation(int *, int *, int *);
int main()
{
// ...
If you want to restrict it to one line, use white-space: nowrap;
on the div.
You can't do something like that: (int(sumall[0])+int(sumall[1]))
That's because sumall
is an int
and not a list or dict.
So, summ + sumd
will be you're lucky number
example:
sudo vim /usr/local/netbeans-8.2/etc/netbeans.conf
Try %*s
and %-*s
and prefix each string with the column width:
>>> print "Location: %-*s Revision: %s" % (20,"10-10-10-10","1")
Location: 10-10-10-10 Revision: 1
>>> print "District: %-*s Date: %s" % (20,"Tower","May 16, 2012")
District: Tower Date: May 16, 2012
$.event.special.rightclick = {
bindType: "contextmenu",
delegateType: "contextmenu"
};
$(document).on("rightclick", "div", function() {
console.log("hello");
return false;
});
I was working on some groovy code, which doesn't auto-format on save. What I did was right-click on the code pane, then chose ESLint Fix. That fixed my indents.
JDBC is a much lower-level (and older) specification than JPA. In it's bare essentials, JDBC is an API for interacting with a database using pure SQL - sending queries and retrieving results. It has no notion of objects or hierarchies. When using JDBC, it's up to you to translate a result set (essentially a row/column matrix of values from one or more database tables, returned by your SQL query) into Java objects.
Now, to understand and use JDBC it's essential that you have some understanding and working knowledge of SQL. With that also comes a required insight into what a relational database is, how you work with it and concepts such as tables, columns, keys and relationships. Unless you have at least a basic understanding of databases, SQL and data modelling you will not be able to make much use of JDBC since it's really only a thin abstraction on top of these things.
This works too, with the semi-colon.
NAME=sam; echo $NAME
In addition to other answers, I recommend you to look at this list:
14 Great Android apps that are also open source
For me, NewsBlur, Hacker News Reader and Astrid were the most helpful. Still, I don't know whether they are "suitable for basic learning".
// this is how I always do it
for (i = n; --i >= 0;){
...
}
What you want to do is a combination of part of 1 and all of 2.
You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.
But the 2-argument overload of mockStatic you are using supplies a default strategy for what Mockito/PowerMock should do when you call a method you haven't explicitly stubbed on the mock instance.
From the javadoc:
Creates class mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems. It is the default answer so it will be used only when you don't stub the method call.
The default default stubbing strategy is to just return null, 0 or false for object, number and boolean valued methods. By using the 2-arg overload, you're saying "No, no, no, by default use this Answer subclass' answer method to get a default value. It returns a Long, so if you have static methods which return something incompatible with Long, there is a problem.
Instead, use the 1-arg version of mockStatic to enable stubbing of static methods, then use when-thenReturn to specify what to do for a particular method. For example:
import static org.mockito.Mockito.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
class ClassWithStatics {
public static String getString() {
return "String";
}
public static int getInt() {
return 1;
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
@Test
public void test() {
PowerMockito.mockStatic(ClassWithStatics.class);
when(ClassWithStatics.getString()).thenReturn("Hello!");
System.out.println("String: " + ClassWithStatics.getString());
System.out.println("Int: " + ClassWithStatics.getInt());
}
}
The String-valued static method is stubbed to return "Hello!", while the int-valued static method uses the default stubbing, returning 0.
Try this
function pad (str, max) {
return str.length < max ? pad("0" + str, max) : str;
}
alert(pad("5", 2));
Example
Or
var number = 5;
var i;
if (number < 10) {
alert("0"+number);
}
Example
I use GNU Cash and it uses Open Financial Exchange (ofx) http://www.ofx.net/ to download complete transactions and balances from each account of each bank.
Let me emphasize that again, you get a huge list of transactions with OFX into the GNU Cash. Depending on the account type these transactions can be very detailed description of your transactions (purchases+paycheques), investments, interests, etc.
In my case, even though I have Chase debit card I had to choose Chase Credit to make it work. But Chase wants you to enable this OFX feature by logging into your online banking and enable Quicken/MS Money/etc. somewhere in your profile or preferences. Don't call Chase customer support because they know nothing about it.
This service for OFX and GNU Cash is free. I have heard that they charge $10 a month for other platforms.
OFX can download transactions from 348 banks so far. http://www.ofxhome.com/index.php/home/directory
Actualy, OFX also supports making bill payments, stop a check, intrabank and interbank transfers etc. It is quite extensive. See it here: http://ofx.net/AboutOFX/ServicesSupported.aspx
For CodeIgniter 4
, you can use the built-in API Response Trait
Here's sample code for reference:
<?php namespace App\Controllers;
use CodeIgniter\API\ResponseTrait;
class Home extends BaseController
{
use ResponseTrait;
public function index()
{
$data = [
'data' => 'value1',
'data2' => 'value2',
];
return $this->respond($data);
}
}
Using .isInitialized
property one can check initialization state of a lateinit variable.
if (::file.isInitialized) {
// File is initialized
} else {
// File is not initialized
}
%g can do this:
#include <stdio.h>
int main() {
float w = 234.567;
char x[__SIZEOF_FLOAT__];
sprintf(x, "%g", w);
puts(x);
}
You can use typeof operator.
if( (typeof A === "object" || typeof A === 'function') && (A !== null) )
{
alert("A is object");
}
Note that because typeof new Number(1) === 'object'
while typeof Number(1) === 'number';
the first syntax should be avoided.
COUNT is part of pig see the manual
LOGS= LOAD 'log';
LOGS_GROUP= GROUP LOGS ALL;
LOG_COUNT = FOREACH LOGS_GROUP GENERATE COUNT(LOGS);
SASS has a built-in rgba() function to evaluate values.
rgba($color, $alpha)
E.g.
rgba(#00aaff, 0.5) => rgba(0, 170, 255, 0.5)
An example using your own variables:
$my-color: #00aaff;
$my-opacity: 0.5;
.my-element {
color: rgba($my-color, $my-opacity);
}
Outputs:
.my-element {
color: rgba(0, 170, 255, 0.5);
}
(I don't have enough reputation to comment this on the top post, so I hope someone else can do that for me.) There was a concern raised that the first method:
df.sample(frac=1)
made a deep copy or just changed the dataframe. I ran the following code:
print(hex(id(df)))
print(hex(id(df.sample(frac=1))))
print(hex(id(df.sample(frac=1).reset_index(drop=True))))
and my results were:
0x1f8a784d400
0x1f8b9d65e10
0x1f8b9d65b70
which means the method is not returning the same object, as was suggested in the last comment. So this method does indeed make a shuffled copy.
Here is how I did it!
//create the font
try {
//create the font to use. Specify the size!
Font customFont = Font.createFont(Font.TRUETYPE_FONT, new File("Fonts\\custom_font.ttf")).deriveFont(12f);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
//register the font
ge.registerFont(customFont);
} catch (IOException e) {
e.printStackTrace();
} catch(FontFormatException e) {
e.printStackTrace();
}
//use the font
yourSwingComponent.setFont(customFont);
Put the below <meta>
tag into the <head>
section of your document to force the browser to replace unsecure connections (http) to secured connections (https). This can solve the mixed content problem if the connection is able to use https.
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
If you want to block then add the below tag into the <head>
tag:
<meta http-equiv="Content-Security-Policy" content="block-all-mixed-content">
Either You can use LinkedHashMap<K, V>
or you can implement you own CustomMap which maintains insertion order.
You can use the Following CustomHashMap
with the following features:
null
or empty strings are not allowed.HashMap
vs LinkedHashMap
vs CustomHashMap
interface CustomMap<K, V> extends Map<K, V> {
public boolean insertionRule(K key, V value);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public class CustomHashMap<K, V> implements CustomMap<K, V> {
private Map<K, V> entryMap;
// SET: Adds the specified element to this set if it is not already present.
private Set<K> entrySet;
public CustomHashMap() {
super();
entryMap = new LinkedHashMap<K, V>();
entrySet = new HashSet();
}
@Override
public boolean insertionRule(K key, V value) {
// KEY as null and EMPTY String is not allowed.
if (key == null || (key instanceof String && ((String) key).trim().equals("") ) ) {
return false;
}
// If key already available then, we are not overriding its value.
if (entrySet.contains(key)) { // Then override its value, but we are not allowing
return false;
} else { // Add the entry
entrySet.add(key);
entryMap.put(key, value);
return true;
}
}
public V put(K key, V value) {
V oldValue = entryMap.get(key);
insertionRule(key, value);
return oldValue;
}
public void putAll(Map<? extends K, ? extends V> t) {
for (Iterator i = t.keySet().iterator(); i.hasNext();) {
K key = (K) i.next();
insertionRule(key, t.get(key));
}
}
public void clear() {
entryMap.clear();
entrySet.clear();
}
public boolean containsKey(Object key) {
return entryMap.containsKey(key);
}
public boolean containsValue(Object value) {
return entryMap.containsValue(value);
}
public Set entrySet() {
return entryMap.entrySet();
}
public boolean equals(Object o) {
return entryMap.equals(o);
}
public V get(Object key) {
return entryMap.get(key);
}
public int hashCode() {
return entryMap.hashCode();
}
public boolean isEmpty() {
return entryMap.isEmpty();
}
public Set keySet() {
return entrySet;
}
public V remove(Object key) {
entrySet.remove(key);
return entryMap.remove(key);
}
public int size() {
return entryMap.size();
}
public Collection values() {
return entryMap.values();
}
}
Usage of CustomHashMap
:
public static void main(String[] args) {
System.out.println("== LinkedHashMap ==");
Map<Object, String> map2 = new LinkedHashMap<Object, String>();
addData(map2);
System.out.println("== CustomHashMap ==");
Map<Object, String> map = new CustomHashMap<Object, String>();
addData(map);
}
public static void addData(Map<Object, String> map) {
map.put(null, "1");
map.put("name", "Yash");
map.put("1", "1 - Str");
map.put("1", "2 - Str"); // Overriding value
map.put("", "1"); // Empty String
map.put(" ", "1"); // Empty String
map.put(1, "Int");
map.put(null, "2"); // Null
for (Map.Entry<Object, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
}
O/P:
== LinkedHashMap == | == CustomHashMap ==
null = 2 | name = Yash
name = Yash | 1 = 1 - Str
1 = 2 - Str | 1 = Int
= 1 |
= 1 |
1 = Int |
If you know the KEY's are fixed then you can use EnumMap. Get the values form Properties/XML files
EX:
enum ORACLE {
IP, URL, USER_NAME, PASSWORD, DB_Name;
}
EnumMap<ORACLE, String> props = new EnumMap<ORACLE, String>(ORACLE.class);
props.put(ORACLE.IP, "127.0.0.1");
props.put(ORACLE.URL, "...");
props.put(ORACLE.USER_NAME, "Scott");
props.put(ORACLE.PASSWORD, "Tiget");
props.put(ORACLE.DB_Name, "MyDB");
If you have installed mongodb community server via homebrew, then you can do:
brew services list
This will list the current services as below:
Name Status User Plist
mongodb-community started thehaystacker /Users/thehaystacker/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist
redis stopped
Then you can restart mongodb by first stopping and restart:
brew services stop mongodb
brew services start mongodb
Yes, with features of C99 you may do this. This works without defining new data structures or so and without the function having to decide at runtime how it was called, and without any computational overhead.
For a detailed explanation see my post at
http://gustedt.wordpress.com/2010/06/03/default-arguments-for-c99/
Jens
The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.
According to this Google blogpost:
It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.
When referencing the mipmap- folders ensure you are using the following reference:
android:icon="@mipmap/ic_launcher"
The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.
tooltips can be used as alerts. These can be timed to appear and disappear.
CSS can be used to create tooltips and menus. More info on this can be found in 'Javascript for Dummies'. Sorry about the label of this book... Not infuring anything.
Reading other peoples answers here, I realized the answer to my own thoughts/questions. SetTimeOut could be applied to tooltips. Javascript could trigger them.
Here you go.
SELECT
[so].[name] AS [trigger_name],
USER_NAME([so].[uid]) AS [trigger_owner],
USER_NAME([so2].[uid]) AS [table_schema],
OBJECT_NAME([so].[parent_obj]) AS [table_name],
OBJECTPROPERTY( [so].[id], 'ExecIsUpdateTrigger') AS [isupdate],
OBJECTPROPERTY( [so].[id], 'ExecIsDeleteTrigger') AS [isdelete],
OBJECTPROPERTY( [so].[id], 'ExecIsInsertTrigger') AS [isinsert],
OBJECTPROPERTY( [so].[id], 'ExecIsAfterTrigger') AS [isafter],
OBJECTPROPERTY( [so].[id], 'ExecIsInsteadOfTrigger') AS [isinsteadof],
OBJECTPROPERTY([so].[id], 'ExecIsTriggerDisabled') AS [disabled]
FROM sysobjects AS [so]
INNER JOIN sysobjects AS so2 ON so.parent_obj = so2.Id
WHERE [so].[type] = 'TR'
A couple of things here...
Also I see that you were attempting to pull the parent tables schema information, I believe in order to do so you would also need to join the sysobjects table on itself so that you can correctly get the schema information for the parent table. the query above does this. Also the sysusers table wasn't needed in the results so that Join has been removed.
tested with SQL 2000, SQL 2005, and SQL 2008 R2
I such cases I usually end up with a list of predicates and actions. Something along these lines:
class Mine {
static List<Func<object, bool>> predicates;
static List<Action<object>> actions;
static Mine() {
AddAction<A>(o => o.Hop());
AddAction<B>(o => o.Skip());
}
static void AddAction<T>(Action<T> action) {
predicates.Add(o => o is T);
actions.Add(o => action((T)o);
}
static void RunAction(object o) {
for (int i=0; o < predicates.Count; i++) {
if (predicates[i](o)) {
actions[i](o);
break;
}
}
}
void Foo(object o) {
RunAction(o);
}
}
You are not supposed to assign it to any variable, when you append something in the list, it updates automatically. use only:-
last_list.append(p.last)
if you assign this to a variable "last_list" again, it will no more be a list (will become a none type variable since you haven't declared the type for that) and append will become invalid in the next run.
That will only work if register_globals
is on, and it should never be on (unless of course you are defining that variable somewhere else).
Try setting the form
's action
attribute to ?
...
<form method="post" action="?">
...
</form>
You can also set it to be blank (""
), but older WebKit versions had a bug.
At the beginning with the usepackage
definitions include:
\usepackage{placeins}
And before and after add:
\FloatBarrier
\begin{table}[h]
\begin{tabular}{llll}
....
\end{tabular}
\end{table}
\FloatBarrier
This places the table exactly where you want in the text.
Passing the :value
option to f.label
will ensure the label tag's for
attribute is the same as the id of the corresponding radio_button
<% form_for(@message) do |f| %>
<%= f.radio_button :contactmethod, 'email' %>
<%= f.label :contactmethod, 'Email', :value => 'email' %>
<%= f.radio_button :contactmethod, 'sms' %>
<%= f.label :contactmethod, 'SMS', :value => 'sms' %>
<% end %>
See ActionView::Helpers::FormHelper#label
the :value option, which is designed to target labels for radio_button tags
You can use an array and unpack it inside the select:
cols = ['_2','_4','_5']
df.select(*cols).show()
I have made a variant solution based on paxdiablo's post
Place the following code in Waitlink.cmd
@setlocal enableextensions enabledelayedexpansion
@echo off
set ipaddr=%1
:loop
set state=up
ping -n 1 !ipaddr! >nul: 2>nul:
if not !errorlevel!==0 set state=down
echo.Link is !state!
if "!state!"=="up" (
goto :endloop
)
ping -n 6 127.0.0.1 >nul: 2>nul:
goto :loop
:endloop
endlocal
For example use it from another batch file like this
call Waitlink someurl.com
net use o: \\someurl.com\myshare
The call to waitlink will only return when a ping was succesful. Thanks to paxdiablo and Gabe. Hope this helps someone else.
Hmmm, perhaps another option would be to use something like sshfs (there an sshfs for Mac too). Once your router is mounted you can just copy the files outright. I'm not sure if that works for your particular application but it's a nice solution to keep handy.
def formatE_decimal(x, prec=2):
""" Examples:
>>> formatE_decimal('0.1613965',10)
'1.6139650000E-01'
>>> formatE_decimal('0.1613965',5)
'1.61397E-01'
>>> formatE_decimal('0.9995',2)
'1.00E+00'
"""
xx=decimal.Decimal(x) if type(x)==type("") else x
tup = xx.as_tuple()
xx=xx.quantize( decimal.Decimal("1E{0}".format(len(tup[1])+tup[2]-prec-1)), decimal.ROUND_HALF_UP )
tup = xx.as_tuple()
exp = xx.adjusted()
sign = '-' if tup.sign else ''
dec = ''.join(str(i) for i in tup[1][1:prec+1])
if prec>0:
return '{sign}{int}.{dec}E{exp:+03d}'.format(sign=sign, int=tup[1][0], dec=dec, exp=exp)
elif prec==0:
return '{sign}{int}E{exp:+03d}'.format(sign=sign, int=tup[1][0], exp=exp)
else:
return None
You can also use the following syntax for the strongly typed version:
<% using (Html.BeginForm<SomeController>(x=> x.SomeAction(),
FormMethod.Post,
new { enctype = "multipart/form-data" }))
{ %>
make sure the name of the folder that contains the font name is "fonts" not "font"
I did not find the answer to my question after searching Google & stackoverflow for a while so I would like to share my solution here.
git config --global credential.helper "/bin/bash /git_creds.sh"
echo '#!/bin/bash' > /git_creds.sh
echo "sleep 1" >> /git_creds.sh
echo "echo username=$SERVICE_USER" >> /git_creds.sh
echo "echo password=$SERVICE_PASS" >> /git_creds.sh
# to test it
git clone https://my-scm-provider.com/project.git
I did it for Windows too. Full answer here
In command line, you can use
spark-shell -i file.scala
to run code which is written in file.scala
You can do :
System.out.println(nir[0].length);
But be aware that there's no real two-dimensional array in Java. Each "first level" array contains another array. Each of these arrays can be of different sizes. nir[0].length
isn't necessarily the same size as nir[1].length
.
In modern browsers you can use :placeholder-shown
to target the empty input (not to be confused with ::placeholder
).
input:placeholder-shown {
border: 1px solid red; /* Red border only if the input is empty */
}
More info and browser support: https://css-tricks.com/almanac/selectors/p/placeholder-shown/
I think this may be another way
var width= $('#elm').width();
$('#element').css({ 'width': 'calc(100% - ' + width+ 'px)' });
While the above solutions do work, there is a very simple solution shall we say in "layman's" terms. Someone still learning python and string's can use the other answers but they don't really understand how they work or what each part of the code is doing without a full explanation by the poster as opposed to "this works". The following executes the swapping of every second character in a string and is easy for beginners to understand how it works.
It is simply iterating through the string (any length) by two's (starting from 0 and finding every second character) and then creating a new string (swapped_pair) by adding the current index + 1 (second character) and then the actual index (first character), e.g., index 1 is put at index 0 and then index 0 is put at index 1 and this repeats through iteration of string.
Also added code to ensure string is of even length as it only works for even length.
DrSanjay Bhakkad post above is also a good one that works for even or odd strings and is basically doing the same function as below.
string = "abcdefghijklmnopqrstuvwxyz123"
# use this prior to below iteration if string needs to be even but is possibly odd
if len(string) % 2 != 0:
string = string[:-1]
# iteration to swap every second character in string
swapped_pair = ""
for i in range(0, len(string), 2):
swapped_pair += (string[i + 1] + string[i])
# use this after above iteration for any even or odd length of strings
if len(swapped_pair) % 2 != 0:
swapped_adj += swapped_pair[-1]
print(swapped_pair)
badcfehgjilknmporqtsvuxwzy21 # output if the "needs to be even" code used
badcfehgjilknmporqtsvuxwzy213 # output if the "even or odd" code used
EDIT: While this is currently accepted answer, readers might find this other answer by user John Hart more adapted to their needs. It uses an option which, according to user Ken, was introduced in version 7.21.3 (which was released in December 2010, i.e. after this initial answer).
In your edited question, you're using the URL as the host name, whereas it needs to be the host name only.
Try:
curl -H 'Host: project1.loc' http://127.0.0.1/something
where project1.loc
is just the host name and 127.0.0.1
is the target IP address.
(If you're using curl from a library and not on the command line, make sure you don't put http://
in the Host
header.)
Have the element display as a block:
display: block;
I had the same problem with Ubuntu 17, Ispconfig
was not processing the operations queued of any kind and also the server.sh
command was not working.
I checked and the running PHP version after the OS upgrade was 7.1 so the solution was to type:
apt-get install php7.1-mbstring
and now is everything ok
This is old thread but answer because if useful to anyone.
Step 1. Your Db Storage Engine set to InnoDB
Step 2. Create Primary Table
here customer
is primary table and customer_id
is primary key
Step 3. create foreign key table and give index
here we have customer_addresses
as related table and store customer addresses, so here customer_id
relation with customer
table
we can select index directly when create table as below
If you forgot to give index when create a table, then you can give index from the structure tab of table as below.
Step 4. Once index give to the field, Go to structure tab and click on Relation View as shown in below pic
Step 5. Now select the ON DELETE and ON UPDATE what you want to do, Select column from current table, select DB (SAME DB), select relation table and primary key from that table as shown in below pic and Save it
Now check if relation are give successfully, go to foreign table data list and click on foreign key value, you will redirect to primary table record, then relation made successfully.
The reason for your fatal error is DOMDocument does not have a __toString() method and thus can not be echo'ed.
You're probably looking for
echo $dom->saveHTML();
If you are a Windows user and you are using conda to manage the environment in Anaconda prompt, you can do the following:
Make sure you deactivate the virtual environment or restart Anaconda Prompt. Use the following command to remove virtual environment:
$ conda env remove --name $MyEnvironmentName
Alternatively, you can go to the
C:\Users\USERNAME\AppData\Local\Continuum\anaconda3\envs\MYENVIRONMENTNAME
(that's the default file path) and delete the folder manually.
$('#mySelect').on('change', function() {_x000D_
var value = $(this).val();_x000D_
alert(value);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>_x000D_
<select id="mySelect">_x000D_
<option value='1'>1</option>_x000D_
<option value='2'>2</option>_x000D_
<option value='3'>3</option>_x000D_
<option value='4'>4</option>_x000D_
<option value='5'>5</option>_x000D_
<option value='6'>6</option>_x000D_
<option value='7'>7</option>_x000D_
<option value='8'>8</option>_x000D_
</select>
_x000D_
you can use arraylist object from collections class
using System.Collections;
static void Main()
{
ArrayList arr = new ArrayList();
}
when you want to add elements you can use
arr.Add();
When calling just git tag <TAGNAME>
without any additional parameters, Git will create a new tag from your current HEAD (i.e. the HEAD of your current branch). When adding additional commits into this branch, the branch HEAD will keep up with those new commits, while the tag always refers to the same commit.
When calling git tag <TAGNAME> <COMMIT>
you can even specify which commit to use for creating the tag.
Regardless, a tag is still simply a "pointer" to a certain commit (not a branch).
Dictionaries in python have no order. You could use a list of tuples as your data structure instead.
d = { 'a': 10, 'b': 20, 'c': 30}
newd = [('a',10), ('b',20), ('c',30)]
Then this code could be used to find the locations of keys with a specific value
locations = [i for i, t in enumerate(newd) if t[0]=='b']
>>> [1]
This could be done using List::Util's first
function:
use List::Util qw/first/;
my @array = qw/foo bar baz/;
print first { $_ eq 'bar' } @array;
Other functions from List::Util
like max
, min
, sum
also may be useful for you
Here is a link that has a performance test you can run. find()
is actually about 2 times faster than children()
.
You will have to access db through the ip of host machine, or if you want to access it via localhost:1521, then run webserver like -
docker run --net=host --name oracle-wls wls-image:latest
There is no 'DROP TABLE IF EXISTS' in oracle, you would have to do the select statement.
try this (i'm not up on oracle syntax, so if my variables are ify, please forgive me):
declare @count int
select @count=count(*) from all_tables where table_name='Table_name';
if @count>0
BEGIN
DROP TABLE tableName;
END
As an addition to mklement0's excellent answer:
Almost all executables accept \"
as an escaped "
. Safe usage in cmd however is almost only possible using DELAYEDEXPANSION.
To explicitely send a literal "
to some process, assign \"
to an environment variable, and then use that variable, whenever you need to pass a quote. Example:
SETLOCAL ENABLEDELAYEDEXPANSION
set q=\"
child "malicious argument!q!&whoami"
Note SETLOCAL ENABLEDELAYEDEXPANSION
seems to work only within batch files. To get DELAYEDEXPANSION in an interactive session, start cmd /V:ON
.
If your batchfile does't work with DELAYEDEXPANSION, you can enable it temporarily:
::region without DELAYEDEXPANSION
SETLOCAL ENABLEDELAYEDEXPANSION
::region with DELAYEDEXPANSION
set q=\"
echoarg.exe "ab !q! & echo danger"
ENDLOCAL
::region without DELAYEDEXPANSION
If you want to pass dynamic content from a variable that contains quotes that are escaped as ""
you can replace ""
with \"
on expansion:
SETLOCAL ENABLEDELAYEDEXPANSION
foo.exe "danger & bar=region with !dynamic_content:""=\"! & danger"
ENDLOCAL
This replacement is not safe with %...%
style expansion!
In case of OP bash -c "g++-linux-4.1 !v_params:"=\"!"
is the safe version.
If for some reason even temporarily enabling DELAYEDEXPANSION is not an option, read on:
Using \"
from within cmd is a little bit safer if one always needs to escape special characters, instead of just sometimes. (It's less likely to forget a caret, if it's consistent...)
To achieve this, one precedes any quote with a caret (^"
), quotes that should reach the child process as literals must additionally be escaped with a backlash (\^"
). ALL shell meta characters must be escaped with ^
as well, e.g. &
=> ^&
; |
=> ^|
; >
=> ^>
; etc.
Example:
child ^"malicious argument\^"^&whoami^"
Source: Everyone quotes command line arguments the wrong way, see "A better method of quoting"
To pass dynamic content, one needs to ensure the following:
The part of the command that contains the variable must be considered "quoted" by cmd.exe
(This is impossible if the variable can contain quotes - don't write %var:""=\"%
). To achieve this, the last "
before the variable and the first "
after the variable are not ^
-escaped. cmd-metacharacters between those two "
must not be escaped. Example:
foo.exe ^"danger ^& bar=\"region with %dynamic_content% & danger\"^"
This isn't safe, if %dynamic_content%
can contain unmatched quotes.
I would add that HTMLElement has a built-in .blur
method as well.
Here's a demo using both .focus
and .blur
which work in similar ways.
const input = document.querySelector("#myInput");
_x000D_
<input id="myInput" value="Some Input">_x000D_
_x000D_
<button type="button" onclick="input.focus()">Focus</button>_x000D_
<button type="button" onclick="input.blur()">Lose focus</button>
_x000D_
Bold text:
<Text>
<Text>This is a sentence</Text>
<Text style={{fontWeight: "bold"}}> with</Text>
<Text> one word in bold</Text>
</Text>
Italic text:
<Text>
<Text>This is a sentence</Text>
<Text style={{fontStyle: "italic"}}> with</Text>
<Text> one word in italic</Text>
</Text>
This command may solve the problem :
git add -A
All the files and subdirectories will be added to be tracked.
Hope it helps
If it is a 2 byte string you can do something like in this concrete example where I switch on ISO639-2 language codes.
LANIDX_TYPE LanCodeToIdx(const char* Lan)
{
if(Lan)
switch(Lan[0]) {
case 'A': switch(Lan[1]) {
case 'N': return LANIDX_AN;
case 'R': return LANIDX_AR;
}
break;
case 'B': switch(Lan[1]) {
case 'E': return LANIDX_BE;
case 'G': return LANIDX_BG;
case 'N': return LANIDX_BN;
case 'R': return LANIDX_BR;
case 'S': return LANIDX_BS;
}
break;
case 'C': switch(Lan[1]) {
case 'A': return LANIDX_CA;
case 'C': return LANIDX_CO;
case 'S': return LANIDX_CS;
case 'Y': return LANIDX_CY;
}
break;
case 'D': switch(Lan[1]) {
case 'A': return LANIDX_DA;
case 'E': return LANIDX_DE;
}
break;
case 'E': switch(Lan[1]) {
case 'L': return LANIDX_EL;
case 'N': return LANIDX_EN;
case 'O': return LANIDX_EO;
case 'S': return LANIDX_ES;
case 'T': return LANIDX_ET;
case 'U': return LANIDX_EU;
}
break;
case 'F': switch(Lan[1]) {
case 'A': return LANIDX_FA;
case 'I': return LANIDX_FI;
case 'O': return LANIDX_FO;
case 'R': return LANIDX_FR;
case 'Y': return LANIDX_FY;
}
break;
case 'G': switch(Lan[1]) {
case 'A': return LANIDX_GA;
case 'D': return LANIDX_GD;
case 'L': return LANIDX_GL;
case 'V': return LANIDX_GV;
}
break;
case 'H': switch(Lan[1]) {
case 'E': return LANIDX_HE;
case 'I': return LANIDX_HI;
case 'R': return LANIDX_HR;
case 'U': return LANIDX_HU;
}
break;
case 'I': switch(Lan[1]) {
case 'S': return LANIDX_IS;
case 'T': return LANIDX_IT;
}
break;
case 'J': switch(Lan[1]) {
case 'A': return LANIDX_JA;
}
break;
case 'K': switch(Lan[1]) {
case 'O': return LANIDX_KO;
}
break;
case 'L': switch(Lan[1]) {
case 'A': return LANIDX_LA;
case 'B': return LANIDX_LB;
case 'I': return LANIDX_LI;
case 'T': return LANIDX_LT;
case 'V': return LANIDX_LV;
}
break;
case 'M': switch(Lan[1]) {
case 'K': return LANIDX_MK;
case 'T': return LANIDX_MT;
}
break;
case 'N': switch(Lan[1]) {
case 'L': return LANIDX_NL;
case 'O': return LANIDX_NO;
}
break;
case 'O': switch(Lan[1]) {
case 'C': return LANIDX_OC;
}
break;
case 'P': switch(Lan[1]) {
case 'L': return LANIDX_PL;
case 'T': return LANIDX_PT;
}
break;
case 'R': switch(Lan[1]) {
case 'M': return LANIDX_RM;
case 'O': return LANIDX_RO;
case 'U': return LANIDX_RU;
}
break;
case 'S': switch(Lan[1]) {
case 'C': return LANIDX_SC;
case 'K': return LANIDX_SK;
case 'L': return LANIDX_SL;
case 'Q': return LANIDX_SQ;
case 'R': return LANIDX_SR;
case 'V': return LANIDX_SV;
case 'W': return LANIDX_SW;
}
break;
case 'T': switch(Lan[1]) {
case 'R': return LANIDX_TR;
}
break;
case 'U': switch(Lan[1]) {
case 'K': return LANIDX_UK;
case 'N': return LANIDX_UN;
}
break;
case 'W': switch(Lan[1]) {
case 'A': return LANIDX_WA;
}
break;
case 'Z': switch(Lan[1]) {
case 'H': return LANIDX_ZH;
}
break;
}
return LANIDX_UNDEFINED;
}
LANIDX_* being constant integers used to index in arrays.
To remove ALL spaces:
myString = myString.Replace(" ", "")
To remove leading and trailing spaces:
myString = myString.Trim()
Note: this removes any white space, so newlines, tabs, etc. would be removed.
The above works but this does not. Note the ON DELETE CASCADE
CREATE DATABASE t;
USE t;
CREATE TABLE parent (id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (id INT NULL,
parent_id INT NULL,
FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE
) ENGINE=INNODB;
INSERT INTO child (id, parent_id) VALUES (1, NULL);
-- Query OK, 1 row affected (0.01 sec)
Transforming object to array with plain JavaScript's(ECMAScript-2016
) Object.values
:
var obj = {_x000D_
22: {name:"John", id:22, friends:[5,31,55], works:{books:[], films:[]}},_x000D_
12: {name:"Ivan", id:12, friends:[2,44,12], works:{books:[], films:[]}}_x000D_
}_x000D_
_x000D_
var values = Object.values(obj)_x000D_
_x000D_
console.log(values);
_x000D_
If you also want to keep the keys use Object.entries
and Array#map
like this:
var obj = {_x000D_
22: {name:"John", id:22, friends:[5,31,55], works:{books:[], films:[]}},_x000D_
12: {name:"Ivan", id:12, friends:[2,44,12], works:{books:[], films:[]}}_x000D_
}_x000D_
_x000D_
var values = Object.entries(obj).map(([k, v]) => ({[k]: v}))_x000D_
_x000D_
console.log(values);
_x000D_
This stuff comes from ES file explorer
Just go into this app > settings
Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good
window.location.hash = 'whatever';
Kinda little late but I tried to extend @Tobia's answer to set the layout "horizontal" or "vertical" driven by the command argument e.g.
{"keys": ["f6"], "command": "split_pane", "args": {"split_type": "vertical"} }
Plugin code:
import sublime_plugin
class SplitPaneCommand(sublime_plugin.WindowCommand):
def run(self, split_type):
w = self.window
if w.num_groups() == 1:
if (split_type == "horizontal"):
w.run_command('set_layout', {
'cols': [0.0, 1.0],
'rows': [0.0, 0.33, 1.0],
'cells': [[0, 0, 1, 1], [0, 1, 1, 2]]
})
elif (split_type == "vertical"):
w.run_command('set_layout', {
"cols": [0.0, 0.46, 1.0],
"rows": [0.0, 1.0],
"cells": [[0, 0, 1, 1], [1, 0, 2, 1]]
})
w.focus_group(0)
w.run_command('clone_file')
w.run_command('move_to_group', {'group': 1})
w.focus_group(1)
else:
w.focus_group(1)
w.run_command('close')
w.run_command('set_layout', {
'cols': [0.0, 1.0],
'rows': [0.0, 1.0],
'cells': [[0, 0, 1, 1]]
})
You can disable need to run Internet Explorer's first launch configuration by running this PowerShell script, it will adjust corresponding registry property:
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Internet Explorer\Main" -Name "DisableFirstRunCustomize" -Value 2
After this, WebClient will work without problems
Having reviewed a few different large scale React/Redux projects in my experience Sagas provide developers a more structured way of writing code that is much easier to test and harder to get wrong.
Yes it is a little wierd to start with, but most devs get enough of an understanding of it in a day. I always tell people to not worry about what yield
does to start with and that once you write a couple of test it will come to you.
I have seen a couple of projects where thunks have been treated as if they are controllers from the MVC patten and this quickly becomes an unmaintable mess.
My advice is to use Sagas where you need A triggers B type stuff relating to a single event. For anything that could cut across a number of actions, I find it is simpler to write customer middleware and use the meta property of an FSA action to trigger it.
This solved my problem. You should select Properties, Right-Click, Source Control and Get Specific Version.
A fast approach is to use the following according to ie that you want to focus (check the comments), inside your css files (where margin-top, set whatever css attribute you like):
margin-top: 10px\9; /*It will apply to all ie from 8 and below */
*margin-top: 10px; /*It will apply to ie 7 and below */
_margin-top: 10px; /*It will apply to ie 6 and below*/
A better approach would be to check user agent or a conditional if, in order to avoid the loading of unnecessary CSS in other browsers.
Here is another solution:
for(String serverId : serverIds) {
sb.append(",");
sb.append(serverId);
}
String resultingString = "";
if ( sb.length() > 1 ) {
resultingString = sb.substring(1);
}
Please note that using StringFormat in Bindings only seems to work for "text" properties. Using this for Label.Content will not work
If you're using C# 7, you can use a handy wrapper method like this...
public static class TaskEx
{
public static async Task<(T1, T2)> WhenAll<T1, T2>(Task<T1> task1, Task<T2> task2)
{
return (await task1, await task2);
}
}
...to enable convenient syntax like this when you want to wait on multiple tasks with different return types. You'd have to make multiple overloads for different numbers of tasks to await, of course.
var (someInt, someString) = await TaskEx.WhenAll(GetIntAsync(), GetStringAsync());
However, see Marc Gravell's answer for some optimizations around ValueTask and already-completed tasks if you intend to turn this example into something real.
To test the primality of a number, n, one would expect a loop such as following in the first place :
bool isPrime = true;
for(int i = 2; i < n; i++){
if(n%i == 0){
isPrime = false;
break;
}
}
What the above loop does is this : for a given 1 < i < n, it checks if n/i is an integer (leaves remainder 0). If there exists an i for which n/i is an integer, then we can be sure that n is not a prime number, at which point the loop terminates. If for no i, n/i is an integer, then n is prime.
As with every algorithm, we ask : Can we do better ?
Let us see what is going on in the above loop.
The sequence of i goes : i = 2, 3, 4, ... , n-1
And the sequence of integer-checks goes : j = n/i, which is n/2, n/3, n/4, ... , n/(n-1)
If for some i = a, n/a is an integer, then n/a = k (integer)
or n = ak, clearly n > k > 1 (if k = 1, then a = n, but i never reaches n; and if k = n, then a = 1, but i starts form 2)
Also, n/k = a, and as stated above, a is a value of i so n > a > 1.
So, a and k are both integers between 1 and n (exclusive). Since, i reaches every integer in that range, at some iteration i = a, and at some other iteration i = k. If the primality test of n fails for min(a,k), it will also fail for max(a,k). So we need to check only one of these two cases, unless min(a,k) = max(a,k) (where two checks reduce to one) i.e., a = k , at which point a*a = n, which implies a = sqrt(n).
In other words, if the primality test of n were to fail for some i >= sqrt(n) (i.e., max(a,k)), then it would also fail for some i <= n (i.e., min(a,k)). So, it would suffice if we run the test for i = 2 to sqrt(n).
Follow these steps to run your application on the device connected.
1. Change directories to the root of your Android project and execute:
ant debug
2. Make sure the Android SDK platform-tools/
directory is included in your PATH
environment variable, then execute: adb install bin/<*your app name*>-debug.apk
On your device, locate <*your app name*>
and open it.
Refer Running App
Found a possible workaround that I don't believe was mentioned.
Here is a good description of the problem: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
Basically as long as you use forms/url-encoded/plain text content types you are fine.
$.ajax({
type: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'text/plain'
},
dataType: "json",
url: "http://localhost/endpoint",
data: JSON.stringify({'DataToPost': 123}),
success: function (data) {
alert(JSON.stringify(data));
}
});
I use it with ASP.NET WebAPI2. So on the other end:
public static void RegisterWebApi(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
}
This way Json formatter gets used when parsing plain text content type.
And don't forget in Web.config:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST" />
</customHeaders>
</httpProtocol>
Hope this helps.
Just give you some idea how other databases solve this problem. DolphinDB
also has built-in support for pivoting and the sql looks much more intuitive and neat. It is as simple as specifying the key column (Store
), pivoting column (Week
), and the calculated metric (sum(xCount)
).
//prepare a 10-million-row table
n=10000000
t=table(rand(100, n) + 1 as Store, rand(54, n) + 1 as Week, rand(100, n) + 1 as xCount)
//use pivot clause to generate a pivoted table pivot_t
pivot_t = select sum(xCount) from t pivot by Store, Week
DolphinDB is a columnar high performance database. The calculation in the demo costs as low as 546 ms on a dell xps laptop (i7 cpu). To get more details, please refer to online DolphinDB manual https://www.dolphindb.com/help/index.html?pivotby.html
Google recently changed the terms of use of its Google Maps APIs; if you were already using them on a website (different from localhost) prior to June 22nd, 2016, nothing will change for you; otherwise, you will get the aforementioned issue and need an API key in order to fix your error. The free API key is valid up to 25,000 map loads per day.
In this article you will find everything you may need to know regarding the topic, including a tutorial to fix your error:
Google Maps API error: MissingKeyMapError [SOLVED]
Also, remember to replace YOUR_API_KEY with your actual API key!
Use replace
method of strings not strip
:
s = s.replace(',','')
An example:
>>> s = 'Foo, bar'
>>> s.replace(',',' ')
'Foo bar'
>>> s.replace(',','')
'Foo bar'
>>> s.strip(',') # clears the ','s at the start and end of the string which there are none
'Foo, bar'
>>> s.strip(',') == s
True
Answering the 2012 refreshed (by the second bounty) question, and reviewing the today's results (other answers).
About SOAP 1.2, advantages and drawbacks when comparing with "REST"... Well, since 2007 you can describe REST Web services with WSDL, and using SOAP protocol... That is, if you work a little harder, all W3C standards of the web services protocol stack can be REST!
It is a good starting point, because we can imagine a scenario in which all the philosophical and methodological discussions are temporarily avoided. We can compare technically "SOAP-REST" with "NON-SOAP-REST" in similar services,
SOAP-REST (="REST-SOAP"): as showed by L.Mandel, WSDL2 can describe a REST webservice, and, if we suppose that exemplified XML can be enveloped in SOAP, all the implementation will be "SOAP-REST".
NON-SOAP-REST: any REST web service that can not be SOAP... That is, "90%" of the well-knowed REST examples. Some not use XML (ex. typical AJAX RESTs use JSON instead), some use another XML strucutures, without the SOAP headers or rules. PS: to avoid informality, we can suppose REST level 2 in the comparisons.
Of course, to compare more conceptually, compare "NON-REST-SOAP" with "NON-SOAP-REST", as different modeling approaches. So, completing this taxonomy of web services:
NON-REST-SOAP: any SOAP web service that can not be REST... That is, "90%" of the well-knowed SOAP examples.
NON-REST-NEITHER-SOAP: yes, the universe of "web services modeling" comprises other things (ex. XML-RPC).
Comparing comparable things: SOAP-REST with NON-SOAP-REST.
Explaining some terms,
Contractual stability: for all kinds of contracts (as "written agreements"),
By the use of standars: all levels of the W3C stack are mutually compliant. REST, by other hand, is not a W3C or ISO standard, and have no normatized details about service's peripherals. So, as I, @DaveWoldrich(20 votes), @cynicalman(5), @Exitos(0) said before, in a context where are NEED FOR STANDARDS, you need SOAP.
By the use of best practices: the "verbose aspect" of the W3C stack implementations, translates relevant human/legal/juridic agreements.
Robustness: the safety of SOAP structure and headers. With metada communication (with the full expressiveness of XML) and verification you have an "insurance policy" against any changes or noise.
SOAP have "transactional reliability (...) deal with communication failures. SOAP has more controls around retry logic and thus can provide more end-to-end reliability and service guarantees", E. Terman.
Sorting pros by popularity,
Better tools (~70 votes): SOAP currently has the advantage of better tools, since 2007 and still 2012, because it is a well-defined and widely accepted standard. See @MarkCidade(27 votes), @DaveWoldrich(20), @JoshM(13), @TravisHeseman(9).
Standars compliance (25 votes): as I, @DaveWoldrich(20 votes), @cynicalman(5), @Exitos(0) said before, in a context where are NEED FOR STANDARDS, you need SOAP.
Robustness: insurance of SOAP headers, @JohnSaunders (8 votes).
SOAP strucuture is more complex (more than 300 votes): all answers here, and sources about "SOAP vs REST", manifest some degree of dislike with SOAP's redundancy and complexity. This is a natural consequence of the requirements for formal verification (see below), and for robustness (see above). "REST NON-SOAP" (and XML-RPC, the SOAP originator) can be more simple and informal.
The "only XML" restriction is a performance obstacle when using tiny services (~50 votes): see json.org/xml and this question, or this other one. This point is showed by @toluju(41), and others.
PS: as JSON is not a IETF standard, but we can consider a de facto standard for web software community.
Now, we can add SOAP-NON-REST with NON-SOAP-REST comparisons, and explain when is better to use SOAP:
Need for standards and stable contracts (see "PROS" section). PS: see a typical "B2B need for standards" described by @saille.
Need for tools (see "PROS" section). PS: standards, and the existence of formal verifications (see bellow), are important issues for the tools automation.
Parallel heavy processing (see "Context/Foundations" section below): with bigger and/or slower processes, no matter with a bit more complexity of SOAP, reliability and stability are the best investments.
Need more security: when more than HTTPS is required, and you really need additional features for protection, SOAP is a better choice (see @Bell, 32 votes). "Sending the message along a path more complicated than request/response or over a transport that does not involve HTTP", S. Seely. XML is a core issue, offering standards for XML Encryption, XML Signature, and XML Canonicalization, and, only with SOAP you can to embed these mechanisms into a message by a well-accepted standard as WS-Security.
Need more flexibility (less restrictions): SOAP not need exact correspondence with an URI; not nedd restrict to HTTP; not need to restrict to 4 verbs. As @TravisHeseman (9 votes) says, if you wanted something "flexible for an arbitrary number of client technologies and uses", use SOAP.
PS: remember that XML is more universal/expressive than JSON (et al).
Need for formal verifications: important to understand that W3C stack uses formal methods, and REST is more informal. Your WSDL (a formal language) service description is a formal specification of your web services interfaces, and SOAP is a robust protocol that accept all possible WSDL prescriptions.
To assess trends is necessary historical perspective. For this subject, a 10 or 15 years perspective...
Before the W3C standardization, there are some anarchy. Was difficult to implement interoperable services with different frameworks, and more difficult, costly, and time consuming to implement something interoperable between companys. The W3C stack standards has been a light, a north for interoperation of sets of complex web services.
For day-by-day tasks, like to implement AJAX, SOAP is heavy... So, the need for simple approaches need to elect a new theory-framework... And big "Web software players", as Google, Amazon, Yahoo, et al, elected the best alternative, that is the REST approach. Was in this context that REST concept arrived as a "competing framework", and, today (2012's), this alternative is a de facto standard for programmers.
In a context of Parallel Computing the web services provides parallel subtasks; and protocols, like SOAP, ensures good synchronization and communication. Not "any task": web services can be classified as
coarse-grained and embarrassing parallelism.
As the task gets bigger, it becomes less significant "complexity debate", and becomes more relevant the robustness of the communication and the solidity of the contracts.
Use the :w
command with a filename:
:w other_filename
I copy the file "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5.1\Facades\system.runtime.dll" to bin folder of production server, this solve the problem.
Though I am late to answer this, a better approach to get distinct records using Eloquent would be
$user_names = User::distinct()->get(['name']);
This is a tricky but super simple solution which works in many situations:
import os
os.system('sample_cmd > tmp')
print open('tmp', 'r').read()
A temporary file(here is tmp) is created with the output of the command and you can read from it your desired output.
Extra note from the comments: You can remove the tmp file in the case of one-time job. If you need to do this several times, there is no need to delete the tmp.
os.remove('tmp')
SELECT NAME FROM v$database;
shows the database name in oracle
Try this:
import time
t_end = time.time() + 60 * 15
while time.time() < t_end:
# do whatever you do
This will run for 15 min x 60 s = 900 seconds.
Function time.time
returns the current time in seconds since 1st Jan 1970. The value is in floating point, so you can even use it with sub-second precision. In the beginning the value t_end is calculated to be "now" + 15 minutes. The loop will run until the current time exceeds this preset ending time.
This might be overkill for most people, that's why I hadn't posted it when I implemented it. But it's very robust and flexible.
It stores a Queue with the last frame times, so it can accurately calculate an average FPS value much better than just taking the last frame into consideration.
It also allows you to ignore one frame, if you are doing something that you know is going to artificially screw up that frame's time.
It also allows you to change the number of frames to store in the Queue as it runs, so you can test it out on the fly what is the best value for you.
// Number of past frames to use for FPS smooth calculation - because
// Unity's smoothedDeltaTime, well - it kinda sucks
private int frameTimesSize = 60;
// A Queue is the perfect data structure for the smoothed FPS task;
// new values in, old values out
private Queue<float> frameTimes;
// Not really needed, but used for faster updating then processing
// the entire queue every frame
private float __frameTimesSum = 0;
// Flag to ignore the next frame when performing a heavy one-time operation
// (like changing resolution)
private bool _fpsIgnoreNextFrame = false;
//=============================================================================
// Call this after doing a heavy operation that will screw up with FPS calculation
void FPSIgnoreNextFrame() {
this._fpsIgnoreNextFrame = true;
}
//=============================================================================
// Smoothed FPS counter updating
void Update()
{
if (this._fpsIgnoreNextFrame) {
this._fpsIgnoreNextFrame = false;
return;
}
// While looping here allows the frameTimesSize member to be changed dinamically
while (this.frameTimes.Count >= this.frameTimesSize) {
this.__frameTimesSum -= this.frameTimes.Dequeue();
}
while (this.frameTimes.Count < this.frameTimesSize) {
this.__frameTimesSum += Time.deltaTime;
this.frameTimes.Enqueue(Time.deltaTime);
}
}
//=============================================================================
// Public function to get smoothed FPS values
public int GetSmoothedFPS() {
return (int)(this.frameTimesSize / this.__frameTimesSum * Time.timeScale);
}
Maybe you want more simple and short approach. This will clear all TextBoxes too. (Except TextBoxes inside Panel or GroupBox).
foreach (TextBox textBox in Controls.OfType<TextBox>())
textBox.Text = "";
The user's input will always be given to you in the form of a string of characters... if you want to convert the user's input from a string to an integer, you'll need to supply the code to do that. If the user types in a number (e.g. "1"), you can pass the string to atoi() to get the integer corresponding to the string. If the user types in an english string (e.g. "EASY") then you'll need to check for that string (e.g. with strcmp()) and assign the appropriate integer value to your variable based on which check matches. Once you have an integer value that was derived from the user's input string, you can pass it into the switch() statement as usual.
This simply means that either tree
, tree[otu]
, or tree[otu][0]
evaluates to None
, and as such is not subscriptable. Most likely tree[otu]
or tree[otu][0]
. Track it down with some simple debugging like this:
def Ancestors (otu,tree):
try:
tree[otu][0][0]
except TypeError:
print otu, tre[otu]
raise
#etc...
or pdb
I agree with Bryan's answer
if I do
cell.isUserInteractionEnabled = false
then the subviews within the cell won't be user interacted.
On the other site, setting
cell.selectionStyle = .none
will trigger the didSelect method despite not updating the selection color.
Using willSelectRowAt is the way I solved my problem. Example:
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if indexPath.section == 0{
if indexPath.row == 0{
return nil
}
}
else if indexPath.section == 1{
if indexPath.row == 0{
return nil
}
}
return indexPath
}
If you want total minutes between two dates in day wise than may below code will help full to you Start Date : 2018-05-04 02:08:05 , End Date : 2018-05-14 09:04:07...
function countDaysAndTimes(startDate,endDate){
return new Promise(function (resolve, reject) {
var dayObj = new Object;
var finalArray = new Array;
var datetime1 = moment(startDate);
var datetime2 = moment(endDate);
if(datetime1.format('D') != datetime2.format('D') || datetime1.format('M') != datetime2.format('M') || datetime1.format('YYYY') != datetime2.format('YYYY')){
var onlyDate1 = startDate.split(" ");
var onlyDate2 = endDate.split(" ");
var totalDays = moment(onlyDate2[0]).diff(moment(onlyDate1[0]), 'days')
// First Day Entry
dayObj.startDate = startDate;
dayObj.endDate = moment(onlyDate1[0]).add(1, 'day').format('YYYY-MM-DD')+" 00:00:00";
dayObj.minutes = moment(dayObj.endDate).diff(moment(dayObj.startDate), 'minutes');
finalArray.push(dayObj);
// Between Days Entry
var i = 1;
if(totalDays > 1){
for(i=1; i<totalDays; i++){
var dayObj1 = new Object;
dayObj1.startDate = moment(onlyDate1[0]).add(i, 'day').format('YYYY-MM-DD')+" 00:00:00";
dayObj1.endDate = moment(onlyDate1[0]).add(i+1, 'day').format('YYYY-MM-DD')+" 00:00:00";
dayObj1.minutes = moment(dayObj1.endDate).diff(moment(dayObj1.startDate), 'minutes');
finalArray.push(dayObj1);
}
}
// Last Day Entry
var dayObj2 = new Object;
dayObj2.startDate = moment(onlyDate1[0]).add(i, 'day').format('YYYY-MM-DD')+" 00:00:00";
dayObj2.endDate = endDate ;
dayObj2.minutes = moment(dayObj2.endDate).diff(moment(dayObj2.startDate), 'minutes');
finalArray.push(dayObj2);
}
else{
dayObj.startDate = startDate;
dayObj.endDate = endDate;
dayObj.minutes = datetime2.diff(datetime1, 'minutes');
finalArray.push(dayObj);
}
console.log(JSON.stringify(finalArray));
// console.table(finalArray);
resolve(finalArray);
});
}
Output
[
{
"startDate":"2018-05-04 02:08:05",
"endDate":"2018-05-05 00:00:00",
"minutes":1311
},
{
"startDate":"2018-05-05 00:00:00",
"endDate":"2018-05-06 00:00:00",
"minutes":1440
},
{
"startDate":"2018-05-06 00:00:00",
"endDate":"2018-05-07 00:00:00",
"minutes":1440
},
{
"startDate":"2018-05-07 00:00:00",
"endDate":"2018-05-08 00:00:00",
"minutes":1440
},
{
"startDate":"2018-05-08 00:00:00",
"endDate":"2018-05-09 00:00:00",
"minutes":1440
},
{
"startDate":"2018-05-09 00:00:00",
"endDate":"2018-05-10 00:00:00",
"minutes":1440
},
{
"startDate":"2018-05-10 00:00:00",
"endDate":"2018-05-11 00:00:00",
"minutes":1440
},
{
"startDate":"2018-05-11 00:00:00",
"endDate":"2018-05-12 00:00:00",
"minutes":1440
},
{
"startDate":"2018-05-12 00:00:00",
"endDate":"2018-05-13 00:00:00",
"minutes":1440
},
{
"startDate":"2018-05-13 00:00:00",
"endDate":"2018-05-14 00:00:00",
"minutes":1440
},
{
"startDate":"2018-05-14 00:00:00",
"endDate":"2018-05-14 09:04:07",
"minutes":544
}
]
Yo could also set labels = FALSE
inside axis(...)
and print the labels in a separate command with Text. With this option you can rotate the text the text in case you need it
lablist<-as.vector(c(1:10))
axis(1, at=seq(1, 10, by=1), labels = FALSE)
text(seq(1, 10, by=1), par("usr")[3] - 0.2, labels = lablist, srt = 45, pos = 1, xpd = TRUE)
Detailed explanation here
I had the same issue and it fixed by the following steps - reference: http://giladka8.blogspot.com.au/2011/11/database-is-in-single-user-mode-and.html
use master
GO
select
d.name,
d.dbid,
spid,
login_time,
nt_domain,
nt_username,
loginame
from sysprocesses p
inner join sysdatabases d
on p.dbid = d.dbid
where d.name = 'dbname'
GO
kill 56 --=> kill the number in spid field
GO
exec sp_dboption 'dbname', 'single user', 'FALSE'
GO
You can make use of location service available in @angular/common and via this below code you can get the location or current URL
import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';
@Component({
selector: 'app-top-nav',
templateUrl: './top-nav.component.html',
styleUrls: ['./top-nav.component.scss']
})
export class TopNavComponent implements OnInit {
route: string;
constructor(location: Location, router: Router) {
router.events.subscribe((val) => {
if(location.path() != ''){
this.route = location.path();
} else {
this.route = 'Home'
}
});
}
ngOnInit() {
}
}
here is the reference link from where I have copied thing to get location for my project. https://github.com/elliotforbes/angular-2-admin/blob/master/src/app/common/top-nav/top-nav.component.ts
Due to low rep can't reply with this to the people asking to run this on multiple databases/SQL Servers.
Create a registered server group and query across them all us the following and just cursor through the databases:
--Make sure all ' are doubled within the SQL string.
DECLARE @dbname VARCHAR(50)
DECLARE @statement NVARCHAR(max)
DECLARE db_cursor CURSOR
LOCAL FAST_FORWARD
FOR
SELECT name
FROM MASTER.dbo.sysdatabases
where name like '%DBName%'
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @dbname
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @statement = 'use '+@dbname +';'+ '
/*
Security Audit Report
1) List all access provisioned to a SQL user or Windows user/group directly
2) List all access provisioned to a SQL user or Windows user/group through a database or application role
3) List all access provisioned to the public role
Columns Returned:
UserType : Value will be either ''SQL User'', ''Windows User'', or ''Windows Group''.
This reflects the type of user/group defined for the SQL Server account.
DatabaseUserName: Name of the associated user as defined in the database user account. The database user may not be the
same as the server user.
LoginName : SQL or Windows/Active Directory user account. This could also be an Active Directory group.
Role : The role name. This will be null if the associated permissions to the object are defined at directly
on the user account, otherwise this will be the name of the role that the user is a member of.
PermissionType : Type of permissions the user/role has on an object. Examples could include CONNECT, EXECUTE, SELECT
DELETE, INSERT, ALTER, CONTROL, TAKE OWNERSHIP, VIEW DEFINITION, etc.
This value may not be populated for all roles. Some built in roles have implicit permission
definitions.
PermissionState : Reflects the state of the permission type, examples could include GRANT, DENY, etc.
This value may not be populated for all roles. Some built in roles have implicit permission
definitions.
ObjectType : Type of object the user/role is assigned permissions on. Examples could include USER_TABLE,
SQL_SCALAR_FUNCTION, SQL_INLINE_TABLE_VALUED_FUNCTION, SQL_STORED_PROCEDURE, VIEW, etc.
This value may not be populated for all roles. Some built in roles have implicit permission
definitions.
Schema : Name of the schema the object is in.
ObjectName : Name of the object that the user/role is assigned permissions on.
This value may not be populated for all roles. Some built in roles have implicit permission
definitions.
ColumnName : Name of the column of the object that the user/role is assigned permissions on. This value
is only populated if the object is a table, view or a table value function.
*/
--1) List all access provisioned to a SQL user or Windows user/group directly
SELECT
[UserType] = CASE princ.[type]
WHEN ''S'' THEN ''SQL User''
WHEN ''U'' THEN ''Windows User''
WHEN ''G'' THEN ''Windows Group''
END,
[DatabaseUserName] = princ.[name],
[LoginName] = ulogin.[name],
[Role] = NULL,
[PermissionType] = perm.[permission_name],
[PermissionState] = perm.[state_desc],
[ObjectType] = CASE perm.[class]
WHEN 1 THEN obj.[type_desc] -- Schema-contained objects
ELSE perm.[class_desc] -- Higher-level objects
END,
[Schema] = objschem.[name],
[ObjectName] = CASE perm.[class]
WHEN 3 THEN permschem.[name] -- Schemas
WHEN 4 THEN imp.[name] -- Impersonations
ELSE OBJECT_NAME(perm.[major_id]) -- General objects
END,
[ColumnName] = col.[name]
FROM
--Database user
sys.database_principals AS princ
--Login accounts
LEFT JOIN sys.server_principals AS ulogin ON ulogin.[sid] = princ.[sid]
--Permissions
LEFT JOIN sys.database_permissions AS perm ON perm.[grantee_principal_id] = princ.[principal_id]
LEFT JOIN sys.schemas AS permschem ON permschem.[schema_id] = perm.[major_id]
LEFT JOIN sys.objects AS obj ON obj.[object_id] = perm.[major_id]
LEFT JOIN sys.schemas AS objschem ON objschem.[schema_id] = obj.[schema_id]
--Table columns
LEFT JOIN sys.columns AS col ON col.[object_id] = perm.[major_id]
AND col.[column_id] = perm.[minor_id]
--Impersonations
LEFT JOIN sys.database_principals AS imp ON imp.[principal_id] = perm.[major_id]
WHERE
princ.[type] IN (''S'',''U'',''G'')
-- No need for these system accounts
AND princ.[name] NOT IN (''sys'', ''INFORMATION_SCHEMA'')
UNION
--2) List all access provisioned to a SQL user or Windows user/group through a database or application role
SELECT
[UserType] = CASE membprinc.[type]
WHEN ''S'' THEN ''SQL User''
WHEN ''U'' THEN ''Windows User''
WHEN ''G'' THEN ''Windows Group''
END,
[DatabaseUserName] = membprinc.[name],
[LoginName] = ulogin.[name],
[Role] = roleprinc.[name],
[PermissionType] = perm.[permission_name],
[PermissionState] = perm.[state_desc],
[ObjectType] = CASE perm.[class]
WHEN 1 THEN obj.[type_desc] -- Schema-contained objects
ELSE perm.[class_desc] -- Higher-level objects
END,
[Schema] = objschem.[name],
[ObjectName] = CASE perm.[class]
WHEN 3 THEN permschem.[name] -- Schemas
WHEN 4 THEN imp.[name] -- Impersonations
ELSE OBJECT_NAME(perm.[major_id]) -- General objects
END,
[ColumnName] = col.[name]
FROM
--Role/member associations
sys.database_role_members AS members
--Roles
JOIN sys.database_principals AS roleprinc ON roleprinc.[principal_id] = members.[role_principal_id]
--Role members (database users)
JOIN sys.database_principals AS membprinc ON membprinc.[principal_id] = members.[member_principal_id]
--Login accounts
LEFT JOIN sys.server_principals AS ulogin ON ulogin.[sid] = membprinc.[sid]
--Permissions
LEFT JOIN sys.database_permissions AS perm ON perm.[grantee_principal_id] = roleprinc.[principal_id]
LEFT JOIN sys.schemas AS permschem ON permschem.[schema_id] = perm.[major_id]
LEFT JOIN sys.objects AS obj ON obj.[object_id] = perm.[major_id]
LEFT JOIN sys.schemas AS objschem ON objschem.[schema_id] = obj.[schema_id]
--Table columns
LEFT JOIN sys.columns AS col ON col.[object_id] = perm.[major_id]
AND col.[column_id] = perm.[minor_id]
--Impersonations
LEFT JOIN sys.database_principals AS imp ON imp.[principal_id] = perm.[major_id]
WHERE
membprinc.[type] IN (''S'',''U'',''G'')
-- No need for these system accounts
AND membprinc.[name] NOT IN (''sys'', ''INFORMATION_SCHEMA'')
UNION
--3) List all access provisioned to the public role, which everyone gets by default
SELECT
[UserType] = ''{All Users}'',
[DatabaseUserName] = ''{All Users}'',
[LoginName] = ''{All Users}'',
[Role] = roleprinc.[name],
[PermissionType] = perm.[permission_name],
[PermissionState] = perm.[state_desc],
[ObjectType] = CASE perm.[class]
WHEN 1 THEN obj.[type_desc] -- Schema-contained objects
ELSE perm.[class_desc] -- Higher-level objects
END,
[Schema] = objschem.[name],
[ObjectName] = CASE perm.[class]
WHEN 3 THEN permschem.[name] -- Schemas
WHEN 4 THEN imp.[name] -- Impersonations
ELSE OBJECT_NAME(perm.[major_id]) -- General objects
END,
[ColumnName] = col.[name]
FROM
--Roles
sys.database_principals AS roleprinc
--Role permissions
LEFT JOIN sys.database_permissions AS perm ON perm.[grantee_principal_id] = roleprinc.[principal_id]
LEFT JOIN sys.schemas AS permschem ON permschem.[schema_id] = perm.[major_id]
--All objects
JOIN sys.objects AS obj ON obj.[object_id] = perm.[major_id]
LEFT JOIN sys.schemas AS objschem ON objschem.[schema_id] = obj.[schema_id]
--Table columns
LEFT JOIN sys.columns AS col ON col.[object_id] = perm.[major_id]
AND col.[column_id] = perm.[minor_id]
--Impersonations
LEFT JOIN sys.database_principals AS imp ON imp.[principal_id] = perm.[major_id]
WHERE
roleprinc.[type] = ''R''
AND roleprinc.[name] = ''public''
AND obj.[is_ms_shipped] = 0
ORDER BY
[UserType],
[DatabaseUserName],
[LoginName],
[Role],
[Schema],
[ObjectName],
[ColumnName],
[PermissionType],
[PermissionState],
[ObjectType]
'
exec sp_executesql @statement
FETCH NEXT FROM db_cursor INTO @dbname
END
CLOSE db_cursor
DEALLOCATE db_cursor
This thread massively helped me thanks everyone!
let text:String = "Hello Friend"
let searchRange:NSRange = NSRange(location:0,length: text.characters.count)
let range:Range`<Int`> = Range`<Int`>.init(start: searchRange.location, end: searchRange.length)
Dim f as Range
Set f=ActiveSheet.Cells.Find(...)
If Not f Is Nothing then
msgbox "Row=" & f.Row & vbcrlf & "Column=" & f.Column
Else
msgbox "value not found!"
End If
1) What is Express.js?
Express.js is a Node.js framework. It's the most popular framework as of now (the most starred on NPM).
.
It's built around configuration and granular simplicity of Connect middleware. Some people compare Express.js to Ruby Sinatra vs. the bulky and opinionated Ruby on Rails.
2) What is the purpose of it with Node.js?
That you don't have to repeat same code over and over again. Node.js is a low-level I/O mechanism which has an HTTP module. If you just use an HTTP module, a lot of work like parsing the payload, cookies, storing sessions (in memory or in Redis), selecting the right route pattern based on regular expressions will have to be re-implemented. With Express.js, it is just there for you to use.
3) Why do we actually need Express.js? How it is useful for us to use with Node.js?
The first answer should answer your question. If no, then try to write a small REST API server in plain Node.js (that is, using only core modules) and then in Express.js. The latter will take you 5-10x less time and lines of code.
What is Redis? Does it come with Express.js?
Redis is a fast persistent key-value storage. You can optionally use it for storing sessions with Express.js, but you don't need to. By default, Express.js has memory storage for sessions. Redis also can be use for queueing jobs, for example, email jobs.
Check out my tutorial on REST API server with Express.js.
MVC but not by itself
Express.js is not an model-view-controller framework by itself. You need to bring your own object-relational mapping libraries such as Mongoose for MongoDB, Sequelize (http://sequelizejs.com) for SQL databases, Waterline (https://github.com/balderdashy/waterline) for many databases into the stack.
Alternatives
Other Node.js frameworks to consider (https://www.quora.com/Node-js/Which-Node-js-framework-is-best-for-building-a-RESTful-API):
UPDATE: I put together this resource that aid people in choosing Node.js frameworks: http://nodeframework.com
UPDATE2: We added some GitHub stats to nodeframework.com so now you can compare the level of social proof (GitHub stars) for 30+ frameworks on one page.
Full-stack:
Just REST API:
Ruby on Rails like:
Sinatra like:
Other:
Middleware:
Static site generators:
I wrote some code to make it easy
//Add custom event listener_x000D_
$(':root').on('mousedown', '*', function() {_x000D_
var el = $(this),_x000D_
events = $._data(this, 'events');_x000D_
if (events && events.clickHold) {_x000D_
el.data(_x000D_
'clickHoldTimer',_x000D_
setTimeout(_x000D_
function() {_x000D_
el.trigger('clickHold')_x000D_
},_x000D_
el.data('clickHoldTimeout')_x000D_
)_x000D_
);_x000D_
}_x000D_
}).on('mouseup mouseleave mousemove', '*', function() {_x000D_
clearTimeout($(this).data('clickHoldTimer'));_x000D_
});_x000D_
_x000D_
//Attach it to the element_x000D_
$('#HoldListener').data('clickHoldTimeout', 2000); //Time to hold_x000D_
$('#HoldListener').on('clickHold', function() {_x000D_
console.log('Worked!');_x000D_
});
_x000D_
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>_x000D_
<img src="http://lorempixel.com/400/200/" id="HoldListener">
_x000D_
Now you need just to set the time of holding and add clickHold
event on your element
From:Source
public String MysqlRealScapeString(String str){
String data = null;
if (str != null && str.length() > 0) {
str = str.replace("\\", "\\\\");
str = str.replace("'", "\\'");
str = str.replace("\0", "\\0");
str = str.replace("\n", "\\n");
str = str.replace("\r", "\\r");
str = str.replace("\"", "\\\"");
str = str.replace("\\x1a", "\\Z");
data = str;
}
return data;
}
Promises have state, they start as pending and can settle to:
Promise returning functions should never throw, they should return rejections instead. Throwing from a promise returning function will force you to use both a } catch {
and a .catch
. People using promisified APIs do not expect promises to throw. If you're not sure how async APIs work in JS - please see this answer first.
So, creating promises generally means specifying when they settle - that means when they move to the fulfilled or rejected phase to indicate the data is available (and can be accessed with .then
).
With modern promise implementations that support the Promise
constructor like native ES6 promises:
function load() {
return new Promise(function(resolve, reject) {
window.onload = resolve;
});
}
You would then use the resulting promise like so:
load().then(function() {
// Do things after onload
});
With libraries that support deferred (Let's use $q for this example here, but we'll also use jQuery later):
function load() {
var d = $q.defer();
window.onload = function() { d.resolve(); };
return d.promise;
}
Or with a jQuery like API, hooking on an event happening once:
function done() {
var d = $.Deferred();
$("#myObject").once("click",function() {
d.resolve();
});
return d.promise();
}
These APIs are rather common since well… callbacks are common in JS. Let's look at the common case of having onSuccess
and onFail
:
function getUserData(userId, onLoad, onFail) { …
With modern promise implementations that support the Promise
constructor like native ES6 promises:
function getUserDataAsync(userId) {
return new Promise(function(resolve, reject) {
getUserData(userId, resolve, reject);
});
}
With libraries that support deferred (Let's use jQuery for this example here, but we've also used $q above):
function getUserDataAsync(userId) {
var d = $.Deferred();
getUserData(userId, function(res){ d.resolve(res); }, function(err){ d.reject(err); });
return d.promise();
}
jQuery also offers a $.Deferred(fn)
form, which has the advantage of allowing us to write an expression that emulates very closely the new Promise(fn)
form, as follows:
function getUserDataAsync(userId) {
return $.Deferred(function(dfrd) {
getUserData(userId, dfrd.resolve, dfrd.reject);
}).promise();
}
Note: Here we exploit the fact that a jQuery deferred's resolve
and reject
methods are "detachable"; ie. they are bound to the instance of a jQuery.Deferred(). Not all libs offer this feature.
Node style callbacks (nodebacks) have a particular format where the callbacks is always the last argument and its first parameter is an error. Let's first promisify one manually:
getStuff("dataParam", function(err, data) { …
To:
function getStuffAsync(param) {
return new Promise(function(resolve, reject) {
getStuff(param, function(err, data) {
if (err !== null) reject(err);
else resolve(data);
});
});
}
With deferreds you can do the following (let's use Q for this example, although Q now supports the new syntax which you should prefer):
function getStuffAsync(param) {
var d = Q.defer();
getStuff(param, function(err, data) {
if (err !== null) d.reject(err);
else d.resolve(data);
});
return d.promise;
}
In general, you should not promisify things manually too much, most promise libraries that were designed with Node in mind as well as native promises in Node 8+ have a built in method for promisifying nodebacks. For example
var getStuffAsync = Promise.promisify(getStuff); // Bluebird
var getStuffAsync = Q.denodeify(getStuff); // Q
var getStuffAsync = util.promisify(getStuff); // Native promises, node only
There is no golden rule here, you promisify them one by one. However, some promise implementations allow you to do this in bulk, for example in Bluebird, converting a nodeback API to a promise API is as simple as:
Promise.promisifyAll(API);
Or with native promises in Node:
const { promisify } = require('util');
const promiseAPI = Object.entries(API).map(([key, v]) => ({key, fn: promisify(v)}))
.reduce((o, p) => Object.assign(o, {[p.key]: p.fn}), {});
Notes:
.then
handler you do not need to promisify things. Returning a promise from a .then
handler will resolve or reject with that promise's value. Throwing from a .then
handler is also good practice and will reject the promise - this is the famous promise throw safety. onload
case, you should use addEventListener
rather than onX
.Take a look at this tutorial, it's for FreeBSD but also applies to OS X. http://people.freebsd.org/~arved/vlan/vlan_en.html
You could use a navigation property if its available. It produces an inner join in the SQL.
from s in db.Services
where s.ServiceAssignment.LocationId == 1
select s
An easier way that works regardless of the OS is to do
git rm -r --cached .
git add .
git commit -m "Drop files from .gitignore"
You basically remove and re-add all files, but git add
will ignore the ones in .gitignore
.
Using the --cached
option will keep files in your filesystem, so you won't be removing files from your disk.
Note:
Some pointed out in the comments that you will lose the history of all your files. I tested this with git 2.27.0 on MacOS and it is not the case. If you want to check what is happening, check your git diff HEAD~1
before you push your commit.
You can actually do this within the query.
$results = Project::orderBy('name')->get();
This will return all results with the proper order.
SQL Server Management Studio provides an Import/Export wizard tool which have an option to automatically create tables.
You can access it by right clicking on the Database in Object Explorer and selecting Tasks->Import Data...
From there wizard should be self-explanatory and easy to navigate. You choose your CSV as source, desired destination, configure columns and run the package.
If you need detailed guidance, there are plenty of guides online, here is a nice one: http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/
You simply need to start mysql
and feed it with the content of db.sql
:
mysql -u user -p < db.sql
Syntax is source <file-name>
ex. source config.sh
script - config.sh
USERNAME="satish"
EMAIL="[email protected]"
calling script -
#!/bin/bash
source config.sh
echo Welcome ${USERNAME}!
echo Your email is ${EMAIL}.
You can learn to include a bash script in another bash script here.
You can Use this for Curl:
function fakeip()
{
return long2ip( mt_rand(0, 65537) * mt_rand(0, 65535) );
}
function getdata($url,$args=false)
{
global $session;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("REMOTE_ADDR: ".fakeip(),"X-Client-IP: ".fakeip(),"Client-IP: ".fakeip(),"HTTP_X_FORWARDED_FOR: ".fakeip(),"X-Forwarded-For: ".fakeip()));
if($args)
{
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$args);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1:8888");
$result = curl_exec ($ch);
curl_close ($ch);
return $result;
}
Then To Read Json:
$result=getdata("https://example.com");
Then :
///Deocde Json
$data = json_decode($result,true);
///Count
$total=count($data);
$Str='<h1>Total : '.$total.'';
echo $Str;
//You Can Also Make In Table:
foreach ($data as $key => $value)
{
echo ' <td><font face="calibri"color="red">'.$value[type].' </font></td><td><font face="calibri"color="blue">'.$value[category].' </font></td><td><font face="calibri"color="green">'.$value[amount].' </font></tr><tr>';
}
echo "</tr></table>";
}
You Can Also Use This:
echo '<p>Name : '.$data['result']['name'].'</p>
<img src="'.$data['result']['pic'].'"><br>';
Hope this helped.
Here is what worked for me (specific to Oracle, but using scalar
seems to be the key)
Long getNext() {
Query query =
session.createSQLQuery("select MYSEQ.nextval as num from dual")
.addScalar("num", StandardBasicTypes.BIG_INTEGER);
return ((BigInteger) query.uniqueResult()).longValue();
}
Thanks to the posters here: springsource_forum
The following example demonstrates how to POST a JSON via WebClient.UploadString Method:
var vm = new { k = "1", a = "2", c = "3", v= "4" };
using (var client = new WebClient())
{
var dataString = JsonConvert.SerializeObject(vm);
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
client.UploadString(new Uri("http://www.contoso.com/1.0/service/action"), "POST", dataString);
}
Prerequisites: Json.NET library
When searching for an answer to the very same question I came across gem_unused.
You also might wanna read this article: http://chill.manilla.com/2012/12/31/clean-up-your-dirty-gemsets/
The source code is available on GitHub: https://github.com/apolzon/gem_unused
If you want to pass a JavaScript object/hash (ie. an associative array in PHP) then you would do:
$.post('/url/to/page', {'key1': 'value', 'key2': 'value'});
If you wanna pass an actual array (ie. an indexed array in PHP) then you can do:
$.post('/url/to/page', {'someKeyName': ['value','value']});
If you want to pass a JavaScript array then you can do:
$.post('/url/to/page', {'someKeyName': variableName});
On Windows and Linux : Ctrl + Shift + F
On Mac : ? + ? + F
(Alternatively you can press Format
in Main Menu > Source)
In the above solution, repeated here:
f = open('file.txt', 'r')
try:
# do stuff with f
finally:
f.close()
if something bad happens (you never know ...) after opening the file successfully and before the try, the file will not be closed, so a safer solution is:
f = None
try:
f = open('file.txt', 'r')
# do stuff with f
finally:
if f is not None:
f.close()
Type mysql --version
to see if it is installed.
To find location use find -name mysql
.
Cast the operands to floats:
float ans = (float)a / (float)b;
If you just want to get the highest salary from that table, by department:
SELECT MAX(Salary) FROM TableName GROUP BY DeptID
With an Android-powered device, you can develop and debug your Android applications just as you would on the emulator.
1. Declare your application as "debuggable" in AndroidManifest.xml
.
<application
android:debuggable="true"
... >
...
</application>
2. On your handset, navigate to Settings > Security and check Unknown sources
3. Go to Settings > Developer Options and check USB debugging
Note that if Developer Options
is invisible you will need to navigate to Settings > About Phone and tap on Build number
several times until you are notified that it has been unlocked.
4. Set up your system to detect your device.
Follow the instructions below for your OS:
Install the Google USB Driver from the ADT SDK Manager
(Support for: ADP1, ADP2, Verizon Droid, Nexus One, Nexus S).
For devices not listed above, install an OEM driver for your device
Your device should automatically work; Go to the next step
Add a udev
rules file that contains a USB configuration for each type of device you want to use for development. In the rules file, each device manufacturer is identified by a unique vendor ID, as specified by the ATTR{idVendor} property. For a list of vendor IDs, click here. To set up device detection on Ubuntu Linux:
/etc/udev/rules.d/51-android.rules
.SUBSYSTEM=="usb", ATTR{idVendor}=="0bb4", MODE="0666", GROUP="plugdev"
chmod a+r /etc/udev/rules.d/51-android.rules
Note: The rule syntax may vary slightly depending on your environment. Consult the udev documentation for your system as needed. For an overview of rule syntax, see this guide to writing udev rules.
5. Run the project with your connected device.
With Eclipse/ADT: run or debug your application as usual. You will be presented with a Device Chooser dialog that lists the available emulator(s) and connected device(s).
With ADB: issue commands with the -d flag to target your connected device.
Still need help? Click here for the full guide.
$('#someid').attr('disabled', 'true');
Properties
.Libraries
.Compile tab
- click Add Jar/Folder
button.Or
Libraries
.Add Jar/Folder
.With pure javascript:
var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (var i = 0; i <= buttonsCount; i += 1) {
buttons[i].onclick = function(e) {
alert(this.id);
};
}?
For Eclipse in Macbook it is just 2 click process:
I know what you're trying to do, but why not simply do this:
$('div').addClass('hover');
The class is already defined in your CSS...
As for you original question, this has been asked before and it is not possible unfortunately. e.g. http://forum.jquery.com/topic/jquery-triggering-css-pseudo-selectors-like-hover
However, your desired functionality may be possible if your Stylesheet is defined in Javascript. see: http://www.4pmp.com/2009/11/dynamic-css-pseudo-class-styles-with-jquery/
Hope this helps!
We can do like below:
const item= {
image: require("../../assets/dashboard/project1.jpeg"),
location: "Chennai",
status: 1,
projectId: 1
}
<Image source={item.image} style={[{ width: 150, height: 150}]} />
Or since Objective C is just C with some OO layer on top you can use the posix conterparts:
int execl(const char *path, const char *arg0, ..., const char *argn, (char *)0);
int execle(const char *path, const char *arg0, ..., const char *argn, (char *)0, char *const envp[]);
int execlp(const char *file, const char *arg0, ..., const char *argn, (char *)0);
int execlpe(const char *file, const char *arg0, ..., const char *argn, (char *)0, char *const envp[]);
int execv(const char *path, char *const argv[]);
int execve(const char *path, char *const argv[], char *const envp[]);
int execvp(const char *file, char *const argv[]);
int execvpe(const char *file, char *const argv[], char *const envp[]);
They are included from unistd.h header file.
If you are using System.Web.Script.Serialization
in the .NET framework you can put a ScriptIgnore
attribute on the members that shouldn't be serialized. See the example taken from here:
Consider the following (simplified) case:
public class User { public int Id { get; set; } public string Name { get; set; } [ScriptIgnore] public bool IsComplete { get { return Id > 0 && !string.IsNullOrEmpty(Name); } } }
In this case, only the Id and the Name properties will be serialized, thus the resulting JSON object would look like this:
{ Id: 3, Name: 'Test User' }
PS. Don't forget to add a reference to "System.Web.Extensions
" for this to work
If you explicitly cast double
to int
, the decimal part will be truncated. For example:
int x = (int) 4.97542; //gives 4 only
int x = (int) 4.23544; //gives 4 only
Moreover, you may also use Math.floor()
method to round values in case you want double
value in return.
You can also use pd.DataFrame.from_dict(d)
as :
In [8]: d = [{'points': 50, 'time': '5:00', 'year': 2010},
...: {'points': 25, 'time': '6:00', 'month': "february"},
...: {'points':90, 'time': '9:00', 'month': 'january'},
...: {'points_h1':20, 'month': 'june'}]
In [12]: pd.DataFrame.from_dict(d)
Out[12]:
month points points_h1 time year
0 NaN 50.0 NaN 5:00 2010.0
1 february 25.0 NaN 6:00 NaN
2 january 90.0 NaN 9:00 NaN
3 june NaN 20.0 NaN NaN
Well I know this might be a big change or even not suitable for your project, but did you consider not performing the push until you already have the data? That way you only need to draw the view once and the user experience will also be better - the push will move in already loaded.
The way you do this is in the UITableView
didSelectRowAtIndexPath
you asynchronously ask for the data. Once you receive the response, you manually perform the segue and pass the data to your viewController in prepareForSegue
.
Meanwhile you may want to show some activity indicator, for simple loading indicator check https://github.com/jdg/MBProgressHUD
You are right, the second Dockerfile will overwrite the CMD
command of the first one. Docker will always run a single command, not more. So at the end of your Dockerfile, you can specify one command to run. Not more.
But you can execute both commands in one line:
FROM centos+ssh
EXPOSE 22
EXPOSE 4149
CMD service sshd start && /opt/mq/sbin/rabbitmq-server start
What you could also do to make your Dockerfile a little bit cleaner, you could put your CMD commands to an extra file:
FROM centos+ssh
EXPOSE 22
EXPOSE 4149
CMD sh /home/centos/all_your_commands.sh
And a file like this:
service sshd start &
/opt/mq/sbin/rabbitmq-server start
The ideal way is not to use ioutil.ReadAll
, but rather use a decoder on the reader directly. Here's a nice function that gets a url and decodes its response onto a target
structure.
var myClient = &http.Client{Timeout: 10 * time.Second}
func getJson(url string, target interface{}) error {
r, err := myClient.Get(url)
if err != nil {
return err
}
defer r.Body.Close()
return json.NewDecoder(r.Body).Decode(target)
}
Example use:
type Foo struct {
Bar string
}
func main() {
foo1 := new(Foo) // or &Foo{}
getJson("http://example.com", foo1)
println(foo1.Bar)
// alternately:
foo2 := Foo{}
getJson("http://example.com", &foo2)
println(foo2.Bar)
}
You should not be using the default *http.Client
structure in production as this answer originally demonstrated! (Which is what http.Get
/etc call to). The reason is that the default client has no timeout set; if the remote server is unresponsive, you're going to have a bad day.
Is there something that prevents you from merging all revisions on trunk since the last merge?
svn merge -rLastRevisionMergedFromTrunkToBranch:HEAD url/of/trunk path/to/branch/wc
should work just fine. At least if you want to merge all changes on trunk to your branch.
In IntelliJ IDEA this happened to me when I imported a project that had been working fine and running with Java 1.7. I apparently hadn't notified IntelliJ that java 1.7 had been installed on my machine, and it wasn't finding my $JAVA_HOME
.
On a Mac, this is resolved by:
Right clicking on the module | Module Settings | Project
and adding the 1.7 SDK by selecting "New" in the Project SDK.
Then go to the main IntelliJ IDEA menu | Preferences | Maven | Runner
and select the correct JRE. In my case it updated correctly Use Project SDK, which was now 1.7.
I know this is an older subject, however Mocking a MVC application for unit tests is something we do on very regular basis.
I just wanted to add my experiences Mocking a MVC 3 application using Moq 4 after upgrading to Visual Studio 2013. None of the unit tests were working in debug mode and the HttpContext was showing "could not evaluate expression" when trying to peek at the variables.
Turns out visual studio 2013 has issues evaluating some objects. To get debugging mocked web applications working again, I had to check the "Use Managed Compatibility Mode" in Tools=>Options=>Debugging=>General settings.
I generally do something like this:
public static class FakeHttpContext
{
public static void SetFakeContext(this Controller controller)
{
var httpContext = MakeFakeContext();
ControllerContext context =
new ControllerContext(
new RequestContext(httpContext,
new RouteData()), controller);
controller.ControllerContext = context;
}
private static HttpContextBase MakeFakeContext()
{
var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
var response = new Mock<HttpResponseBase>();
var session = new Mock<HttpSessionStateBase>();
var server = new Mock<HttpServerUtilityBase>();
var user = new Mock<IPrincipal>();
var identity = new Mock<IIdentity>();
context.Setup(c=> c.Request).Returns(request.Object);
context.Setup(c=> c.Response).Returns(response.Object);
context.Setup(c=> c.Session).Returns(session.Object);
context.Setup(c=> c.Server).Returns(server.Object);
context.Setup(c=> c.User).Returns(user.Object);
user.Setup(c=> c.Identity).Returns(identity.Object);
identity.Setup(i => i.IsAuthenticated).Returns(true);
identity.Setup(i => i.Name).Returns("admin");
return context.Object;
}
}
And initiating the context like this
FakeHttpContext.SetFakeContext(moController);
And calling the Method in the controller straight forward
long lReportStatusID = -1;
var result = moController.CancelReport(lReportStatusID);
I presume you are talking about filling zeros of some existing mat? How about this? :)
mat *= 0;
In GNU Awk 4.1.0 (released 2013) and later, it has the option of "inplace" file editing:
[...] The "inplace" extension, built using the new facility, can be used to simulate the GNU "
sed -i
" feature. [...]
Example usage:
$ gawk -i inplace '{ gsub(/foo/, "bar") }; { print }' file1 file2 file3
To keep the backup:
$ gawk -i inplace -v INPLACE_SUFFIX=.bak '{ gsub(/foo/, "bar") }
> { print }' file1 file2 file3
I don't think you should implement the toggle method since there is a reason why it was removed from jQuery 1.9.
Consider using toggleClass instead that is fully supported by jQuery:
function a(){...}
function b(){...}
Let's say for example that your event trigger is onclick, so:
First option:
$('#test').on('click', function (event) {
$(this).toggleClass('toggled');
if ($(this).hasClass('toggled')) {
a();
} else{
b();
}
}
You can also send the handler functions as parameters:
Second option:
$('#test').on('click',{handler1: a, handler2: b}, function (event) {
$(this).toggleClass('toggled');
if ($(this).hasClass('toggled')) {
event.data.handler1();
} else{
event.data.handler2();
}
}
I got this error on my ASP.Net 4.5 app on Windows Server 2012 R2.
Go to start menu -> "Turn windows features on or off". A wizard popped up for me.
Click Next to Server Roles
I had to check these to get this to work, located under Web Server IIS->Web Server-> Application Development (these are based on Jeremy Cook's answer above):
Then click next to Features and make sure the following is checked:
Then click next and Install. At this point, the error went away for me. Good luck!
In my case my application tag includes:
<application
android:name=".common.MyApplication"
android:allowBackup="false"
android:extractNativeLibs="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true"
tools:ignore="GoogleAppIndexingWarning"
tools:replace="android:appComponentFactory">
I resolved this issue my adding new param as android:appComponentFactory=""
So my final application tag becomes:
<application
android:name=".common.MyApplication"
android:allowBackup="false"
android:extractNativeLibs="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true"
tools:ignore="GoogleAppIndexingWarning"
tools:replace="android:appComponentFactory"
android:appComponentFactory="">
I encountered above issue when I tired using firebase-auth latest version as "19.3.1". Whereas in my project I was already using firebase but version was "16.0.6".
.middle {
margin:0 auto;
text-align: center;
}
/* it brings div to center */
It's pretty crazy town that the only way to make checked false is to omit any values. With Angular 1.x, you can do this:
<input type="radio" ng-checked="false">
which is a lot more sane, if you need to make it unchecked.
Check this: Why is the Android emulator so slow? How can we speed up the Android emulator?
Android Emulator is very slow on most computers, on that post you can read some suggestions to improve performance of emulator, or use android_x86 virtual machine
No, they don't exist.
I know that the C# team was considering them at one point (or at least Eric Lippert was) - along with extension constructors and operators (those may take a while to get your head around, but are cool...) However, I haven't seen any evidence that they'll be part of C# 4.
EDIT: They didn't appear in C# 5, and as of July 2014 it doesn't look like it's going to be in C# 6 either.
Eric Lippert, the Principal Developer on the C# compiler team at Microsoft thru November 2012, blogged about this in October of 2009:
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.
I had this issue and tried both, but had to settle for removing crap like "pageEditState", but not removing user info lest I have to look it up again.
public static void RemoveEverythingButUserInfo()
{
foreach (String o in HttpContext.Current.Session.Keys)
{
if (o != "UserInfoIDontWantToAskForAgain")
keys.Add(o);
}
}
Simpler:
export
to all the lineseval
the whole thingeval $(cat .env | sed -e /^$/d -e /^#/d -e 's/^/export /')
Another option (you don't have to run eval
(thanks to @Jaydeep)):
export $(cat .env | sed -e /^$/d -e /^#/d | xargs)
Lastly, if you want to make your life REALLY easy, add this to your ~/.bash_profile
:
function source_envfile() { export $(cat $1 | sed -e /^$/d -e /^#/d | xargs); }
(MAKE SURE YOU RELOAD YOUR BASH SETTINGS!!! source ~/.bash_profile
or.. just make a new tab/window and problem solved) you call it like this: source_envfile .env
Maybe I don't completely understand the accepted answer so it didn't work for me.
What i did was simply to check if the variable is null, assign it to a known value from my database. Which seems to be similar to the accepted answer whereby you first declare an known value and set it to selected
<select name="department">
<c:forEach var="item" items="${dept}">
<option value="${item.key}">${item.value}</option>
</c:forEach>
</select>
because none of the options are selected, thus item = null
<%
if(item == null){
item = "selectedDept"; //known value from your database
}
%>
This way if the user then selects another option, my IF clause will not catch it and assign to the fixed value that was declared at the start. My concept could be wrong here but it works for me
int var1 = int.Parse(ds.Tables[0].Rows[0][3].ToString());
int var2 = int.Parse(ds.Tables[0].Rows[0][4].ToString());
Facebook uses MQTT instead of HTTP. Push is better than polling. Through HTTP we need to poll the server continuously but via MQTT server pushes the message to clients.
Comparision between MQTT and HTTP: http://www.youtube.com/watch?v=-KNPXPmx88E
Note: my answers best fits for mobile devices.
With try-with-resources writer will be automatically closed:
import org.apache.commons.lang3.StringUtils;
final File file = new File("SomeFile");
try (PrintWriter writer = new PrintWriter(file)) {
writer.print(StringUtils.EMPTY);
}
// here we can be sure that writer will be closed automatically
select
sum(a) as atotal,
sum(b) as btotal,
sum(c) as ctotal
from
yourtable t
where
t.id in (1, 2, 3)
As the previous answers saids, try to move the state to a top component and modify the state through callbacks passed to it's children.
In case that you really need to access to a child state that is declared as a functional component (hooks) you can declare a ref in the parent component, then pass it as a ref attribute to the child but you need to use React.forwardRef and then the hook useImperativeHandle to declare a function you can call in the parent component.
Take a look at the following example:
const Parent = () => {
const myRef = useRef();
return <Child ref={myRef} />;
}
const Child = React.forwardRef((props, ref) => {
const [myState, setMyState] = useState('This is my state!');
useImperativeHandle(ref, () => ({getMyState: () => {return myState}}), [myState]);
})
Then you should be able to get myState in the Parent component by calling:
myRef.current.getMyState();
new Date(date) === 'Invalid Date'
only works in Firefox and Chrome. IE8 (the one I have on my machine for testing purposes) gives NaN.
As was stated to the accepted answer, Date.parse(date)
will also work for numbers. So to get around that, you could also check that it is not a number (if that's something you want to confirm).
var parsedDate = Date.parse(date);
// You want to check again for !isNaN(parsedDate) here because Dates can be converted
// to numbers, but a failed Date parse will not.
if (isNaN(date) && !isNaN(parsedDate)) {
/* do your work */
}
If you already have the data "for (Parcelable currentHeadline : allHeadlines)," then why are you doing that in a separate thread?
You should poll the data in a separate thread, and when it's finished gathering it, then call your populateTables method on the UI thread:
private void populateTable() {
runOnUiThread(new Runnable(){
public void run() {
//If there are stories, add them to the table
for (Parcelable currentHeadline : allHeadlines) {
addHeadlineToTable(currentHeadline);
}
try {
dialog.dismiss();
} catch (final Exception ex) {
Log.i("---","Exception in thread");
}
}
});
}
Yes, it's easy and possible. Define first default colors.
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.White;
Console.Clear();
Console.Clear()
it's important in order to set new console colors. If you don't make this step you can see combined colors when ask for values with Console.ReadLine()
.
Then you can change the colors on each print:
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Red text over black.");
When finish your program, remember reset console colors on finish:
Console.ResetColor();
Console.Clear();
Now with netcore we have another problem if you want to "preserve" the User experience because terminal have different colors on each Operative System.
I'm making a library that solves this problem with Text Format: colors, alignment and lot more. Feel free to use and contribute.
https://github.com/deinsoftware/colorify/ and also available as NuGet package
You can do like this :
input {
vertical-align:middle;
}
label{
color:#222;
font-family:corbel,sans-serif;
font-size: 14px;
}
This solution has left aligned text and button on the far right.
If anyone is looking for a material design answer:
<div layout="column" layout-align="start start">
<div layout="row" style="width:100%">
<div flex="grow">Left Aligned text</div>
<md-button aria-label="help" ng-click="showHelpDialog()">
<md-icon md-svg-icon="help"></md-icon>
</md-button>
</div>
</div>
char c = '5'
A char
(1 byte) is allocated on stack at address 0x12345678
.
char *d = &c;
You obtain the address of c
and store it in d
, so d = 0x12345678
.
int *e = (int*)d;
You force the compiler to assume that 0x12345678
points to an int
, but an int is not just one byte (sizeof(char) != sizeof(int)
). It may be 4 or 8 bytes according to the architecture or even other values.
So when you print the value of the pointer, the integer is considered by taking the first byte (that was c
) and other consecutive bytes which are on stack and that are just garbage for your intent.
(boolean)json_decode(strtolower($string))
It handles all possible variants of $string
'true' => true
'True' => true
'1' => true
'false' => false
'False' => false
'0' => false
'foo' => false
'' => false
The accepted answer is a good solution. The problem with it is that so far it only works on Windows 10, Linux and Mac. Yes Windows (known for it lack of ANSI support)! This new feature was implemented on Windows 10 (and above) which includes ANSI support, although you have to enable it. This will clear the screen in a cross platform manner:
import os
print ('Hello World')
os.system('')
print ("\x1B[2J")
On anything below Windows 10 however it returns this:
[2J
This is due to the lack of ANSI support on previous Windows builds. This can however, be solved using the colorama module. This adds support for ANSI characters on Windows:
ANSI escape character sequences have long been used to produce colored terminal text and cursor positioning on Unix and Macs. Colorama makes this work on Windows, too, by wrapping stdout, stripping ANSI sequences it finds (which would appear as gobbledygook in the output), and converting them into the appropriate win32 calls to modify the state of the terminal. On other platforms, Colorama does nothing.
So here is a cross platform method:
import sys
if sys.platform == 'win32':
from colorama import init
init()
print('Hello World')
print("\x1B[2J")
Or print(chr(27) + "[2J")
used instead of print("\x1B[2J")
.
@poke answer is very insecure on Windows, yes it works but it is really a hack. A file named cls.bat
or cls.exe
in the same dictionary as the script will conflict with the command and execute the file instead of the command, creating a huge security hazard.
One method to minimise the risk could be to change the location of where the cls
command is called:
import os
os.system('cd C:\\Windows|cls' if os.name == 'nt' else 'clear')
This will change the Currant Dictionary to C:\Window
(backslash is important here) then execute. C:\Windows
is always present and needs administration permissions to write there making it a good for executing this command with minimal risk. Another solution is to run the command through PowerShell instead of Command Prompt since it has been secured against such vulnerabilities.
There are also other methods mentioned in this question: Clear screen in shell which may also be of use.
The appearance and disappearance of a window for displaying text is a feature of how you are running the program, not of C++.
Run in a persistent command line environment, or include windowing support in your program, or use sleep
or wait on input as shown in other answers.
This is by far the best post for exporting to excel from SQL:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926
To quote from user madhivanan
,
Apart from using DTS and Export wizard, we can also use this query to export data from SQL Server2000 to Excel
Create an Excel file named testing having the headers same as that of table columns and use these queries
1 Export data to existing EXCEL file from SQL Server table
insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;',
'SELECT * FROM [SheetName$]') select * from SQLServerTable
2 Export data from Excel to new SQL Server table
select *
into SQLServerTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;HDR=YES',
'SELECT * FROM [Sheet1$]')
3 Export data from Excel to existing SQL Server table (edited)
Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;HDR=YES',
'SELECT * FROM [SheetName$]')
4 If you dont want to create an EXCEL file in advance and want to export data to it, use
EXEC sp_makewebtask
@outputfile = 'd:\testing.xls',
@query = 'Select * from Database_name..SQLServerTable',
@colheaders =1,
@FixedFont=0,@lastupdated=0,@resultstitle='Testing details'
(Now you can find the file with data in tabular format)
5 To export data to new EXCEL file with heading(column names), create the following procedure
create procedure proc_generate_excel_with_columns
(
@db_name varchar(100),
@table_name varchar(100),
@file_name varchar(100)
)
as
--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)
select
@columns=coalesce(@columns+',','')+column_name+' as '+column_name
from
information_schema.columns
where
table_name=@table_name
select @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')
--Create a dummy file to have actual data
select @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.xls'
--Generate column names in the passed EXCEL file
set @sql='exec master..xp_cmdshell ''bcp " select * from (select '+@columns+') as t" queryout "'+@file_name+'" -c'''
exec(@sql)
--Generate data in the dummy file
set @sql='exec master..xp_cmdshell ''bcp "select * from '+@db_name+'..'+@table_name+'" queryout "'+@data_file+'" -c'''
exec(@sql)
--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''
exec(@sql)
--Delete dummy file
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)
After creating the procedure, execute it by supplying database name, table name and file path:
EXEC proc_generate_excel_with_columns 'your dbname', 'your table name','your file path'
Its a whomping 29 pages but that is because others show various other ways as well as people asking questions just like this one on how to do it.
Follow that thread entirely and look at the various questions people have asked and how they are solved. I picked up quite a bit of knowledge just skimming it and have used portions of it to get expected results.
To update single cells
A member also there Peter Larson posts the following: I think one thing is missing here. It is great to be able to Export and Import to Excel files, but how about updating single cells? Or a range of cells?
This is the principle of how you do manage that
update OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\test.xls;hdr=no',
'SELECT * FROM [Sheet1$b7:b7]') set f1 = -99
You can also add formulas to Excel using this:
update OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\test.xls;hdr=no',
'SELECT * FROM [Sheet1$b7:b7]') set f1 = '=a7+c7'
Exporting with column names using T-SQL
Member Mladen Prajdic also has a blog entry on how to do this here
References: www.sqlteam.com (btw this is an excellent blog / forum for anyone looking to get more out of SQL Server). For error referencing I used this
If you get the following error:
OLE DB provider 'Microsoft.Jet.OLEDB.4.0' cannot be used for distributed queries
Then run this:
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO
For arbitrary levels of nestedness:
In [2]: def nested_dict():
...: return collections.defaultdict(nested_dict)
...:
In [3]: a = nested_dict()
In [4]: a
Out[4]: defaultdict(<function __main__.nested_dict>, {})
In [5]: a['a']['b']['c'] = 1
In [6]: a
Out[6]:
defaultdict(<function __main__.nested_dict>,
{'a': defaultdict(<function __main__.nested_dict>,
{'b': defaultdict(<function __main__.nested_dict>,
{'c': 1})})})
public string Sifre_Uret(int boy, int noalfa)
{
// 01.03.2016
// Genel amaçli sifre üretme fonksiyonu
//Fonskiyon 128 den büyük olmasina izin vermiyor.
if (boy > 128 ) { boy = 128; }
if (noalfa > 128) { noalfa = 128; }
if (noalfa > boy) { noalfa = boy; }
string passch = System.Web.Security.Membership.GeneratePassword(boy, noalfa);
//URL encoding ve Url Pass + json sorunu yaratabilecekler pass ediliyor.
//Microsoft Garanti etmiyor. Alfa Sayisallar Olabiliyorimis . !@#$%^&*()_-+=[{]};:<>|./?.
//https://msdn.microsoft.com/tr-tr/library/system.web.security.membership.generatepassword(v=vs.110).aspx
//URL ve Json ajax lar için filtreleme
passch = passch.Replace(":", "z");
passch = passch.Replace(";", "W");
passch = passch.Replace("'", "t");
passch = passch.Replace("\"", "r");
passch = passch.Replace("/", "+");
passch = passch.Replace("\\", "e");
passch = passch.Replace("?", "9");
passch = passch.Replace("&", "8");
passch = passch.Replace("#", "D");
passch = passch.Replace("%", "u");
passch = passch.Replace("=", "4");
passch = passch.Replace("~", "1");
passch = passch.Replace("[", "2");
passch = passch.Replace("]", "3");
passch = passch.Replace("{", "g");
passch = passch.Replace("}", "J");
//passch = passch.Replace("(", "6");
//passch = passch.Replace(")", "0");
//passch = passch.Replace("|", "p");
//passch = passch.Replace("@", "4");
//passch = passch.Replace("!", "u");
//passch = passch.Replace("$", "Z");
//passch = passch.Replace("*", "5");
//passch = passch.Replace("_", "a");
passch = passch.Replace(",", "V");
passch = passch.Replace(".", "N");
passch = passch.Replace("+", "w");
passch = passch.Replace("-", "7");
return passch;
}
Put it in a JScrollPane
Edit: Here is a link for you: http://java.sun.com/docs/books/tutorial/uiswing/components/textarea.html
And here is a bigint version of the same
DECLARE @ts BIGINT
SET @ts = CAST(CAST(getdate() AS TIMESTAMP) AS BIGINT)
SELECT @ts
According to http://www.cplusplus.com/reference/std/iterator/distance/, since vec.begin()
is a random access iterator, the distance method uses the -
operator.
So the answer is, from a performance point of view, it is the same, but maybe using distance()
is easier to understand if anybody would have to read and understand your code.
I had same problem.
The cause was that I declared same global variable in 2 files. So it was showing same error saying 2 duplicate symbols.
The solution was to remove those variables.
The easiest solution is to override SaveChanges
on your entities class. You can catch the DbEntityValidationException
, unwrap the actual errors and create a new DbEntityValidationException
with the improved message.
Your exception message will now look like this:
System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. The validation errors are: The field PhoneNumber must be a string or array type with a maximum length of '12'; The LastName field is required.
You can drop the overridden SaveChanges in any class that inherits from DbContext
:
public partial class SomethingSomethingEntities
{
public override int SaveChanges()
{
try
{
return base.SaveChanges();
}
catch (DbEntityValidationException ex)
{
// Retrieve the error messages as a list of strings.
var errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
// Join the list to a single string.
var fullErrorMessage = string.Join("; ", errorMessages);
// Combine the original exception message with the new one.
var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
// Throw a new DbEntityValidationException with the improved exception message.
throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
}
}
}
The DbEntityValidationException
also contains the entities that caused the validation errors. So if you require even more information, you can change the above code to output information about these entities.
See also: http://devillers.nl/improving-dbentityvalidationexception/
Try using IgnoreDataMember
property
public class Foo
{
[IgnoreDataMember]
public int Id { get; set; }
public string Name { get; set; }
}
I'd just experienced something slightly different, because I work on my own library (WM_GSRecognizerLib), but the error is the same.
What'd happen: due to some updates, the path targeting the lib to include (.a) was from the "Debug-iphoneos" folder (where it is generated). Compiling for Generic iOS Devices worked fine, but not for simulator, complaining for the missing i386 architecture.
What I did for this issue, is to also include the binaries from the "Debug-iphonesimulator" folder.
It can help for this topic, because the explanation is here: devices require binaries for arm64/armv7/armv7s, while simulator does need i386.
This will happen if the host page is HTTPS and the included javascript source path is HTTP. The two protocols must be the same, HTTPS. The tell tail sign would be to check under Firebug and notice that the JS is "denied access".
First of all, I don't really see why you would want an object having only ID and Version, and all other props to be nulls. However, here is some code which will do that for you (which doesn't use JPA Em, but normal Hibernate. I assume you can find the equivalence in JPA or simply obtain the Hibernate Session obj from the em delegate Accessing Hibernate Session from EJB using EntityManager ):
List<T> results = session.createCriteria(entityClazz)
.setProjection( Projections.projectionList()
.add( Property.forName("ID") )
.add( Property.forName("VERSION") )
)
.setResultTransformer(Transformers.aliasToBean(entityClazz);
.list();
This will return a list of Objects having their ID and Version set and all other props to null, as the aliasToBean transformer won't be able to find them. Again, I am uncertain I can think of a situation where I would want to do that.
I had a similar issue when opening the sql developer it gave me the below error
Unable to launch the Java Virtual Machine due to missing file MSVCR100.DLL
I was using JDK 8 and windows 64 bit version. Also I downloaded the oracle sql developer software with no jdk/jre option since I already have jdk 8 installed in my system. While double clicking the sqldeveloper.exe file, it asked me to input the path of the JDK. I gave the path and then it gave me the JVM MSVCR100.DLL error.
I checked inside the C:\Program Files\Java\jdk1.8.0_271\jre\bin and couldnt find the MSVCR100.DLL file there.
Then after searching the microsoft forum, understood this dll is part of the 64Bit: Microsoft Visual C++ 2010 SP1 Redistributable Package (x64).
After installing the above microsoft package I am able to find the dll under C:\Windows\System32
Then did the below,
This resolved the error and I was able to open up the Oracle SQL developer when it found the right dll.
do like this
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//codes..,.,,
Uri sound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(sound);
}
this is what i came up with as i was having issues with @asp8811 answer(maybe my own difficulties)
' this will do the put the first 2 sheets in a pdf ' Note each ws should be controlled with page breaks for printing which is a bit fiddly ' this will explicitly put the pdf in the current dir
Sub luxation2()
Dim Filename As String
Filename = "temp201"
Dim shtAry()
ReDim shtAry(1) ' this is an array of length 2
For i = 1 To 2
shtAry(i - 1) = Sheets(i).Name
Debug.Print Sheets(i).Name
Next i
Sheets(shtAry).Select
Debug.Print ThisWorkbook.Path & "\"
ActiveSheet.ExportAsFixedFormat xlTypePDF, ThisWorkbook.Path & "/" & Filename & ".pdf", , , False
End Sub
In IE9+, Chrome or Firefox you can do:
var checkedBoxes = document.querySelectorAll('input[name=mycheckboxes]:checked');
I tried following format, working fine
*/5 * * * * wget --quiet -O /dev/null http://localhost/cron.php
The 'Answer' didn't work for me some reasons. So here is what I ended up doing:
////var group = new L.featureGroup(markerArray);//getting 'getBounds() not a function error.
////map.fitBounds(group.getBounds());
var bounds = L.latLngBounds(markerArray);
map.fitBounds(bounds);//works!
A problem that you get when you allow constructors in interfaces comes from the possibility to implement several interfaces at the same time. When a class implements several interfaces that define different constructors, the class would have to implement several constructors, each one satisfying only one interface, but not the others. It will be impossible to construct an object that calls each of these constructors.
Or in code:
interface Named { Named(String name); }
interface HasList { HasList(List list); }
class A implements Named, HasList {
/** implements Named constructor.
* This constructor should not be used from outside,
* because List parameter is missing
*/
public A(String name) {
...
}
/** implements HasList constructor.
* This constructor should not be used from outside,
* because String parameter is missing
*/
public A(List list) {
...
}
/** This is the constructor that we would actually
* need to satisfy both interfaces at the same time
*/
public A(String name, List list) {
this(name);
// the next line is illegal; you can only call one other super constructor
this(list);
}
}