Using mktime:
list($day, $month, $year) = explode('-', '22-09-2008');
echo mktime(0, 0, 0, $month, $day, $year);
The difference between Response.Write()
and Response.Output.Write()
in ASP.NET. The short answer is that the latter gives you String.Format-style
output and the former doesn't. The long answer follows.
In ASP.NET the Response
object is of type HttpResponse
and when you say Response.Write
you're really saying (basically) HttpContext.Current.Response.Write
and calling one of the many overloaded Write
methods of HttpResponse
.
Response.Write
then calls .Write()
on it's internal TextWriter
object:
public void Write(object obj){ this._writer.Write(obj);}
HttpResponse
also has a Property called Output
that is of type, yes, TextWriter
, so:
public TextWriter get_Output(){ return this._writer; }
Which means you can do the Response
whatever a TextWriter
will let you. Now, TextWriters support a Write()
method aka String.Format
, so you can do this:
Response.Output.Write("Scott is {0} at {1:d}", "cool",DateTime.Now);
But internally, of course, this is happening:
public virtual void Write(string format, params object[] arg)
{
this.Write(string.Format(format, arg));
}
Is there a way to declare first and then initialize an array in C?
There is! but not using the method you described.
You can't initialize with a comma separated list, this is only allowed in the declaration. You can however initialize with...
myArray[0] = 1;
myArray[1] = 2;
...
or
for(int i = 1; i <= SIZE; i++)
{
myArray[i-1] = i;
}
I met the same problem even using -ldl
.
Besides this option, source files need to be placed before libraries, see undefined reference to `dlopen'.
This should do it:
[^\x00-\x7F]+
It matches any character which is not contained in the ASCII character set (0-127, i.e. 0x0 to 0x7F).
You can do the same thing with Unicode:
[^\u0000-\u007F]+
For unicode you can look at this 2 resources:
There was a really good discussion on this over at comp.lang.python last year. It answers your question pretty thoroughly.
Imports are pretty straightforward really. Just remember the following:
'import' and 'from xxx import yyy' are executable statements. They execute when the running program reaches that line.
If a module is not in sys.modules, then an import creates the new module entry in sys.modules and then executes the code in the module. It does not return control to the calling module until the execution has completed.
If a module does exist in sys.modules then an import simply returns that module whether or not it has completed executing. That is the reason why cyclic imports may return modules which appear to be partly empty.
Finally, the executing script runs in a module named __main__, importing the script under its own name will create a new module unrelated to __main__.
Take that lot together and you shouldn't get any surprises when importing modules.
test.html
is will be helpful for how to use VLC WebAPI.
test.html
is located in the directory where VLC was installed.
e.g. C:\Program Files (x86)\VideoLAN\VLC\sdk\activex\test.html
The following code is a quote from the test.html
.
HTML:
<object classid="clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921" width="640" height="360" id="vlc" events="True">
<param name="MRL" value="" />
<param name="ShowDisplay" value="True" />
<param name="AutoLoop" value="False" />
<param name="AutoPlay" value="False" />
<param name="Volume" value="50" />
<param name="toolbar" value="true" />
<param name="StartTime" value="0" />
<EMBED pluginspage="http://www.videolan.org"
type="application/x-vlc-plugin"
version="VideoLAN.VLCPlugin.2"
width="640"
height="360"
toolbar="true"
loop="false"
text="Waiting for video"
name="vlc">
</EMBED>
</object>
JavaScript:
You can get vlc object from getVLC()
.
It works on IE 10 and Chrome.
function getVLC(name)
{
if (window.document[name])
{
return window.document[name];
}
if (navigator.appName.indexOf("Microsoft Internet")==-1)
{
if (document.embeds && document.embeds[name])
return document.embeds[name];
}
else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
{
return document.getElementById(name);
}
}
var vlc = getVLC("vlc");
// do something.
// e.g. vlc.playlist.play();
Quite an old question, but might be helpful to somebody in need.
If you know the url, 1. open the chrome browser, 2. open developer tools in chrome , 3. Put the url in search bar and hit enter 4. look in network tab, you will see the ip and port both
Use:
drop table uno
drop table dos
create table uno
(
uid int,
col1 char(1),
col2 char(2)
)
create table dos
(
did int,
col1 char(1),
col2 char(2),
[sql] char(4)
)
insert into uno(uid) values (1)
insert into uno(uid) values (2)
insert into dos values (1,'a','b',null)
insert into dos values (2,'c','d','cool')
select * from uno
select * from dos
EITHER:
update uno set col1 = (select col1 from dos where uid = did and [sql]='cool'),
col2 = (select col2 from dos where uid = did and [sql]='cool')
OR:
update uno set col1=d.col1,col2=d.col2 from uno
inner join dos d on uid=did where [sql]='cool'
select * from uno
select * from dos
If the ID column name is the same in both tables then just put the table name before the table to be updated and use an alias for the selected table, i.e.:
update uno set col1 = (select col1 from dos d where uno.[id] = d.[id] and [sql]='cool'),
col2 = (select col2 from dos d where uno.[id] = d.[id] and [sql]='cool')
Here you can check for couple of things.
DateTime.TryParseExact
. Check the complete list of formats, available here. CultureInfo.InvariantCulture
which is more likely add problem. So instead of passing a NULL
value or setting it to CultureInfo provider = new CultureInfo("en-US")
, you may write it like.
.
if (!DateTime.TryParseExact(txtStartDate.Text, formats,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out startDate))
{
//your condition fail code goes here
return false;
}
else
{
//success code
}
To all the great answers, I want to add a small detail:
If You write plugins (e.g. DLLs or .so libraries to be loaded by a CAD system), then static is a life saver that avoids name collisions like this one:
Even worse: Step 3 may behave differently depending on compiler optimization, plugin load mechanism, etc.
I had this issue once with two helper functions (same name, different behaviour) in two plugins. Declaring them static solved the problem.
You can move your proxy authentication and ssl staff to soap handler
port = new SomeService().getServicePort();
Binding binding = ((BindingProvider) port).getBinding();
binding.setHandlerChain(Collections.<Handler>singletonList(new ProxyHandler()));
This is my example, do all network ops
class ProxyHandler implements SOAPHandler<SOAPMessageContext> {
static class TrustAllHost implements HostnameVerifier {
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
}
static class TrustAllCert implements X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
}
private SSLSocketFactory socketFactory;
public SSLSocketFactory getSocketFactory() throws Exception {
// just an example
if (socketFactory == null) {
SSLContext sc = SSLContext.getInstance("SSL");
TrustManager[] trustAllCerts = new TrustManager[] { new TrustAllCert() };
sc.init(null, trustAllCerts, new java.security.SecureRandom());
socketFactory = sc.getSocketFactory();
}
return socketFactory;
}
@Override public boolean handleMessage(SOAPMessageContext msgCtx) {
if (!Boolean.TRUE.equals(msgCtx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)))
return true;
HttpURLConnection http = null;
try {
SOAPMessage outMessage = msgCtx.getMessage();
outMessage.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "UTF-8");
// outMessage.setProperty(SOAPMessage.WRITE_XML_DECLARATION, true); // Not working. WTF?
ByteArrayOutputStream message = new ByteArrayOutputStream(2048);
message.write("<?xml version='1.0' encoding='UTF-8'?>".getBytes("UTF-8"));
outMessage.writeTo(message);
String endpoint = (String) msgCtx.get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY);
URL service = new URL(endpoint);
Proxy proxy = Proxy.NO_PROXY;
//Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("{proxy.url}", {proxy.port}));
http = (HttpURLConnection) service.openConnection(proxy);
http.setReadTimeout(60000); // set your timeout
http.setConnectTimeout(5000);
http.setUseCaches(false);
http.setDoInput(true);
http.setDoOutput(true);
http.setRequestMethod("POST");
http.setInstanceFollowRedirects(false);
if (http instanceof HttpsURLConnection) {
HttpsURLConnection https = (HttpsURLConnection) http;
https.setHostnameVerifier(new TrustAllHost());
https.setSSLSocketFactory(getSocketFactory());
}
http.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
http.setRequestProperty("Content-Length", Integer.toString(message.size()));
http.setRequestProperty("SOAPAction", "");
http.setRequestProperty("Host", service.getHost());
//http.setRequestProperty("Proxy-Authorization", "Basic {proxy_auth}");
InputStream in = null;
OutputStream out = null;
try {
out = http.getOutputStream();
message.writeTo(out);
} finally {
if (out != null) {
out.flush();
out.close();
}
}
int responseCode = http.getResponseCode();
MimeHeaders responseHeaders = new MimeHeaders();
message.reset();
try {
in = http.getInputStream();
IOUtils.copy(in, message);
} catch (final IOException e) {
try {
in = http.getErrorStream();
IOUtils.copy(in, message);
} catch (IOException e1) {
throw new RuntimeException("Unable to read error body", e);
}
} finally {
if (in != null)
in.close();
}
for (Map.Entry<String, List<String>> header : http.getHeaderFields().entrySet()) {
String name = header.getKey();
if (name != null)
for (String value : header.getValue())
responseHeaders.addHeader(name, value);
}
SOAPMessage inMessage = MessageFactory.newInstance()
.createMessage(responseHeaders, new ByteArrayInputStream(message.toByteArray()));
if (inMessage == null)
throw new RuntimeException("Unable to read server response code " + responseCode);
msgCtx.setMessage(inMessage);
return false;
} catch (Exception e) {
throw new RuntimeException("Proxy error", e);
} finally {
if (http != null)
http.disconnect();
}
}
@Override public boolean handleFault(SOAPMessageContext context) {
return false;
}
@Override public void close(MessageContext context) {
}
@Override public Set<QName> getHeaders() {
return Collections.emptySet();
}
}
It use UrlConnection, you can use any library you want in handler. Have fun!
As far as I read manual pages, scanf says that 'l' length modifier indicates (in case of floating points) that the argument is of type double rather than of type float, so you can have 'lf, le, lg'.
As for printing, officially, the manual says that 'l' applies only to integer types. So it might be not supported on some systems or by some standards. For instance, I get the following error message when compiling with gcc -Wall -Wextra -pedantic
a.c:6:1: warning: ISO C90 does not support the ‘%lf’ gnu_printf format [-Wformat=]
So you may want to doublecheck if your standard supports the syntax.
To conclude, I would say that you read with '%lf' and you print with '%f'.
Try:
$data = file_get_contents ("file.json");
$json = json_decode($data, true);
foreach ($json as $key => $value) {
if (!is_array($value)) {
echo $key . '=>' . $value . '<br/>';
} else {
foreach ($value as $key => $val) {
echo $key . '=>' . $val . '<br/>';
}
}
}
If you don't need typesafe, just bring block to a new separated file and change the extension to .js,.jsx
var http=require('http');
http.get('http://eternagame.wikia.com/wiki/EteRNA_Dictionary', function(res){
var str = '';
console.log('Response is '+res.statusCode);
res.on('data', function (chunk) {
str += chunk;
});
res.on('end', function () {
console.log(str);
});
});
Clean function can be called from VBA this way:
Range("A1").Value = Application.WorksheetFunction.Clean(Range("A1"))
However as written here, the CLEAN function was designed to remove the first 32 non-printing characters in the 7 bit ASCII code (values 0 through 31) from text. In the Unicode character set, there are additional nonprinting characters (values 127, 129, 141, 143, 144, and 157). By itself, the CLEAN function does not remove these additional nonprinting characters.
Rick Rothstein have written code to handle even this situation here this way:
Function CleanTrim(ByVal S As String, Optional ConvertNonBreakingSpace As Boolean = True) As String
Dim X As Long, CodesToClean As Variant
CodesToClean = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, _
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 127, 129, 141, 143, 144, 157)
If ConvertNonBreakingSpace Then S = Replace(S, Chr(160), " ")
For X = LBound(CodesToClean) To UBound(CodesToClean)
If InStr(S, Chr(CodesToClean(X))) Then S = Replace(S, Chr(CodesToClean(X)), "")
Next
CleanTrim = WorksheetFunction.Trim(S)
End Function
You can try as.vector(t(test))
. Please note that, if you want to do it by columns you should use unlist(test)
.
For me, this was due to the user PATH environment variable, which didn't seem to work even though the user was correct, so I needed to put the entire executable path into the program field.
The equivalent of offsetHeight and offsetWidth in jQuery is $(window).width(), $(window).height() It's not the clientHeight and clientWidth
For IE: window.close();
and self.close();
should work fine.
If you want just open the IE browser and type
javascript:self.close()
and hit enter, it should ask you for a prompt.
Note: this method doesn't work for Chrome or Firefox.
Another online XML Schema (XSD) validator: http://www.utilities-online.info/xsdvalidation/.
Try by Setting up FirefoxProfile
from selenium import webdriver
import time
"Define Both ProxyHost and ProxyPort as String"
ProxyHost = "54.84.95.51"
ProxyPort = "8083"
def ChangeProxy(ProxyHost ,ProxyPort):
"Define Firefox Profile with you ProxyHost and ProxyPort"
profile = webdriver.FirefoxProfile()
profile.set_preference("network.proxy.type", 1)
profile.set_preference("network.proxy.http", ProxyHost )
profile.set_preference("network.proxy.http_port", int(ProxyPort))
profile.update_preferences()
return webdriver.Firefox(firefox_profile=profile)
def FixProxy():
""Reset Firefox Profile""
profile = webdriver.FirefoxProfile()
profile.set_preference("network.proxy.type", 0)
return webdriver.Firefox(firefox_profile=profile)
driver = ChangeProxy(ProxyHost ,ProxyPort)
driver.get("http://whatismyipaddress.com")
time.sleep(5)
driver = FixProxy()
driver.get("http://whatismyipaddress.com")
This program tested on both Windows 8 and Mac OSX. If you are using Mac OSX and if you don't have selenium updated then you may face selenium.common.exceptions.WebDriverException
. If so, then try again after upgrading your selenium
pip install -U selenium
If you need to get json from php sending custom information you can add this header('Content-Type: application/json');
before to print any other thing, So then you can print you custome echo '{"monto": "'.$monto[0]->valor.'","moneda":"'.$moneda[0]->nombre.'","simbolo":"'.$moneda[0]->simbolo.'"}';
>>> '\\&' == '\&'
True
>>> len('\\&')
2
>>> print('\\&')
\&
Or in other words: '\\&'
only contains one backslash. It's just escaped in the python shell's output for clarity.
I use the latest version of SSMS or sql server management studio. I have a SQL script (in query editor) which has about 100 lines of code. This is error I got in the query:
Msg 245, Level 16, State 1, Line 2
Conversion failed when converting the nvarchar value 'abcd' to data type int.
Solution - I had seen this kind of error before when I forgot to enclose a number (in varchar column) in single quotes.
As an aside, the error message is misleading. The actual error on line number 70 in the query editor and not line 2 as the error says!
Note: if the name includes [
or ]
itself, add two backslashes in front of it, like:
<input name="array[child]" ...
document.querySelector("[name=array\\[child\\]]");
(1) This just happened to me, and I thought it was interesting how it happened. Basically I had copied the folder to a new location and modified it, forgetting that it would bring along all the hidden .svn directories. Once you realize how it happens it is easier to avoid in the future.
(2) Removing the .svn directories is the solution, but you have to do it recursively all the way down the directory tree. The easiest way to do that is:
find troublesome_folder -name .svn -exec rm -rf {} \;
When I got this error I wasn't even trying to sign the app. I was writing a test app and didn't care about signing. In order to get rid of this message I had to select "Don't Code Sign" from Build Settings under Code Signing.
I suggest the following structure, which might violate some existing conventions.
I was striving to reduce name redundancy in the path, and trying to keep naming short in general.
So there is no/app/components/home/home.component.ts|html|css.
Instead it looks like this:
|-- app
|-- users
|-- list.ts|html|css
|-- form.ts|html|css
|-- cars
|-- list.ts|html|css
|-- form.ts|html|css
|-- configurator.ts|html|css
|-- app.component.ts|html|css
|-- app.module.ts
|-- user.service.ts
|-- car.service.ts
|-- index.html
|-- main.ts
|-- style.css
In my case, I had to activate the option "SQL Server and Windows Authentication mode", follow all steps below:
1 - Right-click on your server
2 - Go to option Security
3 - Check the option "SQL Server and Windows Authentication mode"
5 - Restart your SQL Express Service ("Windows Key" on the keyboard and write "Services", and then Enter key)
After that, I could log in with user and password
Angular 6 + Alyle UI
With Alyle UI you can change the styles dynamically
Here a demo stackblitz
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
CommonModule,
FormsModule,
HttpClientModule,
BrowserAnimationsModule,
AlyleUIModule.forRoot(
{
name: 'myTheme',
primary: {
default: '#00bcd4'
},
accent: {
default: '#ff4081'
},
scheme: 'myCustomScheme', // myCustomScheme from colorSchemes
lightGreen: '#8bc34a',
colorSchemes: {
light: {
myColor: 'teal',
},
dark: {
myColor: '#FF923D'
},
myCustomScheme: {
background: {
primary: '#dde4e6',
},
text: {
default: '#fff'
},
myColor: '#C362FF'
}
}
}
),
LyCommonModule, // for bg, color, raised and others
],
bootstrap: [AppComponent]
})
export class AppModule { }
Html
<div [className]="classes.card">dynamic style</div>
<p color="myColor">myColor</p>
<p bg="myColor">myColor</p>
For change Style
import { Component } from '@angular/core';
import { LyTheme } from '@alyle/ui';
@Component({ ... })
export class AppComponent {
classes = {
card: this.theme.setStyle(
'card', // key
() => (
// style
`background-color: ${this.theme.palette.myColor};` +
`position: relative;` +
`margin: 1em;` +
`text-align: center;`
...
)
)
}
constructor(
public theme: LyTheme
) { }
changeScheme() {
const scheme = this.theme.palette.scheme === 'light' ?
'dark' : this.theme.palette.scheme === 'dark' ?
'myCustomScheme' : 'light';
this.theme.setScheme(scheme);
}
}
After importing the scripting runtime as described above you have to make some slighty modification to get it working in Excel 2010 (my version). Into the following code I've also add the code used to the user to pick a file.
Dim intChoice As Integer
Dim strPath As String
' Select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
' Show the selection window
intChoice = Application.FileDialog(msoFileDialogOpen).Show
' Get back the user option
If intChoice <> 0 Then
strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
Else
Exit Sub
End If
Dim FSO As New Scripting.FileSystemObject
Dim fsoStream As Scripting.TextStream
Dim strLine As String
Set fsoStream = FSO.OpenTextFile(strPath)
Do Until fsoStream.AtEndOfStream = True
strLine = fsoStream.ReadLine
' ... do your work ...
Loop
fsoStream.Close
Set FSO = Nothing
Hope it help!
Best regards
Fabio
<plugins>
<plugin>
<groupId>org.codehaus.groovy.maven</groupId>
<artifactId>gmaven-plugin</artifactId>
<version>1.0</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<source>
import java.io.File
project.properties.parentdir = "${pom.basedir}"
while (new File(new File(project.properties.parentdir).parent, 'pom.xml').exists()) {
project.properties.parentdir = new File(project.properties.parentdir).parent
}
</source>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0-alpha-2</version>
<executions>
<execution>
<phase>initialize</phase>
<goals>
<goal>read-project-properties</goal>
</goals>
<configuration>
<files>
<file>${parentdir}/build.properties</file>
</files>
</configuration>
</execution>
</executions>
</plugin>
...
For React Native
applications while running in debug add the xml block
mentioned by @Xenolion to react_native_config.xml
located in <project>/android/app/src/debug/res/xml
Similar to the following snippet:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="false">localhost</domain>
<domain includeSubdomains="false">10.0.2.2</domain>
<domain includeSubdomains="false">10.0.3.2</domain>
</domain-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
</network-security-config>
In addition to @Daniel Li's answer, the nginx installation with Valet would use the Velet configuration as well, this is found in "/usr/local/etc/nginx/valet/valet.conf". The nginx.conf file would have imported this Valet conf file. The settings you need may be in the Valet file.
The code posted above by @BrunoS did not work for me,
* {
.border-radius(0) !important;
}
what i used was
* {
border-radius: 0 !important;
}
I hope this helps someone
The major concern here is that the collections don't keep the type in the definition. The types are only available in runtime. I came up with a function to test complex collections (it has one constraint though).
Check if the object is an instance of a generic collection. In order to represent a collection,
false
instanceof
evaluationList
or Set
, the type of the list comes next e.g. {List, Integer} for List<Integer>
Map
, the key and value types come next e.g. {Map, String, Integer} for Map<String, Integer>
More complex use cases could be generated using the same rules. For example in order to represent List<Map<String, GenericRecord>>
, it can be called as
Map<String, Integer> map = new HashMap<>();
map.put("S1", 1);
map.put("S2", 2);
List<Map<String, Integer> obj = new ArrayList<>();
obj.add(map);
isInstanceOfGenericCollection(obj, List.class, List.class, Map.class, String.class, GenericRecord.class);
Note that this implementation doesn't support nested types in the Map. Hence, the type of key and value should be a class and not a collection. But it shouldn't be hard to add it.
public static boolean isInstanceOfGenericCollection(Object object, Class<?>... classes) {
if (classes.length == 0) return false;
if (classes.length == 1) return classes[0].isInstance(object);
if (classes[0].equals(List.class))
return object instanceof List && ((List<?>) object).stream().allMatch(item -> isInstanceOfGenericCollection(item, Arrays.copyOfRange(classes, 1, classes.length)));
if (classes[0].equals(Set.class))
return object instanceof Set && ((Set<?>) object).stream().allMatch(item -> isInstanceOfGenericCollection(item, Arrays.copyOfRange(classes, 1, classes.length)));
if (classes[0].equals(Map.class))
return object instanceof Map &&
((Map<?, ?>) object).keySet().stream().allMatch(classes[classes.length - 2]::isInstance) &&
((Map<?, ?>) object).values().stream().allMatch(classes[classes.length - 1]::isInstance);
return false;
}
For me I had to put the whole interval in single quotes not just the value of the interval.
select id,
title,
created_at + interval '1 day' * claim_window as deadline from projects
Instead of
select id,
title,
created_at + interval '1' day * claim_window as deadline from projects
Warning: ReactDOMComponent: Do not access .getDOMNode() of a DOM node; instead, use the node directly. This DOM node was rendered by
App
.
Should be
componentDidMount: function () {
this.refs.nameInput.focus();
}
Scripts are not allowed to close a window that a user opened. This is considered a security risk. Though it isn't in any standard, all browser vendors follow this (Mozilla docs). If this happens in some browsers, it's a security bug that (ideally) gets patched very quickly.
None of the hacks in the answers on this question work any longer, and if someone would come up with another dirty hack, eventually it will stop working as well.
I suggest you don't waste energy fighting this and embrace the method that the browser so helpfully gives you — ask the user before you seemingly crash their page.
Or if you are already using pandas, You can do it with json_normalize()
like so:
import pandas as pd
d = {'a': 1,
'c': {'a': 2, 'b': {'x': 5, 'y' : 10}},
'd': [1, 2, 3]}
df = pd.json_normalize(d, sep='_')
print(df.to_dict(orient='records')[0])
Output:
{'a': 1, 'c_a': 2, 'c_b_x': 5, 'c_b_y': 10, 'd': [1, 2, 3]}
Download and install packages and dependencies
Usage:
go get [-d] [-f] [-t] [-u] [-v] [-fix] [-insecure] [build flags] [packages]
Get downloads the packages named by the import paths, along with their dependencies. It then installs the named packages, like 'go install'.
The -d flag instructs get to stop after downloading the packages; that is, it instructs get not to install the packages.
The -f flag, valid only when -u is set, forces get -u not to verify that each package has been checked out from the source control repository implied by its import path. This can be useful if the source is a local fork of the original.
The -fix flag instructs get to run the fix tool on the downloaded packages before resolving dependencies or building the code.
The -insecure flag permits fetching from repositories and resolving custom domains using insecure schemes such as HTTP. Use with caution.
The -t flag instructs get to also download the packages required to build the tests for the specified packages.
The -u flag instructs get to use the network to update the named packages and their dependencies. By default, get uses the network to check out missing packages but does not use it to look for updates to existing packages.
The -v flag enables verbose progress and debug output.
Get also accepts build flags to control the installation. See 'go help build'.
When checking out a new package, get creates the target directory GOPATH/src/. If the GOPATH contains multiple entries, get uses the first one. For more details see: 'go help gopath'.
When checking out or updating a package, get looks for a branch or tag that matches the locally installed version of Go. The most important rule is that if the local installation is running version "go1", get searches for a branch or tag named "go1". If no such version exists it retrieves the default branch of the package.
When go get checks out or updates a Git repository, it also updates any git submodules referenced by the repository.
Get never checks out or updates code stored in vendor directories.
For more about specifying packages, see 'go help packages'.
For more about how 'go get' finds source code to download, see 'go help importpath'.
This text describes the behavior of get when using GOPATH to manage source code and dependencies. If instead the go command is running in module-aware mode, the details of get's flags and effects change, as does 'go help get'. See 'go help modules' and 'go help module-get'.
See also: go build, go install, go clean.
For example, showing verbose output,
$ go get -v github.com/capotej/groupcache-db-experiment/...
github.com/capotej/groupcache-db-experiment (download)
github.com/golang/groupcache (download)
github.com/golang/protobuf (download)
github.com/capotej/groupcache-db-experiment/api
github.com/capotej/groupcache-db-experiment/client
github.com/capotej/groupcache-db-experiment/slowdb
github.com/golang/groupcache/consistenthash
github.com/golang/protobuf/proto
github.com/golang/groupcache/lru
github.com/capotej/groupcache-db-experiment/dbserver
github.com/capotej/groupcache-db-experiment/cli
github.com/golang/groupcache/singleflight
github.com/golang/groupcache/groupcachepb
github.com/golang/groupcache
github.com/capotej/groupcache-db-experiment/frontend
$
Simple way to sort any map in Java 8 and above
Map<String, Object> mapToSort = new HashMap<>();
List<Map.Entry<String, Object>> list = new LinkedList<>(mapToSort.entrySet());
Collections.sort(list, Comparator.comparing(o -> o.getValue().getAttribute()));
HashMap<String, Object> sortedMap = new LinkedHashMap<>();
for (Map.Entry<String, Object> map : list) {
sortedMap.put(map.getKey(), map.getValue());
}
if you are using Java 7 and below
Map<String, Object> mapToSort = new HashMap<>();
List<Map.Entry<String, Object>> list = new LinkedList<>(mapToSort.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Object>>() {
@Override
public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {
return o1.getValue().getAttribute().compareTo(o2.getValue().getAttribute());
}
});
HashMap<String, Object> sortedMap = new LinkedHashMap<>();
for (Map.Entry<String, Object> map : list) {
sortedMap.put(map.getKey(), map.getValue());
}
There are multiple methods for handling this problem.
My advice is to use the powerful Windows freeware console application SendEmail.
sendEmail.exe -f [email protected] -o message-file=body.txt -u subject message -t [email protected] -a attachment.zip -s smtp.gmail.com:446 -xu gmail.login -xp gmail.password
Frankly, this looks like a semantic distinction, not a technical distinction. The phrase Data Access Object doesn't refer to a "database" at all. And, although you could design it to be database-centric, I think most people would consider doing so a design flaw.
The purpose of the DAO is to hide the implementation details of the data access mechanism. How is the Repository pattern different? As far as I can tell, it isn't. Saying a Repository is different to a DAO because you're dealing with/return a collection of objects can't be right; DAOs can also return collections of objects.
Everything I've read about the repository pattern seems rely on this distinction: bad DAO design vs good DAO design (aka repository design pattern).
If you want refresh the page you could use like this, but refreshing the page is usually not the best method, it better to try just update the content that you need to be updated.
javascript:
<script language="javascript">
setTimeout(function(){
window.location.reload(1);
}, 30000);
</script>
I think keySet() may be well to find the keys mapping to the value, and have a better coding style than entrySet().
Ex:
Suppose you have a HashMap map, ArrayList res, a value you want to find all the key mapping to , then store keys to the res.
You can write code below:
for (int key : map.keySet()) {
if (map.get(key) == value) {
res.add(key);
}
}
rather than use entrySet() below:
for (Map.Entry s : map.entrySet()) {
if ((int)s.getValue() == value) {
res.add((int)s.getKey());
}
}
Hope it helps :)
You can use a method such as
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
});
In reading the comments on the original post, to make it more usable and allow people to press Enter if they have completed all the fields:
function validationFunction() {
$('input').each(function() {
...
}
if(good) {
return true;
}
return false;
}
$(document).ready(function() {
$(window).keydown(function(event){
if( (event.keyCode == 13) && (validationFunction() == false) ) {
event.preventDefault();
return false;
}
});
});
I tried all the Solution but finally I am able to create resign ipa with these commands
Resign Certificates
Go the Directory where want to create the new ipa with resign certificates . Pase all the files there ipa, certificate and mobileprovision and also install the certificate
security cms -D -i path/to/MyProfile.mobileprovision > provision.plist (Call this command and replace mobile provision with path of the file)
/usr/libexec/PlistBuddy -x -c 'Print :Entitlements' provision.plist > entitlements.plist (Hit this command)
unzip -q *.ipa
rm -rf Payload/*.app/_CodeSignature/
/usr/libexec/PlistBuddy Payload/*.app/Info.plist (After this command we have to add new bundle ID if we don’t need to change bundle id Then we can ignore these 3 steps)
7. Set :CFBundleIdentifier “com.mycompany.newbundleidentifier” (This should be new bundle ID)
8. save
9. quit
cp $PROVISION Payload/*.app/embedded.mobileprovision
codesign -d --entitlements :entitlements.plist Payload/*.app/ (Try to ignore this command if app doesn’t work then next time use this command)
codesign -f -s "$CERTIFICATE" --entitlements entitlements.plist Payload/.app/Frameworks/
codesign -f -s "$CERTIFICATE" --entitlements entitlements.plist Payload/*.app/
zip -qr resigned.ipa Payload
https://stackoverflow.com/a/37172815 https://stackoverflow.com/a/50392448 https://coderwall.com/p/qwqpnw/resign-ipa-with-new-cfbundleidentifier-and-certificate
$ch = curl_init('http://www.google.com/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// get headers too with this line
curl_setopt($ch, CURLOPT_HEADER, 1);
$result = curl_exec($ch);
// get cookie
// multi-cookie variant contributed by @Combuster in comments
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $matches);
$cookies = array();
foreach($matches[1] as $item) {
parse_str($item, $cookie);
$cookies = array_merge($cookies, $cookie);
}
var_dump($cookies);
Create this method into your recyclerview Adapter
private void setZoomInAnimation(View view) {
Animation zoomIn = AnimationUtils.loadAnimation(context, R.anim.zoomin);// animation file
view.startAnimation(zoomIn);
}
And finally add this line of code in onBindViewHolder
setZoomInAnimation(holder.itemView);
Based on the very helpful answer by joran I was able to come up with this solution for a stable color scale for a boolean factor (TRUE
, FALSE
).
boolColors <- as.character(c("TRUE"="#5aae61", "FALSE"="#7b3294"))
boolScale <- scale_colour_manual(name="myboolean", values=boolColors)
ggplot(myDataFrame, aes(date, duration)) +
geom_point(aes(colour = myboolean)) +
boolScale
Since ColorBrewer isn't very helpful with binary color scales, the two needed colors are defined manually.
Here myboolean
is the name of the column in myDataFrame
holding the TRUE/FALSE factor. date
and duration
are the column names to be mapped to the x and y axis of the plot in this example.
This works in Python 2 and Python 3:
A random key:
random.choice(list(d.keys()))
A random value
random.choice(list(d.values()))
A random key and value
random.choice(list(d.items()))
You can use .change
for what you want
$("input[@name='lom']").change(function(){
// Do something interesting here
});
as of jQuery 1.3
you no longer need the '@'. Correct way to select is:
$("input[name='lom']")
I received the same console error message when working with this example: https://developers.google.com/analytics/devguides/reporting/embed/v1/getting-started
The documentation says not to overlook two critical steps ("As you go through the instructions, it's important that you not overlook these two critical steps: Enable the Analytics API [&] Set the correct origins"), but does not clearly state WHERE to set the correct origins.
Since the client ID I had was not working, I created a new project and a new client ID. The new project may not have been necessary, but I'm retaining (and using) it.
Here's what worked:
During creation of the credentials, you will see a section called "Restrictions Enter JavaScript origins, redirect URIs, or both". This is where you can enter your origins.
Save and copy your client ID (and secret).
My script worked after I created the new OAUTH credential, assigned the origin, and used the newly generated client ID following this process.
Since there is no php.ini file in your /public_html directory......create a new file as phpinfo.php in /public_html directory
-Type this code in phpinfo.php and save it:
<?php
phpinfo();
?>
-Then type yourdomain.com/phpinfo.php...you will see all the details of your configuration
-To edit that config, create another file as php.ini in /public_html directory and paste this code:
memory_limit=512M
post_max_size=200M
upload_max_filesize=200M
-And then refresh yourdomain.com/phpinfo.php and see the changes,it will be done.
Using Apache Commons Lang:
!StringUtils.isAlphanumeric(String)
Alternativly iterate over String's characters and check with:
!Character.isLetterOrDigit(char)
You've still one problem left:
Your example string "abcdefà" is alphanumeric, since à
is a letter. But I think you want it to be considered non-alphanumeric, right?!
So you may want to use regular expression instead:
String s = "abcdefà";
Pattern p = Pattern.compile("[^a-zA-Z0-9]");
boolean hasSpecialChar = p.matcher(s).find();
In the 6.6.8 version I installed the NppAutoIndent plugin from Plugins > Plugin Manager > Show Plugin Manager. Then I selected the Smart Indent option in Plugin > NppAutoIndent. Hope this helps.
If you want to take into consideration the platform (x64, x86 etc) and the configuration (Debug or Release) it would be something like this:
xcopy "$(SolutionDir)\$(Platform)\$(Configuration)\$(TargetName).dll" "$(SolutionDir)TestDirectory\bin\$(Platform)\$(Configuration)\" /F /Y
I think it comes from this line in your XML file:
<context:component-scan base-package="org.assessme.com.controller." />
Replace it by:
<context:component-scan base-package="org.assessme.com." />
It is because your Autowired service is not scanned by Spring since it is not in the right package.
I had to delete all the rows and did it with the next script:
DECLARE @Nombre NVARCHAR(MAX);
DECLARE curso CURSOR FAST_FORWARD
FOR
Select Object_name(object_id) AS Nombre from sys.objects where type = 'U'
OPEN curso
FETCH NEXT FROM curso INTO @Nombre
WHILE (@@FETCH_STATUS <> -1)
BEGIN
IF (@@FETCH_STATUS <> -2)
BEGIN
DECLARE @statement NVARCHAR(200);
SET @statement = 'DELETE FROM ' + @Nombre;
print @statement
execute sp_executesql @statement;
END
FETCH NEXT FROM curso INTO @Nombre
END
CLOSE curso
DEALLOCATE curso
Hope this helps!
You can use the sp_columns stored procedure:
exec sp_columns MyTable
I installed 32-bit JVM and retried it again, looks like the following does tell you JVM bitness, not OS arch:
System.getProperty("os.arch");
#
# on a 64-bit Linux box:
# "x86" when using 32-bit JVM
# "amd64" when using 64-bit JVM
This was tested against both SUN and IBM JVM (32 and 64-bit). Clearly, the system property is not just the operating system arch.
I think the strictSSL: false
should (should have worked, even in 2013) work. So in short are three possible ways:
request
object: const myRequest = require('request').defaults({strictSSL: false})
node-request
internally also allow a request
-object to be injected, so you can make them use your modified instance.NODE_TLS_REJECT_UNAUTHORIZED=0
for the Node.js process.In Ubuntu 12.04 I had to install openjdk-7-jdk
then javac was working !
then I could use
/usr/lib/jvm/java-7-openjdk-amd64
SELECT Id, 'TRUE' AS NewFiled FROM TABEL1
INTERSECT
SELECT Id, 'TRUE' AS NewFiled FROM TABEL2
UNION
SELECT Id, 'FALSE' AS NewFiled FROM TABEL1
EXCEPT
SELECT Id, 'FALSE' AS NewFiled FROM TABEL2;
There are three options:
results = Model.objects.exclude(a=True).filter(x=5)
Use Q()
objects and the ~
operator
from django.db.models import Q
object_list = QuerySet.filter(~Q(a=True), x=5)
Register a custom lookup function
from django.db.models import Lookup
from django.db.models import Field
@Field.register_lookup
class NotEqual(Lookup):
lookup_name = 'ne'
def as_sql(self, compiler, connection):
lhs, lhs_params = self.process_lhs(compiler, connection)
rhs, rhs_params = self.process_rhs(compiler, connection)
params = lhs_params + rhs_params
return '%s <> %s' % (lhs, rhs), params
Which can the be used as usual:
results = Model.objects.exclude(a=True, x__ne=5)
@QueryParam documentation says
" The type T of the annotated parameter, field or property must either:
1) Be a primitive type
2) Have a constructor that accepts a single String argument
3) Have a static method named valueOf or fromString that accepts a single String argument (see, for example, Integer.valueOf(String))
4) Have a registered implementation of javax.ws.rs.ext.ParamConverterProvider JAX-RS extension SPI that returns a javax.ws.rs.ext.ParamConverter instance capable of a "from string" conversion for the type.
5) Be List, Set or SortedSet, where T satisfies 2, 3 or 4 above. The resulting collection is read-only. "
If you want to control what response goes to user when query parameter in String form can't be converted to your type T, you can throw WebApplicationException. Dropwizard comes with following *Param classes you can use for your needs.
BooleanParam, DateTimeParam, IntParam, LongParam, LocalDateParam, NonEmptyStringParam, UUIDParam. See https://github.com/dropwizard/dropwizard/tree/master/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params
If you need Joda DateTime, just use Dropwizard DateTimeParam.
If the above list does not suit your needs, define your own by extending AbstractParam. Override parse method. If you need control over error response body, override error method.
Good article from Coda Hale on this is at http://codahale.com/what-makes-jersey-interesting-parameter-classes/
import io.dropwizard.jersey.params.AbstractParam;
import java.util.Date;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
public class DateParam extends AbstractParam<Date> {
public DateParam(String input) {
super(input);
}
@Override
protected Date parse(String input) throws Exception {
return new Date(input);
}
@Override
protected Response error(String input, Exception e) {
// customize response body if you like here by specifying entity
return Response.status(Status.BAD_REQUEST).build();
}
}
Date(String arg) constructor is deprecated. I would use Java 8 date classes if you are on Java 8. Otherwise joda date time is recommended.
Here is another solution:
1) Download SumatraPDF (portable version) - https://www.sumatrapdfreader.org/download-free-pdf-viewer.html
2) Create a class library project and unzip the SumatraPDF.exe to the project directory root and unblock it.
3) Inside the project Properties, go to the Resoruces tab and add the exe as a file.
4) Add the following class to your library:
public class SumatraWrapper : IDisposable
{
private readonly FileInfo _tempFileForExe = null;
private readonly FileInfo _exe = null;
public SumatraWrapper()
{
_exe = ExtractExe();
}
public SumatraWrapper(FileInfo tempFileForExe)
: this()
{
_tempFileForExe = tempFileForExe ?? throw new ArgumentNullException(nameof(tempFileForExe));
}
private FileInfo ExtractExe()
{
string tempfile =
_tempFileForExe != null ?
_tempFileForExe.FullName :
Path.GetTempFileName() + ".exe";
FileInfo exe = new FileInfo(tempfile);
byte[] bytes = Properties.Resources.SumatraPDF;
using (FileStream fs = exe.OpenWrite())
{
fs.Write(bytes, 0, bytes.Length);
}
return exe;
}
public bool Print(FileInfo file, string printerName)
{
string arguments = $"-print-to \"{printerName}\" \"{file.FullName}\"";
ProcessStartInfo processStartInfo = new ProcessStartInfo(_exe.FullName, arguments)
{
CreateNoWindow = true
};
using (Process process = Process.Start(processStartInfo))
{
process.WaitForExit();
return process.ExitCode == 0;
}
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: dispose managed state (managed objects).
}
// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
// TODO: set large fields to null.
try
{
File.Delete(_exe.FullName);
}
catch
{
}
disposedValue = true;
}
}
// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~PdfToPrinterWrapper() {
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
#endregion
}
5) Enjoy printing pdf files from your code.
Use like this:
FileInfo file = new FileInfo(@"c:\Sandbox\dummy file.pdf");
SumatraWrapper pdfToPrinter =
new SumatraWrapper();
pdfToPrinter.Print(file, "My Printer");
This post pertains to R proxy issues on *nix. You should know that R has many libraries/methods to fetch data over internet.
For 'curl', 'libcurl', 'wget' etc, just do the following:
Open a terminal. Type the following command:
sudo gedit /etc/R/Renviron.site
Enter the following lines:
http_proxy='http://username:[email protected]:port/'
https_proxy='https://username:[email protected]:port/'
Replace username
, password
, abc.com
, xyz.com
and port
with these settings specific to your network.
Quit R and launch again.
This should solve your problem with 'libcurl' and 'curl' method. However, I have not tried it with 'httr'. One way to do that with 'httr' only for that session is as follows:
library(httr)
set_config(use_proxy(url="abc.com",port=8080, username="username", password="password"))
You need to substitute settings specific to your n/w in relevant fields.
First check the default-jdk
package, good chance it already provide you an OpenJDK >= 11
.
ref: https://packages.ubuntu.com/search?keywords=default-jdk&searchon=names&suite=all§ion=all
So starting from Ubuntu 18.04 LTS it should be ok.
sudo apt update -qq
sudo apt install -yq default-jdk
note: don't forget to set JAVA_HOME
export JAVA_HOME=/usr/lib/jvm/default-java
mvn -version
For Ubuntu 16.04 LTS, only openjdk-8-jdk
is provided in the official repos so you need to find it in a ppa:
sudo add-apt-repository -y ppa:openjdk-r/ppa
sudo apt update -qq
sudo apt install -yq openjdk-11-jdk
note: don't forget to set JAVA_HOME
export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64
mvn -version
There is a solution:
<resources>
<item name="text_line_spacing" format="float" type="dimen">1.0</item>
</resources>
In this way, your float number will be under @dimen. Notice that you can use other "format" and/or "type" modifiers, where format stands for:
Format = enclosing data type:
and type stands for:
Type = resource type (referenced with R.XXXXX.name):
To fetch resource from code, you should use this snippet:
TypedValue outValue = new TypedValue();
getResources().getValue(R.dimen.text_line_spacing, outValue, true);
float value = outValue.getFloat();
I know that this is confusing (you'd expect call like getResources().getDimension(R.dimen.text_line_spacing)
), but Android dimensions
have special treatment and pure "float" number is not valid dimension.
Additionally, there is small "hack" to put float number into dimension, but be WARNED that this is really hack, and you are risking chance to lose float range and precision.
<resources>
<dimen name="text_line_spacing">2.025px</dimen>
</resources>
and from code, you can get that float by
float lineSpacing = getResources().getDimension(R.dimen.text_line_spacing);
in this case, value of lineSpacing
is 2.024993896484375
, and not 2.025
as you would expected.
From SQLServer 2012 more elegant alter role:
use mydb
go
ALTER ROLE db_datareader
ADD MEMBER MYUSER
go
ALTER ROLE db_datawriter
ADD MEMBER MYUSER
go
Your best bet would be to use a port of the CSS processor you use.
I'm a big fan of SASS so I currently use https://github.com/thomas-mcdonald/bootstrap-sass
It looks like there's a fork for Stylus here: https://github.com/Acquisio/bootstrap-stylus
Otherwise, Search & Replace is your best friend right in the css version...
I've been frustrated by this problem as well. Find/Replace can be helpful though, because if you don't put anything in the "replace" field it will replace with an -actual- NULL. So the steps would be something along the lines of:
1: Place some unique string in your formula in place of the NULL output (i like to use a password-like string)
2: Run your formula
3: Open Find/Replace, and fill in the unique string as the search value. Leave "replace with" blank
4: Replace All
Obviously, this has limitations. It only works when the context allows you to do a find/replace, so for more dynamic formulas this won't help much. But, I figured I'd put it up here anyway.
As of January 2021, these are the event-related packages available on PyPI, ordered by most recent release date.
0.3.0
: Nov 20204.5.0
: Sept 20200.1.31
: Aug 20201.0.1
: June 20200.13.1
: June 2020 (beta)2.0
: Sept 20194.0.3
: Jan 20190.2.3a0
: 20180.0.5
: 20182.1.2
: 20170.0.7
: 20161.4
: 20152.0.5
: 20151.0
: 20120.3.1
: 2008That's a lot of libraries to choose from, using very different terminology (events, signals, handlers, method dispatch, hooks, ...).
I'm trying to keep an overview of the above packages, plus the techniques mentioned in the answers here.
First, some terminology...
The most basic style of event system is the 'bag of handler methods', which is a simple implementation of the Observer pattern.
Basically, the handler methods (callables) are stored in an array and are each called when the event 'fires'.
The disadvantage of Observer event systems is that you can only register the handlers on the actual Event object (or handlers list). So at registration time the event already needs to exist.
That's why the second style of event systems exists: the publish-subscribe pattern. Here, the handlers don't register on an event object (or handler list), but on a central dispatcher. Also the notifiers only talk to the dispatcher. What to listen for, or what to publish is determined by 'signal', which is nothing more than a name (string).
Might be of interest as well: the Mediator pattern.
A 'hook' system is usally used in the context of application plugins. The application contains fixed integration points (hooks), and each plugin may connect to that hook and perform certain actions.
Note: threading.Event is not an 'event system' in the above sense. It's a thread synchronization system where one thread waits until another thread 'signals' the Event object.
Network messaging libraries often use the term 'events' too; sometimes these are similar in concept; sometimes not. They can of course traverse thread-, process- and computer boundaries. See e.g. pyzmq, pymq, Twisted, Tornado, gevent, eventlet.
In Python, holding a reference to a method or object ensures that it won't get deleted by the garbage collector. This can be desirable, but it can also lead to memory leaks: the linked handlers are never cleaned up.
Some event systems use weak references instead of regular ones to solve this.
Observer-style event systems:
list
.set
instead of a list
to store the bag, and implements __call__
which are both reasonable additions.pydispatch.Dispatcher
.Publish-subscribe libraries:
Others:
pytest
plugins.QObject
.Note that if you want to rebuild the MYI file then the correct use of REPAIR TABLE is:
REPAIR TABLE sometable USE_FRM;
Otherwise you will probably just get another error.
Just to mention, you can also use the default a theme like android.R.style.Theme_DeviceDefault_Light_Dialog
instead.
new DatePickerDialog(MainActivity.this, android.R.style.Theme_DeviceDefault_Light_Dialog, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//DO SOMETHING
}
}, 2015, 02, 26).show();
For me the following worked on Jenkins 2.190.1 and was much simpler than some of the other workarounds:
matcher = manager.getLogMatcher('^.*Text we want comes next: (.*)$');
if (matcher.matches()) {
def myVar = matcher.group(1);
def envVar = new EnvVars([MY_ENV_VAR: myVar]);
def newEnv = Environment.create(envVar);
manager.build.environments.add(0, newEnv);
// now the matched text from the LogMatcher is passed to an
// env var we can access at $MY_ENV_VAR in post build steps
}
This was using the Groovy Script plugin with no additional changes to Jenkins.
Generally you compile most .c files in the following way:
gcc foo.c -o foo. It might vary depending on what #includes you used or if you have any external .h files. Generally, when you have a C file, it looks somewhat like the following:
#include <stdio.h>
/* any other includes, prototypes, struct delcarations... */
int main(){
*/ code */
}
When I get an 'undefined reference to main', it usually means that I have a .c file that does not have int main()
in the file. If you first learned java, this is an understandable manner of confusion since in Java, your code usually looks like the following:
//any import statements you have
public class Foo{
int main(){}
}
I would advise looking to see if you have int main()
at the top.
I'm posting this answer to give insights into multiple ways available for you to change the project on GCP. I will also explain when to use each of the following options.
Option 1: Cloud CLI - Set Project Property on Cloud SDK on CLI
Use this option, if you want to run all Cloud CLI commands on a specific project.
gcloud config set project <Project-ID>
With this, the selected project on Cloud CLI
will change, and the currently selected project is highlighted in yellow.
Option 2: Cloud CLI - Set Project ID flag with most Commands
Use this command if you want to execute commands on multiple projects. Eg: create clusters in one project, and use the same configs to create on another project. Use the following flag for each command.
--project <Project-ID>
Option 3: Cloud CLI - Initialize the Configurations in CLI
This option can be used if you need separate configurations for different projects/accounts. With this, you can easily switch between configurations by using the activate
command. Eg: gcloud config configurations activate <congif-name>
.
gcloud init
Option 4: Open new Cloud Shell with your preferred project
This is preferred if you don't like to work with CLI commands. Press the PLUS +
button for a new tab.
Next, select your preferred project.
I think sim serial Number and sim number is unique. You can try this for get sim serial number and get sim number and Don't forget to add permission in manifest file.
TelephonyManager telemamanger = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String getSimSerialNumber = telemamanger.getSimSerialNumber();
String getSimNumber = telemamanger.getLine1Number();
And add below permission into your Androidmanifest.xml
file.
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Let me know if there is any issue.
Alternative solution is to modify your current Visual Studio installation in the Visual Studio Installer
Win+R %ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vs_installer.exe
adding the Blend for Visual Studio SDK for .NET
'Individual component' under 'SDKs, libraries, and frameworks':
after adding this component System.Windows.Interactivity
should appear in its regular location Add Reference/Assemblies/Extensions
.
It appears this would only work for VS2017 or earlier. For later versions, please refer to other answers.
Create xml file like edit_text_design.xml and save it to your drawable folder
i have given the Color codes According to my Choice, Please Change Color Codes As per your Choice !
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape>
<solid android:color="#c2c2c2" />
</shape>
</item>
<!-- main color -->
<item
android:bottom="1.5dp"
android:left="1.5dp"
android:right="1.5dp">
<shape>
<solid android:color="#000" />
</shape>
</item>
<!-- draw another block to cut-off the left and right bars -->
<item android:bottom="5.0dp">
<shape>
<solid android:color="#000" />
</shape>
</item>
</layer-list>
your Edit Text Should contain it as Background :
add android:background="@drawable/edit_text_design" to all of your EditText's
and your above EditText should now look like this:
<EditText
android:id="@+id/name_edit_text"
android:background="@drawable/edit_text_design"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/profile_image_view_layout"
android:layout_centerHorizontal="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="20dp"
android:ems="15"
android:hint="@string/name_field"
android:inputType="text" />
As aditional information on @Quentin answer, and as he rightly says,
background
CSS property itself, is a shorthand for:
background-color
background-image
background-repeat
background-attachment
background-position
That's mean, you can group all styles in one, like:
background: red url(../img.jpg) 0 0 no-repeat fixed;
This would be (in this example):
background-color: red;
background-image: url(../img.jpg);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: 0 0;
So... when you set: background:none;
you are saying that all the background properties are set to none...
You are saying that background-image: none;
and all the others to the initial
state (as they are not being declared).
So, background:none;
is:
background-color: initial;
background-image: none;
background-repeat: initial;
background-attachment: initial;
background-position: initial;
Now, when you define only the color (in your case transparent
) then you are basically saying:
background-color: transparent;
background-image: initial;
background-repeat: initial;
background-attachment: initial;
background-position: initial;
I repeat, as @Quentin rightly says the default
transparent
and none
values in this case are the same, so in your example and for your original question, No, there's no difference between them.
But!.. if you say background:none
Vs background:red
then yes... there's a big diference, as I say, the first would set all properties to none/default
and the second one, will only change the color
and remains the rest in his default
state.
Short answer: No, there's no difference at all (in your example and orginal question)
Long answer: Yes, there's a big difference, but depends directly on the properties granted to attribute.
default
)Initial value the concatenation of the initial values of its longhand properties:
background-image: none
background-position: 0% 0%
background-size: auto auto
background-repeat: repeat
background-origin: padding-box
background-style: is itself a shorthand, its initial value is the concatenation of its own longhand properties
background-clip: border-box
background-color: transparent
background
descriptions hereUpd2: Clarify better the background:none;
specification.
How are you generating your data?
See how the output shows that your data is of 'object' type? the groupby operations specifically check whether each column is a numeric dtype first.
In [31]: data
Out[31]:
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 2557 entries, 2004-01-01 00:00:00 to 2010-12-31 00:00:00
Freq: <1 DateOffset>
Columns: 360 entries, -89.75 to 89.75
dtypes: object(360)
look ?
Did you initialize an empty DataFrame first and then filled it? If so that's probably why it changed with the new version as before 0.9 empty DataFrames were initialized to float type but now they are of object type. If so you can change the initialization to DataFrame(dtype=float)
.
You can also call frame.astype(float)
According to Authentication on google: OAuth2 keeps returning 'invalid_grant'
"You should reuse the access token you get after the first successful authentication. You will get an invalid_grant error if your previous token has not expired yet. Cache it somewhere so you can reuse it."
hope it helps
If you need to pass $_GET
, $_REQUEST
, $_POST
, or anything else you can also use PHP interactive mode:
php -a
Then type:
<?php
$_GET['a']=1;
$_POST['b']=2;
include("/somefolder/some_file_path.php");
This will manually set any variables you want and then run your php file with those variables set.
To remove one or more columns by name, when the column names are known (as opposed to being determined at run-time), I like the subset()
syntax. E.g. for the data-frame
df <- data.frame(a=1:3, d=2:4, c=3:5, b=4:6)
to remove just the a
column you could do
Data <- subset( Data, select = -a )
and to remove the b
and d
columns you could do
Data <- subset( Data, select = -c(d, b ) )
You can remove all columns between d
and b
with:
Data <- subset( Data, select = -c( d : b )
As I said above, this syntax works only when the column names are known. It won't work when say the column names are determined programmatically (i.e. assigned to a variable). I'll reproduce this Warning from the ?subset
documentation:
Warning:
This is a convenience function intended for use interactively. For programming it is better to use the standard subsetting functions like '[', and in particular the non-standard evaluation of argument 'subset' can have unanticipated consequences.
Use this ..
$str = rawurldecode($_SERVER['REQUEST_URI']);
$arr = explode("{",$str);
$arr1 = explode("}", $arr[1]);
$jsS = '{'.$arr1[0].'}';
$data = json_decode($jsS,true);
Now ..
use $data['elemname']
to access the values.
send jsonp request with JSON Object.
Request format :
$.ajax({
method : 'POST',
url : 'xxx.com',
data : JSONDataObj, //Use JSON.stringfy before sending data
dataType: 'jsonp',
contentType: 'application/json; charset=utf-8',
success : function(response){
console.log(response);
}
})
Just put the following code for jQuery :
jQuery("input:radio").removeAttr("checked");
And for javascript :
$("input:radio").removeAttr("checked");
There is no need to put any foreach loop , .each() fubction or any thing
Here's a better option:
git remote set-head -a origin
From the documentation:
With -a, the remote is queried to determine its HEAD, then $GIT_DIR/remotes//HEAD is set to the same branch. e.g., if the remote HEAD is pointed at next, "git remote set-head origin -a" will set $GIT_DIR/refs/remotes/origin/HEAD to refs/remotes/origin/next. This will only work if refs/remotes/origin/next already exists; if not it must be fetched first.
This has actually been around quite a while (since v1.6.3); not sure how I missed it!
try this type of format:
SELECT to_char(sysdate,'dd-mm-rrrr') FROM dual
Here a simple function that use variable arguments:
final static
public int[] merge(final int[] ...arrays ) {
int size = 0;
for ( int[] a: arrays )
size += a.length;
int[] res = new int[size];
int destPos = 0;
for ( int i = 0; i < arrays.length; i++ ) {
if ( i > 0 ) destPos += arrays[i-1].length;
int length = arrays[i].length;
System.arraycopy(arrays[i], 0, res, destPos, length);
}
return res;
}
To use:
int[] array1 = {1,2,3};
int[] array2 = {4,5,6};
int[] array3 = {7,8,9};
int[] array1and2and3 = merge(array1, array2, array3);
for ( int x: array1and2and3 )
System.out.print( String.format("%3d", x) );
In your Case you can write the following jquery code:
$(document).ready(function(){
$('.staff_on_site').click(function(){
var rBtnVal = $(this).val();
if(rBtnVal == "yes"){
$("#no_of_staff").attr("readonly", false);
}
else{
$("#no_of_staff").attr("readonly", true);
}
});
});
Here is the Fiddle: http://jsfiddle.net/P4QWx/3/
package article14;
import java.io.File;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.util.PDFMergerUtility;
public class Pdf
{
public static void main(String args[])
{
new Pdf().createNew();
new Pdf().combine();
}
public void combine()
{
try
{
PDFMergerUtility mergePdf = new PDFMergerUtility();
String folder ="pdf";
File _folder = new File(folder);
File[] filesInFolder;
filesInFolder = _folder.listFiles();
for (File string : filesInFolder)
{
mergePdf.addSource(string);
}
mergePdf.setDestinationFileName("Combined.pdf");
mergePdf.mergeDocuments();
}
catch(Exception e)
{
}
}
public void createNew()
{
PDDocument document = null;
try
{
String filename="test.pdf";
document=new PDDocument();
PDPage blankPage = new PDPage();
document.addPage( blankPage );
document.save( filename );
}
catch(Exception e)
{
}
}
}
The problem is the length of the filenames. The first filename is only 7 chars long, so the tab occurs at char 8 (doing a tab after every 4 characters). However the next filenames are 8 chars long, so the next tab won't be until char 12. And if you had filenames longer than 11 chars, you'd run into the same problem again.
I had the same problem with foo.new
being set to null
for rows of foo
that had no matching key in bar
. I did something like this in Oracle:
update foo set foo.new = (select bar.new from bar where foo.key = bar.key) where exists (select 1 from bar where foo.key = bar.key)
fix function declaration on
int nonrecursivecountcells(color grid[ROW_SIZE][COL_SIZE], int row, int column)
the .data()
method is from jQuery. If you want to use this method you need to include the jQuery library and access the method like this:
function doStuff(item) {
var id = $(item).data('id');
}
I also updated your jsFiffle
UPDATE
with pure angularjs and the jqlite you can achieve the goal like this:
function doStuff(item) {
var id = angular.element(item).data('id');
}
You must not access the element with []
because then you get the pure DOM element without all the jQuery or jqlite extra methods.
You can overwrite your default activity animation and it perform better than overridePendingTransition. I use this solution that work for every android version. Just copy paste 4 files and add a 4 lines style as below:
Create a "CustomActivityAnimation" and add this to your base Theme by "windowAnimationStyle".
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorPrimary</item>
<item name="android:windowAnimationStyle">@style/CustomActivityAnimation</item>
</style>
<style name="CustomActivityAnimation" parent="@android:style/Animation.Activity">
<item name="android:activityOpenEnterAnimation">@anim/slide_in_right</item>
<item name="android:activityOpenExitAnimation">@anim/slide_out_left</item>
<item name="android:activityCloseEnterAnimation">@anim/slide_in_left</item>
<item name="android:activityCloseExitAnimation">@anim/slide_out_right</item>
</style>
Then Create anim folder under res folder and then create this four animation files into anim folder:
slide_in_right.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="100%p" android:toXDelta="0"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
slide_out_left.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="0" android:toXDelta="-100%p"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
slide_in_left.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="-100%p" android:toXDelta="0"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
slide_out_right.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="0" android:toXDelta="100%p"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
If you face any problem then you can download my sample project from github.
Thanks
I always come to this question when I hit an error in the test environment and remember, "I've done this before, but I can do it straight in the web.config without having to modify code and re-deploy to the test environment, but it takes 2 changes... what was it again?"
For future reference
<system.web>
<customErrors mode="Off"></customErrors>
</system.web>
AND
<system.webServer>
<httpErrors errorMode="Detailed" existingResponse="PassThrough"></httpErrors>
</system.webServer>
str.startswith
allows you to supply a tuple of strings to test for:
if link.lower().startswith(("js", "catalog", "script", "katalog")):
From the docs:
str.startswith(prefix[, start[, end]])
Return
True
if string starts with theprefix
, otherwise returnFalse
.prefix
can also be a tuple of prefixes to look for.
Below is a demonstration:
>>> "abcde".startswith(("xyz", "abc"))
True
>>> prefixes = ["xyz", "abc"]
>>> "abcde".startswith(tuple(prefixes)) # You must use a tuple though
True
>>>
VERY IMPORTANT Additional info on difference between .text() and .html():
If your selector selects more than one item, e.g you have two spans like so
<span class="foo">bar1</span>
<span class="foo">bar2</span>
,
then
$('.foo').text();
appends the two texts and give you that; whereas
$('.foo').html();
gives you only one of those.
tar -czvf mydir.tgz -C my_dir/ `ls -A mydir`
Run it one level above mydir. This won't include any [.] or stuff.
See https://stackoverflow.com/a/12900859/104891.
First of all, set the language level
/release versions
in pom.xml
like that:
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
Maven sets the default to 1.5 otherwise. You will also need to include the maven-compiler-plugin
if you haven't already:
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
</dependency>
Also, try to change the Java version in each of these places:
File -> Project structure -> Project -> Project SDK -> 11.
File -> Project structure -> Project -> Project language level -> 11.
File -> Project structure -> Project -> Modules -> -> Sources --> 11
In project -> ctrl + alt + s -> Build, Execution, Deployment -> Compiler -> Java Compiler -> Project bytecode version -> 11
In project -> ctrl + alt + s -> Build, Execution, Deployment -> Compiler -> Java Compiler -> Module -> 1.11.
You need to unicode each element of the list individually
[x.encode('utf-8') for x in tmp]
I was recently struggling with a similar problem. It turned out that the database was missing indexes on foreign keys. That caused Oracle to lock many more records than required which quickly led to a deadlock during high concurrency.
Here is an excellent article with lots of good detail, suggestions, and details about how to fix a deadlock: http://www.oratechinfo.co.uk/deadlocks.html#unindex_fk
super()
(without arguments) was introduced in Python 3 (along with __class__
):
super() -> same as super(__class__, self)
so that would be the Python 2 equivalent for new-style classes:
super(CurrentClass, self)
for old-style classes you can always use:
class Classname(OldStyleParent):
def __init__(self, *args, **kwargs):
OldStyleParent.__init__(self, *args, **kwargs)
Example code for node.js - async function to sync function:
var deasync = require('deasync');
function syncFunc()
{
var ret = null;
asyncFunc(function(err, result){
ret = {err : err, result : result}
});
while((ret == null))
{
deasync.runLoopOnce();
}
return (ret.err || ret.result);
}
Alternatively, you may also want to check by the .size() method. The list that isn't empty will have a size more than zero
if (numbers.size()>0){
//execute your code
}
Before jumping into any further error checking please first check whether its
document.getElementsByClassName() itself.
double check its getElements and not getElement
The :query_string_normalizer
option is also available, which will override the default normalizer HashConversions.to_params(query)
query_string_normalizer: ->(query){query.to_json}
If you're getting this error with react native, it may be due to a link to an NPM package that you removed (as it was in my case). After removing references to it in the settings.gradle and build.gradle files, I cleaned and rebuilt and it's as good as new :)
Try this maybe :
Bootply : http://www.bootply.com/106527
Js :
$('input').on('click', function(){
var valeur = 0;
$('input:checked').each(function(){
if ( $(this).attr('value') > valeur )
{
valeur = $(this).attr('value');
}
});
$('.progress-bar').css('width', valeur+'%').attr('aria-valuenow', valeur);
});
HTML :
<div class="progress progress-striped active">
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
</div>
</div>
<div class="row tasks">
<div class="col-md-6">
<p><span>Identify your campaign audience.</span>Who are we talking to here? Understand your buyer persona before launching into a campaign, so you can target them correctly.</p>
</div>
<div class="col-md-2">
<label>2014-01-29</label>
</div>
<div class="col-md-2">
<input name="progress" class="progress" type="checkbox" value="10">
</div>
<div class="col-md-2">
<input name="done" class="done" type="checkbox" value="20">
</div>
</div><!-- tasks -->
<div class="row tasks">
<div class="col-md-6">
<p><span>Set your goals + benchmarks</span>Having SMART goals can help you be
sure that you’ll have tangible results to share with the world (or your
boss) at the end of your campaign.</p>
</div>
<div class="col-md-2">
<label>2014-01-25</label>
</div>
<div class="col-md-2">
<input name="progress" class="progress" type="checkbox" value="30">
</div>
<div class="col-md-2">
<input name="done" class="done" type="checkbox" value="40">
</div>
</div><!-- tasks -->
Css
.tasks{
background-color: #F6F8F8;
padding: 10px;
border-radius: 5px;
margin-top: 10px;
}
.tasks span{
font-weight: bold;
}
.tasks input{
display: block;
margin: 0 auto;
margin-top: 10px;
}
.tasks a{
color: #000;
text-decoration: none;
border:none;
}
.tasks a:hover{
border-bottom: dashed 1px #0088cc;
}
.tasks label{
display: block;
text-align: center;
}
$(function(){_x000D_
$('input').on('click', function(){_x000D_
var valeur = 0;_x000D_
$('input:checked').each(function(){_x000D_
if ( $(this).attr('value') > valeur )_x000D_
{_x000D_
valeur = $(this).attr('value');_x000D_
}_x000D_
});_x000D_
$('.progress-bar').css('width', valeur+'%').attr('aria-valuenow', valeur); _x000D_
});_x000D_
_x000D_
});
_x000D_
.tasks{_x000D_
background-color: #F6F8F8;_x000D_
padding: 10px;_x000D_
border-radius: 5px;_x000D_
margin-top: 10px;_x000D_
}_x000D_
.tasks span{_x000D_
font-weight: bold;_x000D_
}_x000D_
.tasks input{_x000D_
display: block;_x000D_
margin: 0 auto;_x000D_
margin-top: 10px;_x000D_
}_x000D_
.tasks a{_x000D_
color: #000;_x000D_
text-decoration: none;_x000D_
border:none;_x000D_
}_x000D_
.tasks a:hover{_x000D_
border-bottom: dashed 1px #0088cc;_x000D_
}_x000D_
.tasks label{_x000D_
display: block;_x000D_
text-align: center;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="progress progress-striped active">_x000D_
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">_x000D_
</div>_x000D_
</div>_x000D_
<div class="row tasks">_x000D_
<div class="col-md-6">_x000D_
<p><span>Identify your campaign audience.</span>Who are we talking to here? Understand your buyer persona before launching into a campaign, so you can target them correctly.</p>_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<label>2014-01-29</label>_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<input name="progress" class="progress" type="checkbox" value="10">_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<input name="done" class="done" type="checkbox" value="20">_x000D_
</div>_x000D_
</div><!-- tasks -->_x000D_
_x000D_
<div class="row tasks">_x000D_
<div class="col-md-6">_x000D_
<p><span>Set your goals + benchmarks</span>Having SMART goals can help you be_x000D_
sure that you’ll have tangible results to share with the world (or your_x000D_
boss) at the end of your campaign.</p>_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<label>2014-01-25</label>_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<input name="progress" class="progress" type="checkbox" value="30">_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<input name="done" class="done" type="checkbox" value="40">_x000D_
</div>_x000D_
</div><!-- tasks -->
_x000D_
int lcmcal(int i,int y)
{
int n,x,s=1,t=1;
for(n=1;;n++)
{
s=i*n;
for(x=1;t<s;x++)
{
t=y*x;
}
if(s==t)
break;
}
return(s);
}
Woo-hoo! It works with some hack!
According to this comment you need to:
Manually edit Microsoft.CSharp.DesignTime.targets
located in C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\VisualStudio\Managed
(for VS Community edition, modify path for other editions), append ClassDesigner
value to ProjectCapability
(right pane):
Restart VS.
MyClasses.cd
with following content:
<?xml version="1.0" encoding="utf-8"?>
<ClassDiagram MajorVersion="1" MinorVersion="1">
<Font Name="Segoe UI" Size="9" />
</ClassDiagram>
Bingo. Now you may open this file in VS. You will see error message "Object reference not set to an instance of object" once after VS starts, but diagram works.
Checked on VS 2017 Community Edition, v15.3.0 with .NETCore 2.0 app/project:
GitHub issue expected to fix in v15.5
While searching for a solution to this problem, I found a variation on GONeale's answer through Patrick Desjardins' blog:
public int Update(T entity, Expression<Func<T, object>>[] properties)
{
DatabaseContext.Entry(entity).State = EntityState.Unchanged;
foreach (var property in properties)
{
var propertyName = ExpressionHelper.GetExpressionText(property);
DatabaseContext.Entry(entity).Property(propertyName).IsModified = true;
}
return DatabaseContext.SaveChangesWithoutValidation();
}
"As you can see, it takes as its second parameter an expression of a function. This will let use this method by specifying in a Lambda expression which property to update."
...Update(Model, d=>d.Name);
//or
...Update(Model, d=>d.Name, d=>d.SecondProperty, d=>d.AndSoOn);
( A somewhat similar solution is also given here: https://stackoverflow.com/a/5749469/2115384 )
The method I am currently using in my own code, extended to handle also (Linq) Expressions of type ExpressionType.Convert
. This was necessary in my case, for example with Guid
and other object properties. Those were 'wrapped' in a Convert() and therefore not handled by System.Web.Mvc.ExpressionHelper.GetExpressionText
.
public int Update(T entity, Expression<Func<T, object>>[] properties)
{
DbEntityEntry<T> entry = dataContext.Entry(entity);
entry.State = EntityState.Unchanged;
foreach (var property in properties)
{
string propertyName = "";
Expression bodyExpression = property.Body;
if (bodyExpression.NodeType == ExpressionType.Convert && bodyExpression is UnaryExpression)
{
Expression operand = ((UnaryExpression)property.Body).Operand;
propertyName = ((MemberExpression)operand).Member.Name;
}
else
{
propertyName = System.Web.Mvc.ExpressionHelper.GetExpressionText(property);
}
entry.Property(propertyName).IsModified = true;
}
dataContext.Configuration.ValidateOnSaveEnabled = false;
return dataContext.SaveChanges();
}
To retrieve data from database:
private SqlConnection Conn;
private void CreateConnection()
{
string ConnStr =
ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
Conn = new SqlConnection(ConnStr);
}
public DataTable getData()
{
CreateConnection();
string SqlString = "SELECT * FROM TableName WHERE SomeID = @SomeID;";
SqlDataAdapter sda = new SqlDataAdapter(SqlString, Conn);
DataTable dt = new DataTable();
try
{
Conn.Open();
sda.Fill(dt);
}
catch (SqlException se)
{
DBErLog.DbServLog(se, se.ToString());
}
finally
{
Conn.Close();
}
return dt;
}
The question does not mention the VM Provider but in my case, I use Virtual Box under the same environment. There is an option in the Virtual Box GUI that I needed to enable in order to make it work. Is located in the Virtual Box app preferences: File >> Preferences... >> Proxy. Once I configured this, I was able to work without problems. Hope this tip can also help you guys.
After trying a skeleton project called "jsf-blank", which did not demonstrate this problem with xhtml files; I concluded that there was an unknown problem in my project. My solution may not have been too elegant, but it saved time. I backed up the code and other files I'd already developed, deleted the project, and started over - recreated the project. So far, I've added back most of the files and it looks pretty good.
create or replace procedure point_triangle
AS
BEGIN
FOR thisteam in (select FIRSTNAME,LASTNAME,SUM(PTS) from PLAYERREGULARSEASON where TEAM = 'IND' group by FIRSTNAME, LASTNAME order by SUM(PTS) DESC)
LOOP
dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.PTS);
END LOOP;
END;
/
In case of plotting time series, the command ts.plot
requires a different argument than xaxt="n"
require(graphics)
ts.plot(ldeaths, mdeaths, xlab="year", ylab="deaths", lty=c(1:2), gpars=list(xaxt="n"))
axis(1, at = seq(1974, 1980, by = 2))
Because when you call $( "#form_id" ).submit();
it triggers the external submit handler which prevents the default action, instead use
$( "#form_id" )[0].submit();
or
$form.submit();//declare `$form as a local variable by using var $form = this;
When you call the dom element's submit method programatically, it won't trigger the submit handlers attached to the element
Google brought me here with a very similar problem, I finally figured out a solution that fits my needs, it might help someone else too...
I used this formula:
=IFERROR(MID(Q2, FIND("{",Q2), FIND("}",Q2) - FIND("{",Q2) + 1), "")
Had the same problem, and the blueimp guy says "maxFileSize and acceptFileTypes are only supported by the UI version" and has provided a (broken) link to incorporate the _validate and _hasError methods.
So without knowing how to incorporate those methods without messing up the script I wrote this little function. It seems to work for me.
Just add this
add: function(e, data) {
var uploadErrors = [];
var acceptFileTypes = /^image\/(gif|jpe?g|png)$/i;
if(data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) {
uploadErrors.push('Not an accepted file type');
}
if(data.originalFiles[0]['size'].length && data.originalFiles[0]['size'] > 5000000) {
uploadErrors.push('Filesize is too big');
}
if(uploadErrors.length > 0) {
alert(uploadErrors.join("\n"));
} else {
data.submit();
}
},
at the start of the .fileupload options as shown in your code here
$(document).ready(function () {
'use strict';
$('#fileupload').fileupload({
add: function(e, data) {
var uploadErrors = [];
var acceptFileTypes = /^image\/(gif|jpe?g|png)$/i;
if(data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) {
uploadErrors.push('Not an accepted file type');
}
if(data.originalFiles[0]['size'].length && data.originalFiles[0]['size'] > 5000000) {
uploadErrors.push('Filesize is too big');
}
if(uploadErrors.length > 0) {
alert(uploadErrors.join("\n"));
} else {
data.submit();
}
},
dataType: 'json',
autoUpload: false,
// acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
// maxFileSize: 5000000,
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p style="color: green;">' + file.name + '<i class="elusive-ok" style="padding-left:10px;"/> - Type: ' + file.type + ' - Size: ' + file.size + ' byte</p>')
.appendTo('#div_files');
});
},
fail: function (e, data) {
$.each(data.messages, function (index, error) {
$('<p style="color: red;">Upload file error: ' + error + '<i class="elusive-remove" style="padding-left:10px;"/></p>')
.appendTo('#div_files');
});
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .bar').css('width', progress + '%');
}
});
});
You'll notice I added a filesize function in there as well because that will also only work in the UI version.
Updated to get past issue suggested by @lopsided: Added data.originalFiles[0]['type'].length
and data.originalFiles[0]['size'].length
in the queries to make sure they exist and are not empty first before testing for errors. If they don't exist, no error will be shown and it will only rely on your server side error testing.
For the 24-hour time, you need to use HH24
instead of HH
.
For the 12-hour time, the AM/PM indicator is written as A.M.
(if you want periods in the result) or AM
(if you don't). For example:
SELECT invoice_date,
TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
FROM invoices
;
For more information on the format models you can use with TO_CHAR
on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.
I encountered a similar error. It was a noob mistake done in a hurry. Integer array without declaring size int a[] then trying to access it. C++ compiler should've caught such an error easily if it were in main. However since this particular int array was declared inside an object, it was being created at the same time as my object (many objects were being created) and the compiler was throwing a free(): invalid next size(normal) error. I thought of 2 explanations for this (please enlighten me if anyone knows more): 1.) This resulted in some random memory being assigned to it but since this wasn't accessible it was freeing up all the other heap memory just trying to find this int. 2.) The memory required by it was practically infinite for a program and to assign this it was freeing up all other memory.
A simple:
int* a;
class foo{
foo(){
for(i=0;i<n;i++)
a=new int[i];
}
Solved the problem. But it did take a lot of time trying to debug this because the compiler could not "really" find the error.
These are the versions of C# known about at the time of this writing:
Dispose
on IEnumerator
s which implemented IDisposable
. A few other small features.var
), query expressionsdynamic
), delegate and interface generic variance, more COM support, named arguments, tuple data type and optional parametersawait
in catch
and finally
, extension Add
methods in collection initializers.out
parameter declarations, local functions, binary literals, digit separators, and arbitrary async returns.unmanaged
generic type constraints. ref
reassignment. Unsafe improvements: stackalloc
initialization, unpinned indexed fixed
buffers, custom fixed
statements. Improved overloading resolution. Expression variables in initializers and queries. ==
and !=
defined for tuples. Auto-properties' backing fields can now be targeted by attributes.new
expressions, target typed ??
and ?
), covariant returns. Minor features: relax ordering of ref
and partial
modifiers, parameter null checking, lambda discard parameters, native int
s, attributes on local functions, function pointers, static lambdas, extension GetEnumerator
, module initializers, extending partial.What are the correct version numbers for C#? What came out when? Why can't I find any answers about C# 3.5?
There is no such thing as C# 3.5 - the cause of confusion here is that the C# 3.0 is present in .NET 3.5. The language and framework are versioned independently, however - as is the CLR, which is at version 2.0 for .NET 2.0 through 3.5, .NET 4 introducing CLR 4.0, service packs notwithstanding. The CLR in .NET 4.5 has various improvements, but the versioning is unclear: in some places it may be referred to as CLR 4.5 (this MSDN page used to refer to it that way, for example), but the Environment.Version
property still reports 4.0.xxx.
As of May 3, 2017, the C# Language Team created a history of C# versions and features on their GitHub repository: Features Added in C# Language Versions. There is also a page that tracks upcoming and recently implemented language features.
It is varchar
and not var_char
CREATE DATABASE IF NOT EXISTS courses;
USE courses;
CREATE TABLE IF NOT EXISTS teachers(
id INT(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
addr VARCHAR(255) NOT NULL,
phone INT NOT NULL
);
You should use a SQL tool to visualize possbile errors like MySQL Workbench.
// This solution provides a way programatically add a handler to the web service clien w/o the XML config
// See full doc here: http://docs.oracle.com/cd/E17904_01//web.1111/e13734/handlers.htm#i222476
// Create new class that implements SOAPHandler
public class LogMessageHandler implements SOAPHandler<SOAPMessageContext> {
@Override
public Set<QName> getHeaders() {
return Collections.EMPTY_SET;
}
@Override
public boolean handleMessage(SOAPMessageContext context) {
SOAPMessage msg = context.getMessage(); //Line 1
try {
msg.writeTo(System.out); //Line 3
} catch (Exception ex) {
Logger.getLogger(LogMessageHandler.class.getName()).log(Level.SEVERE, null, ex);
}
return true;
}
@Override
public boolean handleFault(SOAPMessageContext context) {
return true;
}
@Override
public void close(MessageContext context) {
}
}
// Programatically add your LogMessageHandler
com.csd.Service service = null;
URL url = new URL("https://service.demo.com/ResService.svc?wsdl");
service = new com.csd.Service(url);
com.csd.IService port = service.getBasicHttpBindingIService();
BindingProvider bindingProvider = (BindingProvider)port;
Binding binding = bindingProvider.getBinding();
List<Handler> handlerChain = binding.getHandlerChain();
handlerChain.add(new LogMessageHandler());
binding.setHandlerChain(handlerChain);
To put this folder on the PATH environment variable type
export PATH="$PATH:$HOME/.composer/vendor/bin"
This appends the folder to your existing PATH, however, it is only active for your current terminal session.
If you want it to be automatically set, it depends on the shell you are using. For bash, you can append this line to $HOME/.bashrc
using your favorite editor or type the following on the shell
echo 'export PATH="$PATH:$HOME/.composer/vendor/bin"' >> ~/.bashrc
In order to check if it worked, logout and login again or execute
source ~/.bashrc
on the shell.
PS: For other systems where there is no ~/.bashrc
, you can also put this into ~/.bash_profile
PSS: For more recent laravel you need to put $HOME/.config/composer/vendor/bin
on the PATH
.
PSSS: If you want to put this folder on the path also for other shells or on the GUI, you should append the said export
command to ~/.profile
(cf. https://help.ubuntu.com/community/EnvironmentVariables).
Thx Burhan Khalid, I overlooked your "You need to be root" quote, but found the way when you are not the root here.
At point 7 you need to use:
sudo env ORACLE_HOME=$ORACLE_HOME python setup.py install
Or
sudo env ORACLE_HOME=/path/to/instantclient python setup.py install
Connection in APPConfig
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=192.168.1.25;Initial Catalog=Login;Persist Security Info=True;User ID=sa;Password=example.com" providerName="System.Data.SqlClient" />
</connectionStrings>
In Class.Cs
public string ConnectionString
{
get
{
return System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
}
}
I wrote rabbitmq-dump-queue which allows dumping messages from a RabbitMQ queue to local files and requeuing the messages in their original order.
Example usage (to dump the first 50 messages of queue incoming_1
):
rabbitmq-dump-queue -url="amqp://user:[email protected]:5672/" -queue=incoming_1 -max-messages=50 -output-dir=/tmp
for C use /// in gcc.
#include <windows.h>
then use Sleep(); /// Sleep() with capital S. not sleep() with s .
//Sleep(1000) is 1 sec /// maybe.
clang supports sleep(), sleep(1) is for 1 sec time delay/wait.
Internet Explorer (under version 9) does not natively support rounded corners.
There's an amazing script that will magically add it for you: CSS3 PIE.
I've used it a lot of times, with amazing results.
Actually
{
@synchronized(self) {
return [[myString retain] autorelease];
}
}
transforms directly into:
// needs #import <objc/objc-sync.h>
{
objc_sync_enter(self)
id retVal = [[myString retain] autorelease];
objc_sync_exit(self);
return retVal;
}
This API available since iOS 2.0 and imported using...
#import <objc/objc-sync.h>
The fastest way to check if a string contains another string is using indexOf
:
if (code.indexOf('ST1') !== -1) {
// string code has "ST1" in it
} else {
// string code does not have "ST1" in it
}
I have same problem after update android studio to 1.5, and i fix it by update the gradle location,
Hope this method works for you,
Based on Dimitry Pavlov answere I would remove .ToList()
. And also avoid the anonymous class.
Instead I like to use a struct which does not require a heap memory allocation. (A ValueTuple
would also do job.)
public static IEnumerable<IEnumerable<TSource>> ChunkBy<TSource>(this IEnumerable<TSource> source, int chunkSize)
{
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
if (chunkSize <= 0)
{
throw new ArgumentOutOfRangeException(nameof(chunkSize), chunkSize, "The argument must be greater than zero.");
}
return source
.Select((x, i) => new ChunkedValue<TSource>(x, i / chunkSize))
.GroupBy(cv => cv.ChunkIndex)
.Select(g => g.Select(cv => cv.Value));
}
[StructLayout(LayoutKind.Auto)]
[DebuggerDisplay("{" + nameof(ChunkedValue<T>.ChunkIndex) + "}: {" + nameof(ChunkedValue<T>.Value) + "}")]
private struct ChunkedValue<T>
{
public ChunkedValue(T value, int chunkIndex)
{
this.ChunkIndex = chunkIndex;
this.Value = value;
}
public int ChunkIndex { get; }
public T Value { get; }
}
This can be used like the following which only iterates over the collection once and also does not allocate any significant memory.
int chunkSize = 30;
foreach (var chunk in collection.ChunkBy(chunkSize))
{
foreach (var item in chunk)
{
// your code for item here.
}
}
If a concrete list is actually needed then I would do it like this:
int chunkSize = 30;
var chunkList = new List<List<T>>();
foreach (var chunk in collection.ChunkBy(chunkSize))
{
// create a list with the correct capacity to be able to contain one chunk
// to avoid the resizing (additional memory allocation and memory copy) within the List<T>.
var list = new List<T>(chunkSize);
list.AddRange(chunk);
chunkList.Add(list);
}
You don't need to write a program to do this in Linux. Just pipe the serial port through netcat:
netcat www.example.com port </dev/ttyS0 >/dev/ttyS0
Just replace the address and port information. Also, you may be using a different serial port (i.e. change the /dev/ttyS0
part). You can use the stty or setserial commands to change the parameters of the serial port (baud rate, parity, stop bits, etc.).
If anyone is coming here looking to do this with Font Awesome Icons (like I was) view here: https://fontawesome.com/how-to-use/on-the-web/styling/icons-in-a-list
<ul class="fa-ul">
<li><i class="fa-li fa fa-check-square"></i>List icons</li>
<li><i class="fa-li fa fa-check-square"></i>can be used</li>
<li><i class="fa-li fa fa-spinner fa-spin"></i>as bullets</li>
<li><i class="fa-li fa fa-square"></i>in lists</li>
</ul>
The fa-ul
and fa-li
classes easily replace default bullets in unordered lists.
Your /home/gnu/bin/c++
seem to require additional flag to link things properly and CMake doesn't know about that.
To use /usr/bin/c++
as your compiler run cmake
with -DCMAKE_CXX_COMPILER=/usr/bin/c++
.
Also, CMAKE_PREFIX_PATH
variable sets destination dir where your project' files should be installed. It has nothing to do with CMake installation prefix and CMake itself already know this.
I was getting the same error when i ran:
jar cvfm test.jar Test.class Manifest.txt
What resolved it was this:
jar cvfm test.jar Manifest.txt Test.class
My manifest has the entry point as given in oracle docs (make sure there is a new line character at the end of the file):
Main-Class: Test
I had the exact same problem. Running mvn clean install
instead of mvn clean compile
resolved it.
The difference only occurs when using multi-maven-project since the project dependencies are uploaded to the local repository by using install.
Your if statements are checking for int values. raw_input
returns a string. Change the following line:
tSizeAns = raw_input()
to
tSizeAns = int(raw_input())
Use the time module:
epoch_time = int(time.time())
Yes we can change that but with some more attention
Now add this in your build.gradle in your project while make sure you have checked the build variant of your project like release or Debug
so here I have set my build variant as release
but you may select as Debug as well.
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig getSigningConfig()
applicationVariants.all { variant ->
variant.outputs.each { output ->
def date = new Date();
def formattedDate = date.format('yyyyMMddHHmmss')
output.outputFile = new File(output.outputFile.parent,
output.outputFile.name.replace("-release", "-" + formattedDate)
//for Debug use output.outputFile = new File(output.outputFile.parent,
// output.outputFile.name.replace("-debug", "-" + formattedDate)
)
}
}
}
}
You may Do it With different Approach Like this
defaultConfig {
applicationId "com.myapp.status"
minSdkVersion 16
targetSdkVersion 23
versionCode 1
versionName "1.0"
setProperty("archivesBaseName", "COMU-$versionName")
}
Using Set property method in build.gradle and Don't forget to sync the gradle before running the projects Hope It will solve your problem :)
A New approach to handle this added recently by google update You may now rename your build according to flavor or Variant output //Below source is from developer android documentation For more details follow the above documentation link
Using the Variant API to manipulate variant outputs is broken with the new plugin. It still works for simple tasks, such as changing the APK name during build time, as shown below:
// If you use each() to iterate through the variant objects,
// you need to start using all(). That's because each() iterates
// through only the objects that already exist during configuration time—
// but those object don't exist at configuration time with the new model.
// However, all() adapts to the new model by picking up object as they are
// added during execution.
android.applicationVariants.all { variant ->
variant.outputs.all {
outputFileName = "${variant.name}-${variant.versionName}.apk"
}
}
Renaming .aab bundle This is nicely answered by David Medenjak
tasks.whenTaskAdded { task ->
if (task.name.startsWith("bundle")) {
def renameTaskName = "rename${task.name.capitalize()}Aab"
def flavor = task.name.substring("bundle".length()).uncapitalize()
tasks.create(renameTaskName, Copy) {
def path = "${buildDir}/outputs/bundle/${flavor}/"
from(path)
include "app.aab"
destinationDir file("${buildDir}/outputs/renamedBundle/")
rename "app.aab", "${flavor}.aab"
}
task.finalizedBy(renameTaskName)
}
//@credit to David Medenjak for this block of code
}
Is there need of above code
What I have observed in the latest version of the android studio 3.3.1
The rename of .aab bundle is done by the previous code there don't require any task rename at all.
Hope it will help you guys. :)
I made code for imageview with pinch to zoom using zoomageview. so user can drag the image off the screen and zoom-In , zoom-out the image.
You can follow this link
to get the Step By Step
Code and also given Output Screenshot.
You can only have one ID per element, but you can indeed have more than one class. But don't have multiple class attributes, put multiple class values into one attribute.
<div id="foo" class="bar baz bax">
is perfectly legal.
If you happen to be working with a multidimensional array then you'll need to flatten and unravel the indices:
def largest_indices(ary, n):
"""Returns the n largest indices from a numpy array."""
flat = ary.flatten()
indices = np.argpartition(flat, -n)[-n:]
indices = indices[np.argsort(-flat[indices])]
return np.unravel_index(indices, ary.shape)
For example:
>>> xs = np.sin(np.arange(9)).reshape((3, 3))
>>> xs
array([[ 0. , 0.84147098, 0.90929743],
[ 0.14112001, -0.7568025 , -0.95892427],
[-0.2794155 , 0.6569866 , 0.98935825]])
>>> largest_indices(xs, 3)
(array([2, 0, 0]), array([2, 2, 1]))
>>> xs[largest_indices(xs, 3)]
array([ 0.98935825, 0.90929743, 0.84147098])
On a generic note, you can use a combination of ng-if
and ng-style
incorporate conditional changes with change in background image.
<span ng-if="selectedItem==item.id"
ng-style="{'background-image':'url(../images/'+'{{item.id}}'+'_active.png)','background-size':'52px 57px','padding-top':'70px','background-repeat':'no-repeat','background-position': 'center'}"></span>
<span ng-if="selectedItem!=item.id"
ng-style="{'background-image':'url(../images/'+'{{item.id}}'+'_deactivated.png)','background-size':'52px 57px','padding-top':'70px','background-repeat':'no-repeat','background-position': 'center'}"></span>
var tds = document.getElementById("ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a").getElementsByTagName("td");
time = tds[0].firstChild.value;
address = tds[3].firstChild.value;
yourEnum.ordinal()
EnumType.values()[someInt]
EnumType.valueOf(yourString)
yourEnum.name()
A side-note:
As you correctly point out, the ordinal()
may be "unstable" from version to version. This is the exact reason why I always store constants as strings in my databases. (Actually, when using MySql, I store them as MySql enums!)
If you are looking for content from different domain this will do the trick:
$.ajax({
url:'http://www.corsproxy.com/' +
'en.wikipedia.org/wiki/Briarcliff_Manor,_New_York',
type:'GET',
success: function(data){
$('#content').html($(data).find('#firstHeading').html());
}
});
The simplest way is to simply use the following line of jquery
, using this you don't get the /fakepath
nonsense, you straight up get the file that was uploaded:
$('input[type=file]')[0].files[0]; // This gets the file
$('#idOfFileUpload')[0].files[0]; // This gets the file with the specified id
Some other useful commands are:
To get the name of the file:
$('input[type=file]')[0].files[0].name; // This gets the file name
To get the type of the file:
If I were to upload a PNG, it would return image/png
$("#imgUpload")[0].files[0].type
To get the size (in bytes) of the file:
$("#imgUpload")[0].files[0].size
Also you don't have to use these commands on('change'
, you can get the values at any time, for instance you may have a file upload and when the user clicks upload
, you simply use the commands I listed.
Three Step Process for converting HTML into Plain Text
First You need to Install Nuget Package For HtmlAgilityPack Second Create This class
public class HtmlToText
{
public HtmlToText()
{
}
public string Convert(string path)
{
HtmlDocument doc = new HtmlDocument();
doc.Load(path);
StringWriter sw = new StringWriter();
ConvertTo(doc.DocumentNode, sw);
sw.Flush();
return sw.ToString();
}
public string ConvertHtml(string html)
{
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
StringWriter sw = new StringWriter();
ConvertTo(doc.DocumentNode, sw);
sw.Flush();
return sw.ToString();
}
private void ConvertContentTo(HtmlNode node, TextWriter outText)
{
foreach(HtmlNode subnode in node.ChildNodes)
{
ConvertTo(subnode, outText);
}
}
public void ConvertTo(HtmlNode node, TextWriter outText)
{
string html;
switch(node.NodeType)
{
case HtmlNodeType.Comment:
// don't output comments
break;
case HtmlNodeType.Document:
ConvertContentTo(node, outText);
break;
case HtmlNodeType.Text:
// script and style must not be output
string parentName = node.ParentNode.Name;
if ((parentName == "script") || (parentName == "style"))
break;
// get text
html = ((HtmlTextNode)node).Text;
// is it in fact a special closing node output as text?
if (HtmlNode.IsOverlappedClosingElement(html))
break;
// check the text is meaningful and not a bunch of whitespaces
if (html.Trim().Length > 0)
{
outText.Write(HtmlEntity.DeEntitize(html));
}
break;
case HtmlNodeType.Element:
switch(node.Name)
{
case "p":
// treat paragraphs as crlf
outText.Write("\r\n");
break;
}
if (node.HasChildNodes)
{
ConvertContentTo(node, outText);
}
break;
}
}
}
By using above class with reference to Judah Himango's answer
Third you need to create the Object of above class and Use ConvertHtml(HTMLContent)
Method for converting HTML into Plain Text rather than ConvertToPlainText(string html);
HtmlToText htt=new HtmlToText();
var plainText = htt.ConvertHtml(HTMLContent);
I use ubuntu 16.04 and because I already had openJDK installed, this command have solved the problem. Don't forget that JavaFX is part of OpenJDK.
sudo apt-get install openjfx
Just Use
import qs from "qs";
let data = {
'profileId': this.props.screenProps[0],
'accountId': this.props.screenProps[1],
'accessToken': this.props.screenProps[2],
'itemId': this.itemId
};
return axios.post(METHOD_WALL_GET, qs.stringify(data))
Try to open Services Window, by writing services.msc
into Start->Run and hit Enter.
When window appears, then find SQL Browser service, right click and choose Properties, and then in dropdown list choose Automatic, or Manual, whatever you want, and click OK. Eventually, if not started immediately, you can again press right click on this service and click Start.
I use port 465 all the time.
The answer by danorton is outdated. As he and Wikipedia say, port 465 was initially planned for the SMTPS encryption and quickly deprecated 15 years ago. But a lot of ISPs are still using port 465, especially to be in compliance with the current recommendations of RFC 8314, which encourages the use of implicit TLS instead of the use of the STARTTLS command with port 587. (See section 3.3). Using port 465 is the only way to begin an implicitly secure session with an SMTP server that is acting as a mail submission agent (MSA).
Basically, what RFC 8314 recommends is that cleartext email exchanges be abandoned and that all three common IETF mail protocols be used only in implicit TLS sessions for consistency when possible. The recommended secure ports, then, are 465, 993, and 995 for SMTPS, IMAP4S, and POP3S, respectively.
Although RFC 8314 certainly allows the continued use of explicit TLS with port 587 and the STARTTLS command, doing so opens up the mail user agent (MUA, the mail client) to a downgrade attack where a man-in-the-middle intercepts the STARTTLS request to upgrade to TLS security but denies it, thus forcing the session to remain in cleartext.
Below are code snippets to create and delete a cookie. The cookie is set for 1 day.
// 1 Day = 24 Hrs = 24*60*60 = 86400.
By using max-age:
document.cookie = "cookieName=cookieValue; max-age=86400; path=/;";
document.cookie = "cookieName=; max-age=- (any digit); path=/;";
By using expires:
var expires = (new Date(Date.now()+ 86400*1000)).toUTCString();
document.cookie = "cookieName=cookieValue; expires=" + expires + 86400) + ";path=/;"
You should Remember about TERNARY operator
:
so your code will be like this,
render(){
return (
<div>
<Element1/>
<Element2/>
// note: code does not work here
{
this.props.hasImage ? // if has image
<MyImage /> // return My image tag
:
<OtherElement/> // otherwise return other element
}
</div>
)
}
If you have python installed you could try:
python -c 'import sys;f=open(sys.argv[1]);print len(f.readline().split("|"))' \
stores.dat
As noted above by other contributors, using a .bowerrc
file with the JSON
{ "directory": "some/path" }
is necessary -- HOWEVER, you may run into an issue on Windows while creating that file. If Windows gives you a message imploring you to add a "file name", simply use a text editor / IDE such as Notepad++.
Add the JSON to an unnamed file, save it as .bowerrc -- you're good to go!
Probably an easy assumption, but I hope this save others the unnecessary headache :)
The simplest (and hence best) C++ (using the 2011 standard) answer is
#include <random>
std::random_device rd; // only used once to initialise (seed) engine
std::mt19937 rng(rd()); // random-number engine used (Mersenne-Twister in this case)
std::uniform_int_distribution<int> uni(min,max); // guaranteed unbiased
auto random_integer = uni(rng);
No need to re-invent the wheel. No need to worry about bias. No need to worry about using time as random seed.
I ran across this article in the results returned by a search related to the IF command in a batch file, and I couldn't resist the opportunity to correct the misconception that IF blocks are limited to single commands. Following is a portion of a production Windows NT command script that runs daily on the machine on which I am composing this reply.
if "%COPYTOOL%" equ "R" (
WWLOGGER.exe "%APPDATA%\WizardWrx\%~n0.LOG" "Using RoboCopy to make a backup of %USERPROFILE%\My Documents\Outlook Files\*"
%TOOLPATH% %SRCEPATH% %DESTPATH% /copyall %RCLOGSTR% /m /np /r:0 /tee
C:\BIN\ExitCodeMapper.exe C:\BIN\ExitCodeMapper.INI[Robocopy] %TEMP%\%~n0.TMP %ERRORLEVEL%
) else (
WWLOGGER.exe "%APPDATA%\WizardWrx\%~n0.LOG" "Using XCopy to make a backup of %USERPROFILE%\My Documents\Outlook Files\*"
call %TOOLPATH% "%USERPROFILE%\My Documents\Outlook Files\*" "%USERPROFILE%\My Documents\Outlook Files\_backups" /f /m /v /y
C:\BIN\ExitCodeMapper.exe C:\BIN\ExitCodeMapper.INI[Xcopy] %TEMP%\%~n0.TMP %ERRORLEVEL%
)
Perhaps blocks of two or more lines applies exclusively to Windows NT command scripts (.CMD files), because a search of the production scripts directory of an application that is restricted to old school batch (.BAT) files, revealed only one-command blocks. Since the application has gone into extended maintenance (meaning that I am not actively involved in supporting it), I can't say whether that is because I didn't need more than one line, or that I couldn't make them work.
Regardless, if the latter is true, there is a simple workaround; move the multiple lines into either a separate batch file or a batch file subroutine. I know that the latter works in both kinds of scripts.
I like Guffa's answer and since I can't comment I will provide the answer Udil's question here.
I needed something similar but I wanted certein logic in my token, I wanted to:
Now points 1-3 are fixed length so it was easy, here is my code:
Here is my code to generate the token:
public string GenerateToken(string reason, MyUser user)
{
byte[] _time = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
byte[] _key = Guid.Parse(user.SecurityStamp).ToByteArray();
byte[] _Id = GetBytes(user.Id.ToString());
byte[] _reason = GetBytes(reason);
byte[] data = new byte[_time.Length + _key.Length + _reason.Length+_Id.Length];
System.Buffer.BlockCopy(_time, 0, data, 0, _time.Length);
System.Buffer.BlockCopy(_key , 0, data, _time.Length, _key.Length);
System.Buffer.BlockCopy(_reason, 0, data, _time.Length + _key.Length, _reason.Length);
System.Buffer.BlockCopy(_Id, 0, data, _time.Length + _key.Length + _reason.Length, _Id.Length);
return Convert.ToBase64String(data.ToArray());
}
Here is my Code to take the generated token string and validate it:
public TokenValidation ValidateToken(string reason, MyUser user, string token)
{
var result = new TokenValidation();
byte[] data = Convert.FromBase64String(token);
byte[] _time = data.Take(8).ToArray();
byte[] _key = data.Skip(8).Take(16).ToArray();
byte[] _reason = data.Skip(24).Take(2).ToArray();
byte[] _Id = data.Skip(26).ToArray();
DateTime when = DateTime.FromBinary(BitConverter.ToInt64(_time, 0));
if (when < DateTime.UtcNow.AddHours(-24))
{
result.Errors.Add( TokenValidationStatus.Expired);
}
Guid gKey = new Guid(_key);
if (gKey.ToString() != user.SecurityStamp)
{
result.Errors.Add(TokenValidationStatus.WrongGuid);
}
if (reason != GetString(_reason))
{
result.Errors.Add(TokenValidationStatus.WrongPurpose);
}
if (user.Id.ToString() != GetString(_Id))
{
result.Errors.Add(TokenValidationStatus.WrongUser);
}
return result;
}
private static string GetString(byte[] reason) => Encoding.ASCII.GetString(reason);
private static byte[] GetBytes(string reason) => Encoding.ASCII.GetBytes(reason);
The TokenValidation class looks like this:
public class TokenValidation
{
public bool Validated { get { return Errors.Count == 0; } }
public readonly List<TokenValidationStatus> Errors = new List<TokenValidationStatus>();
}
public enum TokenValidationStatus
{
Expired,
WrongUser,
WrongPurpose,
WrongGuid
}
Now I have an easy way to validate a token, no Need to Keep it in a list for 24 hours or so. Here is my Good-Case Unit test:
private const string ResetPasswordTokenPurpose = "RP";
private const string ConfirmEmailTokenPurpose = "EC";//change here change bit length for reason section (2 per char)
[TestMethod]
public void GenerateTokenTest()
{
MyUser user = CreateTestUser("name");
user.Id = 123;
user.SecurityStamp = Guid.NewGuid().ToString();
var token = sit.GenerateToken(ConfirmEmailTokenPurpose, user);
var validation = sit.ValidateToken(ConfirmEmailTokenPurpose, user, token);
Assert.IsTrue(validation.Validated,"Token validated for user 123");
}
One can adapt the code for other business cases easely.
Happy Coding
Walter
I didn't want to import anything other than csv, and all my lists have the same number of items. The top answer here seems to make the lists into one row each, instead of one column each. Thus I took the answers here and came up with this:
import csv
list1 = ['a', 'b', 'c', 'd', 'e']
list2 = ['f', 'g', 'i', 'j','k']
with open('C:/test/numbers.csv', 'wb+') as myfile:
wr = csv.writer(myfile)
wr.writerow(("list1", "list2"))
rcount = 0
for row in list1:
wr.writerow((list1[rcount], list2[rcount]))
rcount = rcount + 1
myfile.close()
UPDATE c11
SET
c11.completed= c6.completed,
c11.complete_date = c6.complete_date,
-- rest of columns to be copied
FROM courses c11 inner join courses c6 on
c11.userID = c6.userID
and c11.courseID = 11 and c6.courseID = 6
-- and any other checks
I have always viewed the From clause of an update, like one of a normal select. Actually if you want to check what will be updated before running the update, you can take replace the update parts with a select c11.*. See my comments on the lame duck's answer.
I use PropertyResourceBundle to define the error codes in an enterprise application to manage locale error code resources. This is the best way to handle error codes instead of writing code (may be hold good for few error codes) when the number of error codes are huge and structured.
Look at java doc for more information on PropertyResourceBundle
I ran into this when checking on a null or empty string
if (x == NULL || x == '') {
changed it to
if (is.null(x) || x == '') {
I also encountered the same issue. Deleting the app didn't work, but when I tried deleting another app which was the current one's 'parent'(I copied the whole project from the previous app, modified some urls and images, then I clicked 'Run' and saw the unhappy 'could not be verified' dialog). Seems the issue is related to provisioning and code signing and/or some configurations of the project. Very tricky.
UPDATE:
Since the version 22.1.0, the class ActionBarActivity is deprecated, so instead use AppCompatActivity. For more details see here
Using ActionBarActivity:
In Eclipse:
1 - Make sure library project(appcompat_v7) is open & is proper referenced (added as library) in your application project.
2 - Delete android-support-v4.jar from your project's libs folder(if jar is present).
3 - Appcompat_v7 must have android-support-v4.jar & android-support-v7-appcompat.jar inside it's libs folder. (If jars are not present copy them from /sdk/extras/android/support/v7/appcompat/libs folder of your installed android sdk location)
4- Check whether ActionBarActivity is properly imported.
import android.support.v7.app.ActionBarActivity;
In Android Studio
Just add compile dependencies to app's build.gradle
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.1.1'
}
In case your text is compressed inside the blob using DEFLATE algorithm and it's quite large, you can use this function to read it
CREATE OR REPLACE PACKAGE read_gzipped_entity_package AS
FUNCTION read_entity(entity_id IN VARCHAR2)
RETURN VARCHAR2;
END read_gzipped_entity_package;
/
CREATE OR REPLACE PACKAGE BODY read_gzipped_entity_package IS
FUNCTION read_entity(entity_id IN VARCHAR2) RETURN VARCHAR2
IS
l_blob BLOB;
l_blob_length NUMBER;
l_amount BINARY_INTEGER := 10000; -- must be <= ~32765.
l_offset INTEGER := 1;
l_buffer RAW(20000);
l_text_buffer VARCHAR2(32767);
BEGIN
-- Get uncompressed BLOB
SELECT UTL_COMPRESS.LZ_UNCOMPRESS(COMPRESSED_BLOB_COLUMN_NAME)
INTO l_blob
FROM TABLE_NAME
WHERE ID = entity_id;
-- Figure out how long the BLOB is.
l_blob_length := DBMS_LOB.GETLENGTH(l_blob);
-- We'll loop through the BLOB as many times as necessary to
-- get all its data.
FOR i IN 1..CEIL(l_blob_length/l_amount) LOOP
-- Read in the given chunk of the BLOB.
DBMS_LOB.READ(l_blob
, l_amount
, l_offset
, l_buffer);
-- The DBMS_LOB.READ procedure dictates that its output be RAW.
-- This next procedure converts that RAW data to character data.
l_text_buffer := UTL_RAW.CAST_TO_VARCHAR2(l_buffer);
-- For the next iteration through the BLOB, bump up your offset
-- location (i.e., where you start reading from).
l_offset := l_offset + l_amount;
END LOOP;
RETURN l_text_buffer;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('!ERROR: ' || SUBSTR(SQLERRM,1,247));
END;
END read_gzipped_entity_package;
/
Then run select to get text
SELECT read_gzipped_entity_package.read_entity('entity_id') FROM DUAL;
Hope this will help someone.
Try this formula:
=SUBSTITUTE(TEXT(A1/B1,"?/?"),"/",":")
Result:
A B C
33 11 3:1
25 5 5:1
6 4 3:2
Explanation:
This doesn't require any special toolkits or macros. The only downside might be that the result is considered text--not a number--so you can easily use it for further calculations.
Note: as @Robin Day suggested, increase the number of question marks (?) as desired to reduce rounding (thanks Robin!).
$("a.directions-link").attr("href", $("a.directions-link").attr("href")+"...your additions...");
Regarding Wolfwyrd's anwer: "On Error Resume Next" in fact turns error handling off! Not on. On Error Goto 0 turns error-handling back ON because at the least, we want the machine to catch it if we didn't write it in ourselves. Off = leaving it to you to handle it.
If you use On Error Resume Next, you need to be careful about how much code you include after it: remember, the phrase "If Err.Number <> 0 Then" only refers to the most previous error triggered.
If your block of code after "On Error Resume Next" has several places where you might reasonably expect it to fail, then you must place "If Err.number <> 0" after each and every one of those possible failure lines, to check execution.
Otherwise, after "on error resume next" means just what it says - your code can fail on as many lines as it likes and execution will continue merrily along. That's why it's a pain in the ass.
Probably rather than defining both the events click and touch you could define a an handler which will look if the device will work with click or touch.
var handleClick= 'ontouchstart' in document.documentElement ? 'touchstart': 'click';
$(document).on(handleClick,'.button',function(){
alert('Click is now working with touch and click both');
});
I can't reproduce the @SilentGhost-beating performance quoted by @martineau. Here's my effort with comparisons:
=== maxelements.py ===
a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50,
35, 41, 49, 37, 19, 40, 41, 31]
b = range(10000)
c = range(10000 - 1, -1, -1)
d = b + c
def maxelements_s(seq): # @SilentGhost
''' Return list of position(s) of largest element '''
m = max(seq)
return [i for i, j in enumerate(seq) if j == m]
def maxelements_m(seq): # @martineau
''' Return list of position(s) of largest element '''
max_indices = []
if len(seq):
max_val = seq[0]
for i, val in ((i, val) for i, val in enumerate(seq) if val >= max_val):
if val == max_val:
max_indices.append(i)
else:
max_val = val
max_indices = [i]
return max_indices
def maxelements_j(seq): # @John Machin
''' Return list of position(s) of largest element '''
if not seq: return []
max_val = seq[0] if seq[0] >= seq[-1] else seq[-1]
max_indices = []
for i, val in enumerate(seq):
if val < max_val: continue
if val == max_val:
max_indices.append(i)
else:
max_val = val
max_indices = [i]
return max_indices
Results from a beat-up old laptop running Python 2.7 on Windows XP SP3:
>\python27\python -mtimeit -s"import maxelements as me" "me.maxelements_s(me.a)"
100000 loops, best of 3: 6.88 usec per loop
>\python27\python -mtimeit -s"import maxelements as me" "me.maxelements_m(me.a)"
100000 loops, best of 3: 11.1 usec per loop
>\python27\python -mtimeit -s"import maxelements as me" "me.maxelements_j(me.a)"
100000 loops, best of 3: 8.51 usec per loop
>\python27\python -mtimeit -s"import maxelements as me;a100=me.a*100" "me.maxelements_s(a100)"
1000 loops, best of 3: 535 usec per loop
>\python27\python -mtimeit -s"import maxelements as me;a100=me.a*100" "me.maxelements_m(a100)"
1000 loops, best of 3: 558 usec per loop
>\python27\python -mtimeit -s"import maxelements as me;a100=me.a*100" "me.maxelements_j(a100)"
1000 loops, best of 3: 489 usec per loop
If you're using jQuery 2.1.4 or above, try this:
$("#" + this.d);
Or, you can define var before using it. It makes your code simpler.
var d = this.d
$("#" + d);
Had a hard time finding the logs because the IDE was crashing on launch, if you are on Mac and use Android Studio 4.1 then the logs location may be found at /Users/{user}/Library/Logs/Google/AndroidStudio4.1/
And to be specific for me it is on macOS Big Sur
Maybe something changed since 2011 but this worked for me:
$ date +"%Y%m%d"
20150330
No need for the -d
to get the same appearing result.
I was having problem with finding the enhanced uploader tool for uploading folder and subfolders inside it in S3. But rather than finding a tool I could upload the folders along with the subfolders inside it by simply dragging and dropping it in the S3 bucket.
Note: This drag and drop feature doesn't work in Safari. I've tested it in Chrome and it works just fine.
After you drag and drop the files and folders, this screen opens up finally to upload the content.
For those using Select2 4.x, you can disable an individual option by doing:
$('select option:selected').prop('disabled', true);
For those using Select2 4.x, you can disable the entire dropdown with:
$('select').prop('disabled', true);
In the database, there are two options:
I've used bytea columns with great success in the past storing 10+gb of images with thousands of rows. PG's TOAST functionality pretty much negates any advantage that blobs have. You'll need to include metadata columns in either case for filename, content-type, dimensions, etc.
Bootstrap has it's own centering class named text-center.
<div class="span7 text-center"></div>
keep it easy:
sup { vertical-align: text-top; }
[font-size dependent on your individual type-face]
public static int [] locations={1,2,3};
public static test dot=new test();
Declare the above variables above the main method and the code compiles fine.
public static void main(String[] args){
I ran into the same problem every time it finds a special character marks it as ??. to solve this, I tried using the encoding: ISO-8859-1
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("txtPath"),"ISO-8859-1"));
while ((line = br.readLine()) != null) {
}
I hope this can help anyone who sees this post.
A _ttoi
function can convert CString
to integer, both wide char and ansi char can work. Below is the details:
CString str = _T("123");
int i = _ttoi(str);
Thanks for you answers. Shutdown hooks seams like something that would work in my case.
But I also bumped into the thing called Monitoring and Management beans:
http://java.sun.com/j2se/1.5.0/docs/guide/management/overview.html
That gives some nice possibilities, for remote monitoring, and manipulation of the java process. (Was introduced in Java 5)
sp_helptext [dbname.spname] try this