Sure the code does work, but I'm pretty sure it doesn't do what you expect it to do. It just fires off multiple asynchronous calls, but the printFiles
function does immediately return after that.
If you want to read the files in sequence, you cannot use forEach
indeed. Just use a modern for … of
loop instead, in which await
will work as expected:
async function printFiles () {
const files = await getFilePaths();
for (const file of files) {
const contents = await fs.readFile(file, 'utf8');
console.log(contents);
}
}
If you want to read the files in parallel, you cannot use forEach
indeed. Each of the async
callback function calls does return a promise, but you're throwing them away instead of awaiting them. Just use map
instead, and you can await the array of promises that you'll get with Promise.all
:
async function printFiles () {
const files = await getFilePaths();
await Promise.all(files.map(async (file) => {
const contents = await fs.readFile(file, 'utf8')
console.log(contents)
}));
}
You can't do a XMLHttpRequest crossdomain, the only "option" would be a technique called JSONP, which comes down to this:
To start request: Add a new <script>
tag with the remote url, and then make sure that remote url returns a valid javascript file that calls your callback function. Some services support this (and let you name your callback in a GET parameters).
The other easy way out, would be to create a "proxy" on your local server, which gets the remote request and then just "forwards" it back to your javascript.
edit/addition:
I see jQuery has built-in support for JSONP, by checking if the URL contains "callback=?" (where jQuery will replace ? with the actual callback method). But you'd still need to process that on the remote server to generate a valid response.
The main problem is that serializing an entity model which has relation with other entity model(Foreign key relationship). This relation causes self referencing this will throw exception while serialization to json or xml. There are lots of options. Without serializing entity models by using custom models.Values or data from entity model data mapped to custom models(object mapping) using Automapper or Valueinjector then return request and it will serialize without any other issues. Or you can serialize entity model so first disable proxies in entity model
public class LabEntities : DbContext
{
public LabEntities()
{
Configuration.ProxyCreationEnabled = false;
}
To preserve object references in XML, you have two options. The simpler option is to add [DataContract(IsReference=true)] to your model class. The IsReference parameter enables oibject references. Remember that DataContract makes serialization opt-in, so you will also need to add DataMember attributes to the properties:
[DataContract(IsReference=true)]
public partial class Employee
{
[DataMember]
string dfsd{get;set;}
[DataMember]
string dfsd{get;set;}
//exclude the relation without giving datamember tag
List<Department> Departments{get;set;}
}
In Json format in global.asax
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling =
Newtonsoft.Json.PreserveReferencesHandling.All;
in xml format
var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
var dcs = new DataContractSerializer(typeof(Employee), null, int.MaxValue,
false, /* preserveObjectReferences: */ true, null);
xml.SetSerializer<Employee>(dcs);
another way to do is get the UriInfo instead of all the QueryParam
Then you will be able to get the queryParam as per needed in your code
@GET
@Path("/query")
public Response getUsers(@Context UriInfo info) {
String param_1 = info.getQueryParameters().getFirst("param_1");
String param_2 = info.getQueryParameters().getFirst("param_2");
return Response ;
}
I had the very same issue. The answer is that you are doing it right already. It is the problem of MS Excel. Try opening the file with another editor and you will notice that your encoding was successful already. To make MS Excel happy, move from UTF-8 to UTF-16. This should work:
class UnicodeWriter:
def __init__(self, f, dialect=csv.excel_tab, encoding="utf-16", **kwds):
# Redirect output to a queue
self.queue = StringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
# Force BOM
if encoding=="utf-16":
import codecs
f.write(codecs.BOM_UTF16)
self.encoding = encoding
def writerow(self, row):
# Modified from original: now using unicode(s) to deal with e.g. ints
self.writer.writerow([unicode(s).encode("utf-8") for s in row])
# Fetch UTF-8 output from the queue ...
data = self.queue.getvalue()
data = data.decode("utf-8")
# ... and reencode it into the target encoding
data = data.encode(self.encoding)
# strip BOM
if self.encoding == "utf-16":
data = data[2:]
# write to the target stream
self.stream.write(data)
# empty queue
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
If you want to install PHP extensions in ubuntu.
first know which PHP version is active.
php -v
After that install needed plugin using this command.
sudo apt install php7.0-bcmath
you can replace php7.0-bcmath to php-PHPVersion-extensionName
I was facing following error with code (nodejs 0.10.13), provided by ampersand:
origin is not allowed by access-control-allow-origin
Issue was resolved changing
response.writeHead(200, {"Content-Type": "text/plain"});
to
response.writeHead(200, {
'Content-Type': 'text/html',
'Access-Control-Allow-Origin' : '*'});
you can use
<meta http-equiv="refresh" content="10" >
just add it after the head tags
where 10 is the time your page will refresh itself
In my case, i imported wrong, In module place instead of importing module(DemoModule) imported routing module(DemoRoutingModule)
Wrong Import:
const routes: Routes = [
{
path: '', component: ContentComponent,
children: [
{ path: '', redirectTo: 'demo' },
{ path: 'demo', loadChildren : () => import('../content/demo/demo-routing.module').then(m => m.DemoRoutingModule)}]
}
];
Right Code
const routes: Routes = [
{
path: '', component: ContentComponent,
children: [
{ path: '', redirectTo: 'demo' },
{ path: 'demo', loadChildren : () => import('../content/demo/demo.module').then(m => m.DemoModule)}]
}
];
The said method with highest up's by Laz is deprecated from version 4.3 onwards. Hence it would be better to user the Request Config Object and then build the HTTP Client
private CloseableHttpClient createHttpClient()
{
CloseableHttpClient httpClient;
CommonHelperFunctions helperFunctions = new CommonHelperFunctions();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(306);
cm.setDefaultMaxPerRoute(108);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(15000)
.setSocketTimeout(15000).build();
httpClient = HttpClients.custom()
.setConnectionManager(cm)
.setDefaultRequestConfig(requestConfig).build();
return httpClient;
}
The PoolingHttpClientConnectionManager is user to set the max default number of connections and the max number of conncetions per route. I have set it as 306 and 108 respectively. The default values will not be sufficient for most of the cases.
For setting Timeout: I have used the RequestConfig object. You can also set the property Connection Request Timeout for setting timeout for waiting for connection from Connection manager.
Root node is the DocumentElement
property of XmlDocument
XmlElement root = xmlDoc.DocumentElement
If you only have the node, you can get the root node by
XmlElement root = xmlNode.OwnerDocument.DocumentElement
I ran into this issue as well. For some I would like to point out that if it is locked CHECK WITH YOUR TEAM. Someone on the team might have some things locked because they are working on it (this allows developers to do work on things without others coming in and trying to work on the same content as well). If that is the case, releasing the lock and then updating has the potential to lose data for the developer who locked it.
With that in mind my concern was that the "clean up" option would possibly change my working copy or remove information from the Repo level of Subversion. That is not the case. The answer worked for me. Mine became locked when I clicked cancel during the middle of an update. I ended up pulling some of our branches and I did not need the stuff so I hit cancel. My working copy became locked. I could not find any documents that came up as "locked" when I used the command 'release lock'. This left me puzzled and upon some quick reading (and this thread) I attempted the 'clean up' command. After a clean up it resolved my issue and nothing was locked anymore.
source: http://tortoisesvn.net/docs/nightly/TortoiseSVN_en/tsvn-dug-locking.html
In case of Request to a REST Service:
You need to allow the CORS (cross origin sharing of resources) on the endpoint of your REST Service with Spring annotation:
@CrossOrigin(origins = "http://localhost:8080")
Very good tutorial: https://spring.io/guides/gs/rest-service-cors/
After not able to find a good universal solution I made something of my own. I have not tested it for a very large list.
It takes care of nested keys,arrays or just about anything.
app.filter('xf', function() {
function keyfind(f, obj) {
if (obj === undefined)
return -1;
else {
var sf = f.split(".");
if (sf.length <= 1) {
return obj[sf[0]];
} else {
var newobj = obj[sf[0]];
sf.splice(0, 1);
return keyfind(sf.join("."), newobj)
}
}
}
return function(input, clause, fields) {
var out = [];
if (clause && clause.query && clause.query.length > 0) {
clause.query = String(clause.query).toLowerCase();
angular.forEach(input, function(cp) {
for (var i = 0; i < fields.length; i++) {
var haystack = String(keyfind(fields[i], cp)).toLowerCase();
if (haystack.indexOf(clause.query) > -1) {
out.push(cp);
break;
}
}
})
} else {
angular.forEach(input, function(cp) {
out.push(cp);
})
}
return out;
}
})
HTML
<input ng-model="search.query" type="text" placeholder="search by any property">
<div ng-repeat="product in products | xf:search:['color','name']">
...
</div>
You should be able to use Windows "UNC" paths with robocopy. For example:
robocopy \\myServer\myFolder\myFile.txt \\myOtherServer\myOtherFolder
Robocopy has the ability to recover from certain types of network hiccups automatically.
To allow DMARC checks for SPF to pass and also be aligned when using sendmail, make sure you are setting the envelope sender address (-f
or -r
parameter) to something that matches the domain in the From:
header address.
Using PHP's built-in mail()
function without setting the 5th paramater will cause DMARC SPF checks to be unaligned if not done correctly. By default, sendmail will send the email with the webserver's user as the RFC5321.MailFrom / Return Path header.
For example, say you are hosting your website domain.com
on the host.com
web server. If you do not set the additional parameters parameter:
mail($to,$subject,$message,$headers); // Wrong way
The email recipient will receive an email with the following mail headers:
Return-Path: <[email protected]>
From: <[email protected]>
Even though this passes SPF checks, it will be unaligned (since domain.com and host.com do not match), which means that DMARC SPF check will fail as unaligned.
Instead, you must pass the envelope sender address to sendmail by including the 5th parameter in the PHP mail()
function, for example:
mail($to,$subject,$message,$headers, '-r [email protected]'); // Right way
In this case, the email recipient will receive an email with the following mail headers:
Return-Path: <[email protected]>
From: <[email protected]>
Since both of these headers contain addresses from domain.com
, SPF will pass and also be aligned, which means that DMARC will also pass the SPF check.
Since the cleanup is not dependent on the username
, you could put the cleanup in a separate useEffect
that is given an empty array as second argument.
Example
const { useState, useEffect } = React;_x000D_
_x000D_
const ForExample = () => {_x000D_
const [name, setName] = useState("");_x000D_
const [username, setUsername] = useState("");_x000D_
_x000D_
useEffect(_x000D_
() => {_x000D_
console.log("effect");_x000D_
},_x000D_
[username]_x000D_
);_x000D_
_x000D_
useEffect(() => {_x000D_
return () => {_x000D_
console.log("cleaned up");_x000D_
};_x000D_
}, []);_x000D_
_x000D_
const handleName = e => {_x000D_
const { value } = e.target;_x000D_
_x000D_
setName(value);_x000D_
};_x000D_
_x000D_
const handleUsername = e => {_x000D_
const { value } = e.target;_x000D_
_x000D_
setUsername(value);_x000D_
};_x000D_
_x000D_
return (_x000D_
<div>_x000D_
<div>_x000D_
<input value={name} onChange={handleName} />_x000D_
<input value={username} onChange={handleUsername} />_x000D_
</div>_x000D_
<div>_x000D_
<div>_x000D_
<span>{name}</span>_x000D_
</div>_x000D_
<div>_x000D_
<span>{username}</span>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
);_x000D_
};_x000D_
_x000D_
function App() {_x000D_
const [shouldRender, setShouldRender] = useState(true);_x000D_
_x000D_
useEffect(() => {_x000D_
setTimeout(() => {_x000D_
setShouldRender(false);_x000D_
}, 5000);_x000D_
}, []);_x000D_
_x000D_
return shouldRender ? <ForExample /> : null;_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App />, document.getElementById("root"));
_x000D_
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>_x000D_
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>_x000D_
_x000D_
<div id="root"></div>
_x000D_
This is how to get the html DOM element purely with JS:
var htmlElement = document.getElementsByTagName("html")[0];
or
var htmlElement = document.querySelector("html");
And if you want to use jQuery to get attributes from it...
$(htmlElement).attr(INSERT-ATTRIBUTE-NAME);
This line:
char b = "blah";
Is no good - your lvalue needs to be a pointer.
Your code is also in danger of a stack overflow, since your recursion check isn't bounding the decreasing value of x.
Anyway, the actual error message you are getting is because char a
is an automatic variable; the moment you return
it will cease to exist. You need something other than an automatic variable.
Use a parameterized query to prevent Sql injections (secutity problem)
Use the using statement so the connection will be closed and resources will be disposed.
using(var connection = new SqlConnection("connectionString"))
{
connection.Open();
var sql = "INSERT INTO Main(FirstName, SecondName) VALUES(@FirstName, @SecondName)";
using(var cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.AddWithValue("@FirstName", txFirstName.Text);
cmd.Parameters.AddWithValue("@SecondName", txSecondName.Text);
cmd.ExecuteNonQuery();
}
}
If you wind up here based on the question's title ("Another git process seems to be running in this repository"), note that the accepted answer will not be directly applicable to you if the message in this question's title is preceded by another message like the one below:
fatal: cannot lock ref 'HEAD': Unable to create '/<PATH>/<TO>/<REPO>/.git/refs/heads/<BRANCH>.lock': File exists.
In this case, you should delete that file(.lock) instead of .git/index.lock
An abstract class can be used instead of an interface (in C# 7.3).
// Like interface
abstract class IIO
{
public virtual async Task<string> DoOperation(string Name)
{
throw new NotImplementedException(); // throwing exception
// return await Task.Run(() => { return ""; }); // or empty do
}
}
// Implementation
class IOImplementation : IIO
{
public override async Task<string> DoOperation(string Name)
{
return await await Task.Run(() =>
{
if(Name == "Spiderman")
return "ok";
return "cancel";
});
}
}
You can use domaintools.com to lookup the server information for a website and narrow down to whether it's open source / Microsoft:
http://whois.domaintools.com/stackoverflow.com
And after that it's a matter of looking in the footer for tip-offs such as "Powered by WordPress" or "vBulletin" etc.
I came across this question while trying to install the Cucumber-Eclipse plugin in Eclipse via their update site. I received the same SunCertPathBuilderException error:
Unable to read repository at http://cucumber.io/cucumber-eclipse/update-site/content.xml.
Unable to read repository at http://cucumber.io/cucumber-eclipse/update-site/content.xml.
sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
While some of the other answers are appropriate and helpful for this question's given situation, they were nevertheless unhelpful and misleading for my issue.
In my case, the issue was that the URL provided for their update site is:
However when navigating to it via a browser, it redirected to (note the added ".github"):
So the resolution is to simply use the redirected version of the update site URL when adding the update site in eclipse.
I had a similar problem and found @aliwa's answer to be the most helpful and most elegant solution; however, I needed a specific key combination, Ctrl + 1. Unfortunately I got the following error:
'1' cannot be used as a value for 'Key'. Numbers are not valid enumeration values.
With a bit of further search, I modified @aliwa's answer to the following:
<Window.InputBindings>
<KeyBinding Gesture="Ctrl+1" Command="{Binding MyCommand}"/>
</Window.InputBindings>
I found this to work great for pretty well any combination I needed.
Try:
$('#mytable').attr('offsetTop')
USE information_schema;
SELECT COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME
FROM KEY_COLUMN_USAGE
WHERE (table_name = *tablename*) AND NOT (REFERENCED_TABLE_NAME IS NULL)
This will do it System.IO.Compression.ZipFile.ExtractToDirectory(ZipName, ExtractToPath)
In case you are uploading an sql file on cpanel, then try and replace root with your cpanel username in your sql file.
in the case above you could write
CREATE DEFINER = control_panel_username
@localhost
FUNCTION fnc_calcWalkedDistance
then upload the file. Hope it helps
Here is a method that does not require editing the code and works regardless of the number of characters.
String text =
java.text.MessageFormat.format(
"You're about to delete {0} rows.".replaceAll("'", "''"), 5);
For those who want isoWeek
to be the default you can modify moment's behaviour as such:
const moment = require('moment');
const proto = Object.getPrototypeOf(moment());
const {startOf, endOf} = proto;
proto.startOf = function(period) {
if (period === 'week') {
period = 'isoWeek';
}
return startOf.call(this, period);
};
proto.endOf = function(period) {
if (period === 'week') {
period = 'isoWeek';
}
return endOf.call(this, period);
};
Now you can simply use someDate.startOf('week')
without worrying you'll get sunday or having to think about whether to use isoweek
or isoWeek
etc.
Plus you can store this in a variable like const period = 'week'
and use it safely in subtract()
or add()
operations, e.g. moment().subtract(1, period).startOf(period);
. This won't work with period being isoWeek
.
Gmail: OAuth
Client ID
and Secret ID
. Finally click OK to close the credentials pop up.Google API
. Click on Overview in the left pane.Google API
under Social APIs section.That’s all from the Google part.
Come back to your application, open App_start/Startup.Auth.cs
and uncomment the following snippet
app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{
ClientId = "",
ClientSecret = ""
});
Update the ClientId
and ClientSecret
with the values from Google API
credentials which you have created already.
Gmail
id.Gmail
id into your application database.Using:
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
//do your ReconTool stuff
}
}
will work in all circumstances. Whether you want to launch the application from the IDE, or the build tool.
Using maven just use mvn spring-boot:run
while in gradle it would be gradle bootRun
An alternative to adding code under the run method, is to have a Spring Bean that implements CommandLineRunner
. That would look like:
@Component
public class ReconTool implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
//implement your business logic here
}
}
Check out this guide from Spring's official guide repository.
The full Spring Boot documentation can be found here
On Android the color can be declared in the following format
#AARRGGBB
AA
- is the bit that’s of most interest to us, it stands for alpha channel
RR
GG
BB
- red, green & blue channels respectively
Now in order to add transparency to our color we need to prepend it with hexadecimal value representing the alpha (transparency).
For example if you want to set 80% transparency value to black color (#000000
) you need to prepend it with CC
, as a result we end up with the following color resource #CC000000
.
You can read about it in more detail on my blog https://androidexplained.github.io/android/ui/2020/10/12/hex-color-code-transparency.html
Here is the code that worked for me:
public ArrayList GetBBGroups(WindowsIdentity identity)
{
ArrayList groups = new ArrayList();
try
{
String userName = identity.Name;
int pos = userName.IndexOf(@"\");
if (pos > 0) userName = userName.Substring(pos + 1);
PrincipalContext domain = new PrincipalContext(ContextType.Domain, "riomc.com");
UserPrincipal user = UserPrincipal.FindByIdentity(domain, IdentityType.SamAccountName, userName);
DirectoryEntry de = new DirectoryEntry("LDAP://RIOMC.com");
DirectorySearcher search = new DirectorySearcher(de);
search.Filter = "(&(objectClass=group)(member=" + user.DistinguishedName + "))";
search.PropertiesToLoad.Add("samaccountname");
search.PropertiesToLoad.Add("cn");
String name;
SearchResultCollection results = search.FindAll();
foreach (SearchResult result in results)
{
name = (String)result.Properties["samaccountname"][0];
if (String.IsNullOrEmpty(name))
{
name = (String)result.Properties["cn"][0];
}
GetGroupsRecursive(groups, de, name);
}
}
catch
{
// return an empty list...
}
return groups;
}
public void GetGroupsRecursive(ArrayList groups, DirectoryEntry de, String dn)
{
DirectorySearcher search = new DirectorySearcher(de);
search.Filter = "(&(objectClass=group)(|(samaccountname=" + dn + ")(cn=" + dn + ")))";
search.PropertiesToLoad.Add("memberof");
String group, name;
SearchResult result = search.FindOne();
if (result == null) return;
group = @"RIOMC\" + dn;
if (!groups.Contains(group))
{
groups.Add(group);
}
if (result.Properties["memberof"].Count == 0) return;
int equalsIndex, commaIndex;
foreach (String dn1 in result.Properties["memberof"])
{
equalsIndex = dn1.IndexOf("=", 1);
if (equalsIndex > 0)
{
commaIndex = dn1.IndexOf(",", equalsIndex + 1);
name = dn1.Substring(equalsIndex + 1, commaIndex - equalsIndex - 1);
GetGroupsRecursive(groups, de, name);
}
}
}
I measured it's performance in a loop of 200 runs against the code that uses the AttributeValuesMultiString
recursive method; and it worked 1.3 times faster.
It might be so because of our AD settings. Both snippets gave the same result though.
You cannot do it. C compiler cannot do such a complex thing on stack.
You have to use heap and dynamic allocation.
What you really need to do:
Use *access(boardAux, x, y, size) = 42 to interact with the matrix.
I would do something like:
select
A.id, A.age, B.count
from
students A,
(select age, count(*) as count from students group by age) B
where A.age=B.age;
While searching this very question I discovered this example in the documentation.
QPushButton *quitButton = new QPushButton("Quit");
connect(quitButton, &QPushButton::clicked, &app, &QCoreApplication::quit, Qt::QueuedConnection);
Mutatis mutandis for your particular action of course.
Along with this note.
It's good practice to always connect signals to this slot using a QueuedConnection. If a signal connected (non-queued) to this slot is emitted before control enters the main event loop (such as before "int main" calls exec()), the slot has no effect and the application never exits. Using a queued connection ensures that the slot will not be invoked until after control enters the main event loop.
It's common to connect the QGuiApplication::lastWindowClosed() signal to quit()
If Cas Bloem's answer does not apply (i.e. you've definitely got the web
middleware on the applicable route), you might want to check the order of middlewares in your HTTP Kernel.
The default order in Kernel.php
is this:
$middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
];
Note that VerifyCsrfToken
comes after StartSession
. If you've got these in a different order, the dependency between them can also lead to the Session store not set on request.
exception.
I agree with Brainstorm's approach: assuming that you're passing a machine-friendly binary representation, use the encoding/binary
library. The OP suggests that binary.Write()
might have some overhead. Looking at the source for the implementation of Write()
, I see that it does some runtime decisions for maximum flexibility.
func Write(w io.Writer, order ByteOrder, data interface{}) error {
// Fast path for basic types.
var b [8]byte
var bs []byte
switch v := data.(type) {
case *int8:
bs = b[:1]
b[0] = byte(*v)
case int8:
bs = b[:1]
b[0] = byte(v)
case *uint8:
bs = b[:1]
b[0] = *v
...
Right? Write() takes in a very generic data
third argument, and that's imposing some overhead as the Go runtime then is forced into encoding type information. Since Write()
is doing some runtime decisions here that you simply don't need in your situation, maybe you can just directly call the encoding functions and see if it performs better.
Something like this:
package main
import (
"encoding/binary"
"fmt"
)
func main() {
bs := make([]byte, 4)
binary.LittleEndian.PutUint32(bs, 31415926)
fmt.Println(bs)
}
Let us know how this performs.
Otherwise, if you're just trying to get an ASCII representation of the integer, you can get the string representation (probably with strconv.Itoa
) and cast that string to the []byte
type.
package main
import (
"fmt"
"strconv"
)
func main() {
bs := []byte(strconv.Itoa(31415926))
fmt.Println(bs)
}
Suggestions are (basically) based on the text in the current open file and any snippets or completions you have defined (ref). If you want more text suggestions, I'd recommend:
As a side note, I'd really recommend installing Package control to take full advantage of the Sublime community. Some of the options above use Package control. I'd also highly recommend the tutsplus Sublime tutorial videos, which include all sorts of information about improving your efficiency when using Sublime.
<!doctype html>
<html>
<head>
## Heading ##
<meta charset="utf-8">
<title>
Untitled Document
</title>
</head>
<style>
li {
display: block;
width: auto;
}
ul li> ul li {
float: left;
}
ul li> ul {
display: none;
position: absolute;
}
li:hover > ul {
display: block;
margin-left: 148px;
display: inline;
margin-top: -52px;
}
a {
background: #f2f2ea;
display: block;
/*padding:10px 5px;
*/
width: 186px;
height: 50px;
border: solid 2px #c2c2c2;
border-bottom: none;
text-decoration: none;
}
li:hover >a {
background: #ffffff;
}
ul li>li:hover {
margin: 12px auto 0px auto;
padding-top: 10px;
width: 0;
height: 0;
border-top: 8px solid #c2c2c2;
}
.bottom {
border-bottom: solid 2px #c2c2c2;
}
.sub_m {
border-bottom: solid 2px #c2c2c2;
}
.sub_m2 {
border-left: none;
border-right: none;
border-bottom: solid 2px #c2c2c2;
}
li.selected {
background: #6D0070;
}
#menu_content {
/*float:left;
*/
}
.ca-main {
padding-top: 18px;
margin: 0;
color: #34495e;
font-size: 18px;
}
.ca-sub {
padding-top: 18px;
margin: 0px 20px;
color: #34495e;
font-size: 18px;
}
.submenu a {
width: auto;
}
h2 {
text-align: center;
}
</style>
<body>
<ul>
<li>
<a href="#">
<div id="menu_content">
<h2 class="ca-main">
Item 1
</h2>
</div>
</a>
<ul class="submenu" >
<li>
<a href="#" class="sub_m">
<div id="menu_content">
<h2 class="ca-sub">
Item 1_1
</h2>
</div>
</a>
</li>
<li>
<a href="#" class="sub_m2">
<div id="menu_content">
<h2 class="ca-sub">
Item 1_2
</h2>
</div>
</a>
</li>
<li >
<a href="#" class="sub_m">
<div id="menu_content">
<h2 class="ca-sub">
Item 1_3
</h2>
</div>
</a>
</li>
</ul>
</li>
<li>
<a href="#">
<div id="menu_content">
<h2 class="ca-main">
Item 2
</h2>
</div>
</a>
</li>
<li>
<a href="#">
<div id="menu_content">
<h2 class="ca-main">
Item 3
</h2>
</div>
</a>
</li>
<li>
<a href="#" class="bottom">
<div id="menu_content">
<h2 class="ca-main">
Item 4
</h2>
</div>
</a>
</li>
</ul>
</body>
</html>
I had the same issue and i solved it by deleteing gradle-wrapper.jar and gradle-wrapper.properties file of Gradle wrapper then clean rebuild work for me.
Shortest answer, given your timezone being TZ
:
LocalDateTime start = LocalDate.now(TZ).atStartOfDay()
LocalDateTime end = start.plusDays(1)
Compare using isAfter()
and isBefore()
methods, or convert it using toEpochSecond()
or toInstant()
methods.
Try this simple query. It works perfectly.
select * from Table1 where (FirstName,LastName,BirthDate) not in (select * from Table2);
Ajax is a technology / paradigm, whereas jquery is a library (which provides - besides other nice functionality - a convenient wrapper around ajax) - thus you can't compare them.
'$on' itself returns function for unregister
var unregister= $rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams, options) {
alert('state changing');
});
you can call unregister() function to unregister that listener
Simply, you use ADB, as follows:
adb install <path to apk>
Also see the section Installing an Application in Android Debug Bridge.
Bitmap
The accepted answer will crash when the Bitmap
is too large. I believe it's a 1MB limit. The Bitmap
must be compressed into a different file format such as a JPG represented by a ByteArray
, then it can be safely passed via an Intent
.
The function is contained in a separate thread using Kotlin Coroutines because the Bitmap
compression is chained after the Bitmap
is created from an url String
. The Bitmap
creation requires a separate thread in order to avoid Application Not Responding (ANR) errors.
toBitmap()
is a Kotlin extension function requiring that library to be added to the app dependencies.Bitmap
to JPG ByteArray
after it has been created.Repository.kt
suspend fun bitmapToByteArray(url: String) = withContext(Dispatchers.IO) {
MutableLiveData<Lce<ContentResult.ContentBitmap>>().apply {
postValue(Lce.Loading())
postValue(Lce.Content(ContentResult.ContentBitmap(
ByteArrayOutputStream().apply {
try {
BitmapFactory.decodeStream(URL(url).openConnection().apply {
doInput = true
connect()
}.getInputStream())
} catch (e: IOException) {
postValue(Lce.Error(ContentResult.ContentBitmap(ByteArray(0), "bitmapToByteArray error or null - ${e.localizedMessage}")))
null
}?.compress(CompressFormat.JPEG, BITMAP_COMPRESSION_QUALITY, this)
}.toByteArray(), "")))
}
}
ViewModel.kt
//Calls bitmapToByteArray from the Repository
private fun bitmapToByteArray(url: String) = liveData {
emitSource(switchMap(repository.bitmapToByteArray(url)) { lce ->
when (lce) {
is Lce.Loading -> liveData {}
is Lce.Content -> liveData {
emit(Event(ContentResult.ContentBitmap(lce.packet.image, lce.packet.errorMessage)))
}
is Lce.Error -> liveData {
Crashlytics.log(Log.WARN, LOG_TAG,
"bitmapToByteArray error or null - ${lce.packet.errorMessage}")
}
}
})
}
ByteArray
via an Intent
.In this sample it's passed from a Fragment to a Service. It's the same concept if being shared between two Activities.
Fragment.kt
ContextCompat.startForegroundService(
context!!,
Intent(context, AudioService::class.java).apply {
action = CONTENT_SELECTED_ACTION
putExtra(CONTENT_SELECTED_BITMAP_KEY, contentPlayer.image)
})
ByteArray
back to Bitmap
.Utils.kt
fun ByteArray.byteArrayToBitmap(context: Context) =
run {
BitmapFactory.decodeByteArray(this, BITMAP_OFFSET, size).run {
if (this != null) this
// In case the Bitmap loaded was empty or there is an error I have a default Bitmap to return.
else AppCompatResources.getDrawable(context, ic_coinverse_48dp)?.toBitmap()
}
}
I merge projects slightly manually, which allows me to avoid needing to deal with merge conflicts.
first, copy in the files from the other project however you want them.
cp -R myotherproject newdirectory
git add newdirectory
next pull in the history
git fetch path_or_url_to_other_repo
tell git to merge in the history of last fetched thing
echo 'FETCH_HEAD' > .git/MERGE_HEAD
now commit however you normally would commit
git commit
%hash1 = (%hash1, %hash2) ## or else ... @hash1{keys %hash2} = values %hash2; ## or with references ... $hash_ref1 = { %$hash_ref1, %$hash_ref2 };
undef
, zero, empty string, false
, falsy ...)1 * (aka associative-array, aka dictionary)
This type use:
@Html.ActionLink("MainPage","Index","Home")
MainPage : Name of the text Index : Action View Home : HomeController
Base Use ActionLink
<html>_x000D_
<head>_x000D_
<meta name="viewport" content="width=device-width" />_x000D_
<title>_Layout</title>_x000D_
<link href="@Url.Content("~/Content/bootsrap.min.css")" rel="stylesheet" type="text/css" />_x000D_
</head>_x000D_
<body>_x000D_
<div class="container">_x000D_
<div class="col-md-12">_x000D_
<button class="btn btn-default" type="submit">@Html.ActionLink("AnaSayfa","Index","Home")</button>_x000D_
<button class="btn btn-default" type="submit">@Html.ActionLink("Hakkimizda", "Hakkimizda", "Home")</button>_x000D_
<button class="btn btn-default" type="submit">@Html.ActionLink("Iletisim", "Iletisim", "Home")</button>_x000D_
</div> _x000D_
@RenderBody()_x000D_
<div class="col-md-12" style="height:200px;background-image:url(/img/footer.jpg)">_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
The easiest way is to JSON-encode your object and then decode it back to an array:
$array = json_decode(json_encode($object), true);
Or if you prefer, you can traverse the object manually, too:
foreach ($object as $value)
$array[] = $value->post_id;
By default the Ant will considered the JRE as the workspace JRE version. You need to change according to your required version by following the below.
In Eclipse:
Right click on your build.xml click "Run As", click on "External Tool Configurations..." Select tab JRE.
Select the JRE you are using.
Re-run the task, it should be fine now.
The javaw.exe command is identical to java.exe, except that with javaw.exe there is no associated console window
I tried one with my project.
This allows numbers with + | -
signs as well.
/^(\+|-)?[0-9]{0,}((\.){1}[0-9]{1,}){0,1}$/
Use
.wrapper:after {
content : '\n';
}
Much like solution provided by Roko. It allows to insert/change content using : after and :before psuedo. For details check http://www.quirksmode.org/css/content.html
The proper way of using NSLog, as the warning tries to explain, is the use of a formatter, instead of passing in a literal:
Instead of:
NSString *digit = [[sender titlelabel] text];
NSLog(digit);
Use:
NSString *digit = [[sender titlelabel] text];
NSLog(@"%@",digit);
It will still work doing that first way, but doing it this way will get rid of the warning.
You can't run PHP with javascript. JavaScript is a client side technology (runs in the users browser) and PHP is a server side technology (run on the server).
If you want to do this you have to make an ajax request to a PHP script and have that return the results you are looking for.
Why do you want to do this?
Easy workaround that I always use
let list = document.getElementsByClassName("events");
let listArr = Array.from(list)
After this you can run any desired Array methods on the selection
listArr.map(item => console.log(item.id))
listArr.forEach(item => console.log(item.id))
listArr.reverse()
Maybe you can try this: though please note - This pulls the column count, not the row count
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
int count = reader.VisibleFieldCount;
Console.WriteLine(count);
}
}
Here is a utility I made using some of the linked examples to handle 32-bit, 64-bit and 64-bit with compressed OOP. It uses sun.misc.Unsafe
.
It uses Unsafe.addressSize()
to get the size of a native pointer and Unsafe.arrayIndexScale( Object[].class )
for the size of a Java reference.
It uses the field offset of a known class to work out the base size of an object.
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.IdentityHashMap;
import java.util.Stack;
import sun.misc.Unsafe;
/** Usage:
* MemoryUtil.sizeOf( object )
* MemoryUtil.deepSizeOf( object )
* MemoryUtil.ADDRESS_MODE
*/
public class MemoryUtil
{
private MemoryUtil()
{
}
public static enum AddressMode
{
/** Unknown address mode. Size calculations may be unreliable. */
UNKNOWN,
/** 32-bit address mode using 32-bit references. */
MEM_32BIT,
/** 64-bit address mode using 64-bit references. */
MEM_64BIT,
/** 64-bit address mode using 32-bit compressed references. */
MEM_64BIT_COMPRESSED_OOPS
}
/** The detected runtime address mode. */
public static final AddressMode ADDRESS_MODE;
private static final Unsafe UNSAFE;
private static final long ADDRESS_SIZE; // The size in bytes of a native pointer: 4 for 32 bit, 8 for 64 bit
private static final long REFERENCE_SIZE; // The size of a Java reference: 4 for 32 bit, 4 for 64 bit compressed oops, 8 for 64 bit
private static final long OBJECT_BASE_SIZE; // The minimum size of an Object: 8 for 32 bit, 12 for 64 bit compressed oops, 16 for 64 bit
private static final long OBJECT_ALIGNMENT = 8;
/** Use the offset of a known field to determine the minimum size of an object. */
private static final Object HELPER_OBJECT = new Object() { byte b; };
static
{
try
{
// Use reflection to get a reference to the 'Unsafe' object.
Field f = Unsafe.class.getDeclaredField( "theUnsafe" );
f.setAccessible( true );
UNSAFE = (Unsafe) f.get( null );
OBJECT_BASE_SIZE = UNSAFE.objectFieldOffset( HELPER_OBJECT.getClass().getDeclaredField( "b" ) );
ADDRESS_SIZE = UNSAFE.addressSize();
REFERENCE_SIZE = UNSAFE.arrayIndexScale( Object[].class );
if( ADDRESS_SIZE == 4 )
{
ADDRESS_MODE = AddressMode.MEM_32BIT;
}
else if( ADDRESS_SIZE == 8 && REFERENCE_SIZE == 8 )
{
ADDRESS_MODE = AddressMode.MEM_64BIT;
}
else if( ADDRESS_SIZE == 8 && REFERENCE_SIZE == 4 )
{
ADDRESS_MODE = AddressMode.MEM_64BIT_COMPRESSED_OOPS;
}
else
{
ADDRESS_MODE = AddressMode.UNKNOWN;
}
}
catch( Exception e )
{
throw new Error( e );
}
}
/** Return the size of the object excluding any referenced objects. */
public static long shallowSizeOf( final Object object )
{
Class<?> objectClass = object.getClass();
if( objectClass.isArray() )
{
// Array size is base offset + length * element size
long size = UNSAFE.arrayBaseOffset( objectClass )
+ UNSAFE.arrayIndexScale( objectClass ) * Array.getLength( object );
return padSize( size );
}
else
{
// Object size is the largest field offset padded out to 8 bytes
long size = OBJECT_BASE_SIZE;
do
{
for( Field field : objectClass.getDeclaredFields() )
{
if( (field.getModifiers() & Modifier.STATIC) == 0 )
{
long offset = UNSAFE.objectFieldOffset( field );
if( offset >= size )
{
size = offset + 1; // Field size is between 1 and PAD_SIZE bytes. Padding will round up to padding size.
}
}
}
objectClass = objectClass.getSuperclass();
}
while( objectClass != null );
return padSize( size );
}
}
private static final long padSize( final long size )
{
return (size + (OBJECT_ALIGNMENT - 1)) & ~(OBJECT_ALIGNMENT - 1);
}
/** Return the size of the object including any referenced objects. */
public static long deepSizeOf( final Object object )
{
IdentityHashMap<Object,Object> visited = new IdentityHashMap<Object,Object>();
Stack<Object> stack = new Stack<Object>();
if( object != null ) stack.push( object );
long size = 0;
while( !stack.isEmpty() )
{
size += internalSizeOf( stack.pop(), stack, visited );
}
return size;
}
private static long internalSizeOf( final Object object, final Stack<Object> stack, final IdentityHashMap<Object,Object> visited )
{
// Scan for object references and add to stack
Class<?> c = object.getClass();
if( c.isArray() && !c.getComponentType().isPrimitive() )
{
// Add unseen array elements to stack
for( int i = Array.getLength( object ) - 1; i >= 0; i-- )
{
Object val = Array.get( object, i );
if( val != null && visited.put( val, val ) == null )
{
stack.add( val );
}
}
}
else
{
// Add unseen object references to the stack
for( ; c != null; c = c.getSuperclass() )
{
for( Field field : c.getDeclaredFields() )
{
if( (field.getModifiers() & Modifier.STATIC) == 0
&& !field.getType().isPrimitive() )
{
field.setAccessible( true );
try
{
Object val = field.get( object );
if( val != null && visited.put( val, val ) == null )
{
stack.add( val );
}
}
catch( IllegalArgumentException e )
{
throw new RuntimeException( e );
}
catch( IllegalAccessException e )
{
throw new RuntimeException( e );
}
}
}
}
}
return shallowSizeOf( object );
}
}
An earlier process of resolving conflicts (through the staging view) in Eclipse seemed much more intuitive several years ago, so either the tooling no longer functions in the way that I was used to, or I am remembering the process of resolving merge conflicts within SVN repositories. Regardless, there was this nifty "Mark as Merged" menu option when right-clicking on a conflicting file.
Fast forward to 2019, I am using the "Git Staging" view in Eclipse (v4.11). Actually, I am using STS (Spring Tool Suite 3.9.8), but I think the Git Staging view is a standard Eclipse plugin for working with Java/Spring-based projects. I share the following approach in case it helps anyone else, and because I grow weary or resolving merge conflicts from the GIT command line. ;-)
Because the feature I recall is now gone (or perhaps done differently with the current version of GIT and Eclipse), here are the current steps that I now follow to resolve merge conflicts through Eclipse using a GIT repository. It seems the most intuitive to me. Obviously, it is clear from the number of responses here that there are many ways to resolve merge conflicts. Perhaps I just need to switch to JetBrains IntelliJ, with their three-way merge tool.
NOTE: Because the menu options are not intuitive, a number of things can be misleading. For example, if you have saved any updates locally, and try to reopen the conflicting file to confirmand that the changes you made have persisted, confusion may result since the original conflict state is opened... not your changes.
But once you add the file(s) to the index, you will see your changes there.
I also recommend that when you pull in changes that result in a merge conflict, that you "stash" your local changes first, and then pull the changes in again. At least with GIT, as a protection, you will not be allowed to pull in external changes until you either revert your changes or stash them. Discard and revert to the HEAD state if the changes are not important, but stash them otherwise.
Finally, if you have just one or two files changing, then consider pulling them into separate text files as a reference, then revert to the HEAD and then manually update the file(s) when you pull changes across.
A space may only be encoded to "+" in the "application/x-www-form-urlencoded" content-type key-value pairs query part of an URL. In my opinion, this is a MAY, not a MUST. In the rest of URLs, it is encoded as %20.
In my opinion, it's better to always encode spaces as %20, not as "+", even in the query part of an URL, because it is the HTML specification (RFC-1866) that specified that space characters should be encoded as "+" in "application/x-www-form-urlencoded" content-type key-value pairs (see paragraph 8.2.1. subparagraph 1.)
This way of encoding form data is also given in later HTML specifications. For example, look for relevant paragraphs about application/x-www-form-urlencoded in HTML 4.01 Specification, and so on.
Here is a sample string in URL where the HTML specification allows encoding spaces as pluses: "http://example.com/over/there?name=foo+bar". So, only after "?", spaces can be replaced by pluses. In other cases, spaces should be encoded to %20. But since it's hard to correctly determine the context, it's the best practice to never encode spaces as "+".
I would recommend to percent-encode all character except "unreserved" defined in RFC-3986, p.2.3
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
The implementation depends on the programming language that you chose.
If your URL contains national characters, first encode them to UTF-8 and then percent-encode the result.
You can use annotate your method with @Scheduled(cron ="0 1 1 * * ?")
.
0 - is for seconds
1- 1 minute
1 - hour of the day.
Just check if the request has a status code 200. So for example:
if status != 200:
print("An error has occured. [Status code", status, "]")
else:
data = response.json() #Only convert to Json when status is OK.
if not data["elements"]:
print("Empty JSON")
else:
"You can extract data here"
Yes you right and I just want to make it understandable for complete beginners.
<link rel="shortcut icon" href="images/favicon.ico" />
and past it without any changes in between <head>
opening and </head>
closing tag.You must validate your input to make sure the string you pass is not empty and is, in fact, a string. An empty string is not valid JSON.
function is_json($string) {
return !empty($string) && is_string($string) && is_array(json_decode($string, true)) && json_last_error() == 0;
}
I think in PHP it's more important to determine if the JSON object even has data, because to use the data you will need to call json_encode()
or json_decode()
. I suggest denying empty JSON objects so you aren't unnecessarily running encodes and decodes on empty data.
function has_json_data($string) {
$array = json_decode($string, true);
return !empty($string) && is_string($string) && is_array($array) && !empty($array) && json_last_error() == 0;
}
I too had this issue, however nothing I tried above and in several other posts worked.. except for this.
For me, I changed the bundle identifier since we have a different bundle ID for distribution versus development.
My hardware is allowed on this provision and my team account is valid but it was throwing the above error on some other framework.
Turns out that I needed to completely remove the old version of the app completely from my phone. And not just deleting it the standard way.
Solution :
Evidently on installing the same app under the same team under a different bundle ID, if your not starting completely from scratch, there are some references to frameworks that get muddied.
Hope this helps someone.
XAML
<Popup Name="myPopup">
<TextBlock Name="myPopupText"
Background="LightBlue"
Foreground="Blue">
Popup Text
</TextBlock>
</Popup>
c#
Popup codePopup = new Popup();
TextBlock popupText = new TextBlock();
popupText.Text = "Popup Text";
popupText.Background = Brushes.LightBlue;
popupText.Foreground = Brushes.Blue;
codePopup.Child = popupText;
you can find more details about the Popup Control from MSDN documentation.
Here's a quick and dirty method that does what you want in a generic way. You'll need to add exception handling and you'll probably want to cache the BeanInfo types in a weakhashmap.
public Map<String, Object> getNonNullProperties(final Object thingy) {
final Map<String, Object> nonNullProperties = new TreeMap<String, Object>();
try {
final BeanInfo beanInfo = Introspector.getBeanInfo(thingy
.getClass());
for (final PropertyDescriptor descriptor : beanInfo
.getPropertyDescriptors()) {
try {
final Object propertyValue = descriptor.getReadMethod()
.invoke(thingy);
if (propertyValue != null) {
nonNullProperties.put(descriptor.getName(),
propertyValue);
}
} catch (final IllegalArgumentException e) {
// handle this please
} catch (final IllegalAccessException e) {
// and this also
} catch (final InvocationTargetException e) {
// and this, too
}
}
} catch (final IntrospectionException e) {
// do something sensible here
}
return nonNullProperties;
}
See these references:
Start with looking up the z-value for your desired confidence interval from a look-up table. The confidence interval is then mean +/- z*sigma
, where sigma
is the estimated standard deviation of your sample mean, given by sigma = s / sqrt(n)
, where s
is the standard deviation computed from your sample data and n
is your sample size.
Most of the time you can have Android Studio automatically update the Gradle plugin.
If your Gradle plugin version is behind, Instant Run will mostly likely not work. Therefore if you go to the Instant Run settings (Preferences > Build, Execution, Deployment > Instant Run), you'll see an Update project button at the top right (image below). Clicking this will update both the Gradle wrapper and build tools.
Just do Ctrl + Enter inside the text box
Unfortunately this is not supported in Entity Framework. It was on the roadmap for EF 6, but it got pushed back: Workitem 299: Unique Constraints (Unique Indexes)
use html link instead of asp link and you can use label in between html link for server side control
There are many toolboxes. Since you mentioned one that is commercially available from MathWorks, I assume you mean how do you get a trial/license
http://www.mathworks.com/products/image/
There is a link for trials, purchase, demos. This will get you in touch with your sales representative. If you know your sales representative, you could just call to get attention faster.
If you mean just a general toolbox that is from a source other than MathWorks, I would check with the producer, as it will vary widely from "Put it on your path." to whatever their purchase and licensing procedure is.
Thanks everyone who have answered.I have seen all answers and to try to make it easy for everyone
Step 1: Type edit environment and select the option shown
Step 2: Select Path and click on edit
Step 3: In the end add the below statement(you can avoid the first ; if its already there)
;C:\Program Files\Git\bin\git.exe;C:\Program Files\Git\cmd
Step 4:- Click on ok
Step 5 **:- One of the important step which is highlighted by one of the users. thanks to him. Please, **CLOSE command prompt and REOPEN then try to write git.
**
**
Here is the magic
This code will work perfectly in WPF. You can use it in either page load or in button click.
string screenWidth =System.Windows.SystemParameters.PrimaryScreenWidth.ToString();
string screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight.ToString();
txtResolution.Text ="Resolution : "+screenWidth + " X " + screenHeight;
Android Studio 3.5.3 It works with this configuration.
For those like I who just followed the code by skuntsel and received a cryptic stack trace, allow me to save you some time.
It seems c:if
cannot by itself be followed by c:otherwise
.
The correct solution is as follows:
<c:choose>
<c:when test="#{some.test}">
<p>some.test is true</p>
</c:when>
<c:otherwise>
<p>some.test is not true</p>
</c:otherwise>
</c:choose>
You can add additional c:when
tests in as necessary.
Here is a Kotlin
method to make parts of a TextView
clickable:
private fun makeTextLink(textView: TextView, str: String, underlined: Boolean, color: Int?, action: (() -> Unit)? = null) {
val spannableString = SpannableString(textView.text)
val textColor = color ?: textView.currentTextColor
val clickableSpan = object : ClickableSpan() {
override fun onClick(textView: View) {
action?.invoke()
}
override fun updateDrawState(drawState: TextPaint) {
super.updateDrawState(drawState)
drawState.isUnderlineText = underlined
drawState.color = textColor
}
}
val index = spannableString.indexOf(str)
spannableString.setSpan(clickableSpan, index, index + str.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
textView.text = spannableString
textView.movementMethod = LinkMovementMethod.getInstance()
textView.highlightColor = Color.TRANSPARENT
}
It can be called multiple times to create several links within a TextView:
makeTextLink(myTextView, str, false, Color.RED, action = { Log.d("onClick", "link") })
makeTextLink(myTextView, str1, true, null, action = { Log.d("onClick", "link1") })
For me with FreeBSD 10.1 with sed worked only this solution:
sed -e '/^[ ]*$/d' "testfile"
inside []
there are space and tab symbols.
test file contains:
fffffff next 1 tabline ffffffffffff
ffffffff next 1 Space line ffffffffffff
ffffffff empty 1 lines ffffffffffff
============ EOF =============
Just pass it as parameters as follows:
php test.php one two three
And inside file test.php:
<?php
if(isset($argv))
{
foreach ($argv as $arg)
{
echo $arg;
echo "\r\n";
}
}
?>
The Answer i was looking for was:
DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss");
I've also learned that you can do it this way:
DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString(myCountryDateFormat);
where myCountryDateFormat can be changed to meet change depending on requirement.
Please note that the tagged "This question may already have an answer here:" has not actually answered the question because as you can see it used a ".Date" instead of omitting it. It's quite confusing for new programmers of .NET
Easy with perl! If you want to get line 1, 3 and 5 from a file, say /etc/passwd:
perl -e 'while(<>){if(++$l~~[1,3,5]){print}}' < /etc/passwd
I know this is old and answered but I recently had to implement this and decided to make 2 simple jQuery plugins that might help for those interested
usage:
// 1
$('.container').toggleAttr('aria-hidden', "true");
// 2
$('.container').toggleAttrVal('aria-hidden', "true", "false");
1 - Toggles the entire attribute regardless if the original value doesn't match the one you provided.
2 - Toggles the value of the attribute between the 2 provided values.
// jquery toggle whole attribute
$.fn.toggleAttr = function(attr, val) {
var test = $(this).attr(attr);
if ( test ) {
// if attrib exists with ANY value, still remove it
$(this).removeAttr(attr);
} else {
$(this).attr(attr, val);
}
return this;
};
// jquery toggle just the attribute value
$.fn.toggleAttrVal = function(attr, val1, val2) {
var test = $(this).attr(attr);
if ( test === val1) {
$(this).attr(attr, val2);
return this;
}
if ( test === val2) {
$(this).attr(attr, val1);
return this;
}
// default to val1 if neither
$(this).attr(attr, val1);
return this;
};
This is how you would use it in the original example:
$(".list-toggle").click(function() {
$(".list-sort").toggleAttr('colspan', 6);
});
.has()
seems to be designed for this purpose. Since it returns a jQuery object, you have to test for .length
as well:
if ($('div#hello').has(target).length) {
alert('Target is a child of #hello');
}
As I have found and wrote in another topic - this applies to angular < 7 (not sure how it is in 7+)
Just for the future
we need to observe that [(ngModel)]="hero.name"
is just a short-cut that can be de-sugared to: [ngModel]="hero.name" (ngModelChange)="hero.name = $event"
.
So if we de-sugar code we would end up with:
<select (ngModelChange)="onModelChange()" [ngModel]="hero.name" (ngModelChange)="hero.name = $event">
or
<[ngModel]="hero.name" (ngModelChange)="hero.name = $event" select (ngModelChange)="onModelChange()">
If you inspect the above code you will notice that we end up with 2 ngModelChange
events and those need to be executed in some order.
Summing up: If you place ngModelChange
before ngModel
, you get the $event
as the new value, but your model object still holds previous value.
If you place it after ngModel
, the model will already have the new value.
Adding this piece of code after the val() seems to work:
$(":input#single").trigger('change');
html, body {
height:100%;
}
body {
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Consider it as an array of arrays and this will work for sure.
int mat[][] = { {10, 20, 30, 40, 50, 60, 70, 80, 90},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50, 51, 89},
};
for(int i=0; i<mat.length; i++) {
for(int j=0; j<mat[i].length; j++) {
System.out.println("Values at arr["+i+"]["+j+"] is "+mat[i][j]);
}
}
Using CONCAT(CONCAT(,),)
worked for me when concatenating more than two strings.
My problem required working with date strings (only) and creating YYYYMMDD
from YYYY-MM-DD
as follows (i.e. without converting to date format):
CONCAT(CONCAT(SUBSTR(DATECOL,1,4),SUBSTR(DATECOL,6,2)),SUBSTR(DATECOL,9,2)) AS YYYYMMDD
I tried all of the above to no avail. I had been using the phone for ages and suddenly the Organizer thought "this device is currently not connected". A reset of the phone fixed it for me (hold Home & Power until the Apple logo). I did so with it still connected to the MacBook, but it shouldn't be necessary.
I've used something like this before which addresses @scunliffes concern. It finds all instances of items with a class of (in this case .button), and assigns an ID and appends its index to the id name:
$(".button").attr('id', function (index) {_x000D_
return "button-" + index;_x000D_
});
_x000D_
So let's say you have 3 items with the class name of .button on a page. The result would be adding a unique ID to all of them (in addition to their class of "button").
In this case, #button-0, #button-1, #button-2, respectively. This can come in very handy. Simply replace ".button" in the first line with whatever class you want to target, and replace "button" in the return statement with whatever you'd like your unique ID to be. Hope this helps!
A correct snprintf
implementation:
int count = snprintf(NULL, 0, "%i", x);
PHP Manual said :
w Numeric representation of the day of the week
You can therefore construct a date with mktime, and use in it date("w", $yourTime);
The only objects in Python that have canonical names are modules, functions, and classes, and of course there is no guarantee that this canonical name has any meaning in any namespace after the function or class has been defined or the module imported. These names can also be modified after the objects are created so they may not always be particularly trustworthy.
What you want to do is not possible without recursively walking the tree of named objects; a name is a one-way reference to an object. A common or garden-variety Python object contains no references to its names. Imagine if every integer, every dict, every list, every Boolean needed to maintain a list of strings that represented names that referred to it! It would be an implementation nightmare, with little benefit to the programmer.
summary:
df = pd.DataFrame({'money': [100.456, 200.789], 'share': ['100,000', '200,000']})
print(df)
print(df.to_string(formatters={'money': '${:,.2f}'.format}))
for col_name in ('share',):
df[col_name] = df[col_name].map(lambda p: int(p.replace(',', '')))
print(df)
"""
money share
0 100.456 100,000
1 200.789 200,000
money share
0 $100.46 100,000
1 $200.79 200,000
money share
0 100.456 100000
1 200.789 200000
"""
Have you tried using the 'static' storage class similar to?:
public static class employee
{
static NameValueCollection appSetting = ConfigurationManager.AppSettings;
}
One possible reason this might happen is that the Application Pool in IIS is configured to run under some custom account and this account either doesn't exist or a wrong password has been provided, or the password has been changed. Look at the advanced properties of the Application Pool in IIS for which account it uses.
Also the Event Log might contain more information as to why the Application Pool is stopping immediately on the first request.
Code:
s = [2, 3, 1, 4, 5]
li = []
for i in range(len(s)):
li.append([s[i], i])
li.sort()
sort_index = []
for x in li:
sort_index.append(x[1])
print(sort_index)
Try this, It worked for me cheers!
I don't believe MySQL supports dynamic sql. You can do "prepared" statements which is similar, but different.
Here is an example:
mysql> PREPARE stmt FROM
-> 'select count(*)
-> from information_schema.schemata
-> where schema_name = ? or schema_name = ?'
;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> EXECUTE stmt
-> USING @schema1,@schema2
+----------+
| count(*) |
+----------+
| 2 |
+----------+
1 row in set (0.00 sec)
mysql> DEALLOCATE PREPARE stmt;
The prepared statements are often used to see an execution plan for a given query. Since they are executed with the execute command and the sql can be assigned to a variable you can approximate the some of the same behavior as dynamic sql.
Here is a good link about this:
Don't forget to deallocate the stmt
using the last line!
Good Luck!
I just installed VS 2015 Enterprise on Windows Server 2012 R2. The install was fast until it reached Update 1 which is past the 90% mark on the progress indicator. At that point, it took about 2 hours to complete. Be patient before you try anything more radical.
Microsoft SQL Server 2005 Express Edition Service Pack 4 on Windows Server 2012 R2
Those steps are based on previous howto from https://stackoverflow.com/users/2385/eduardo-molteni
This works with Microsoft SQL Server 2005 Express Edition Service Pack 4 http://www.microsoft.com/en-us/download/details.aspx?id=184
Why not hide the input element and replace it with a label element with the same content?
I puzzled over how the React TODOMVC app accomplished this same thing and this is the strategy they came up with.
To see it in action, check out the app below, and watch the CSS properties of the TODO items when you double click them and then click away.
http://todomvc.com/examples/react-backbone/#/
When you render the page you can have either an editable input, or a non-editable label with display:none; depending on your media query.
class Test
{
Dictionary<int, string> entities;
public string GetEntity(int code)
{
// java's get method returns null when the key has no mapping
// so we'll do the same
string val;
if (entities.TryGetValue(code, out val))
return val;
else
return null;
}
}
var id = "id" + Math.random().toString(16).slice(2)
Here's how it should look like in order to return a simple Yes
when it's checked.
<input type="checkbox" id="newsletter" name="newsletter" value="Yes" checked>
<label for="newsletter">i want to sign up for newsletter</label>
I also added the text as a label, it means you can click the text as well to check the box. Small but, personally I hate when sites make me aim my mouse at this tiny little check box.
When the form is submitted if the check box is checked $_POST['newsletter']
will equal Yes
. Just how you are checking to see if $_POST['name']
,$_POST['email']
, and $_POST['tel']
are empty you could do the same.
Here is an example of how you would add this into your email on the php side:
Underneath your existing code:
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['tel'];
Add:
$newsletter = $_POST['newsletter'];
if ($newsletter != 'Yes') {
$newsletter = 'No';
}
If the check box is checked it will add Yes
in your email if it was not checked it will add No
.
I'd go with the following:
Select max(start_ts)
from db
where trunc(start_ts) = date'13-may-2016'
EDIT
another way to deal with duplicate is you can do like this
var dic = slist.Select((element, index)=> new{element,index} )
.ToDictionary(ele=>ele.index.ToString(), ele=>ele.element);
or
easy way to do is
var res = list.ToDictionary(str => str, str=> str);
but make sure that there is no string is repeating...again otherewise above code will not work for you
if there is string is repeating than its better to do like this
Dictionary<string,string> dic= new Dictionary<string,string> ();
foreach(string s in Stringlist)
{
if(!dic.ContainsKey(s))
{
// dic.Add( value to dictionary
}
}
You haven't said which version you want, but an archive of the JDK 8 source code can be downloaded here, along with JDK 7 and JDK 6.
Additionally you can browse or clone the Mercurial repositories: 8, 7, 6.
For graph API v2.1, you can get the like count using 1 call only and, therefore, no need to go through the paging.
For example, to get the number of likes of http://www.imdb.com
https://graph.facebook.com/414652589771/likes?summary=1
Graph API Explorer https://developers.facebook.com/tools/explorer/?method=GET&path=414652589771%2Flikes%3Fsummary%3D1&version=v2.1
It is somehow not documented (at least at the moment I submit this answer...). I found the answer in https://stackoverflow.com/a/18198957/1822624
My initial take gave me something like:
public static int CountOccurrences(string original, string substring)
{
if (string.IsNullOrEmpty(substring))
return 0;
if (substring.Length == 1)
return CountOccurrences(original, substring[0]);
if (string.IsNullOrEmpty(original) ||
substring.Length > original.Length)
return 0;
int substringCount = 0;
for (int charIndex = 0; charIndex < original.Length; charIndex++)
{
for (int subCharIndex = 0, secondaryCharIndex = charIndex; subCharIndex < substring.Length && secondaryCharIndex < original.Length; subCharIndex++, secondaryCharIndex++)
{
if (substring[subCharIndex] != original[secondaryCharIndex])
goto continueOuter;
}
if (charIndex + substring.Length > original.Length)
break;
charIndex += substring.Length - 1;
substringCount++;
continueOuter:
;
}
return substringCount;
}
public static int CountOccurrences(string original, char @char)
{
if (string.IsNullOrEmpty(original))
return 0;
int substringCount = 0;
for (int charIndex = 0; charIndex < original.Length; charIndex++)
if (@char == original[charIndex])
substringCount++;
return substringCount;
}
The needle in a haystack approach using replace and division yields 21+ seconds whereas this takes about 15.2.
Edit after adding a bit which would add substring.Length - 1
to the charIndex (like it should), it's at 11.6 seconds.
Edit 2: I used a string which had 26 two-character strings, here are the times updated to the same sample texts:
Needle in a haystack (OP's version): 7.8 Seconds
Suggested mechanism: 4.6 seconds.
Edit 3: Adding the single character corner-case, it went to 1.2 seconds.
Edit 4: For context: 50 million iterations were used.
It seems there is an issue with glibc that affects the memory allocation in Pandas: https://github.com/pandas-dev/pandas/issues/2659
The monkey patch detailed on this issue has resolved the problem for me:
# monkeypatches.py
# Solving memory leak problem in pandas
# https://github.com/pandas-dev/pandas/issues/2659#issuecomment-12021083
import pandas as pd
from ctypes import cdll, CDLL
try:
cdll.LoadLibrary("libc.so.6")
libc = CDLL("libc.so.6")
libc.malloc_trim(0)
except (OSError, AttributeError):
libc = None
__old_del = getattr(pd.DataFrame, '__del__', None)
def __new_del(self):
if __old_del:
__old_del(self)
libc.malloc_trim(0)
if libc:
print('Applying monkeypatch for pd.DataFrame.__del__', file=sys.stderr)
pd.DataFrame.__del__ = __new_del
else:
print('Skipping monkeypatch for pd.DataFrame.__del__: libc or malloc_trim() not found', file=sys.stderr)
A little bit late to the party... but I found this as a solution for me when having "blocked"-Error in chrome:
Blocking resources whose URLs contain both
\n
and<
characters.
More info here: https://www.chromestatus.com/feature/5735596811091968
In the case of no repeats and no order, the following EqualityComparer can be used to allow collections as dictionary keys:
public class SetComparer<T> : IEqualityComparer<IEnumerable<T>>
where T:IComparable<T>
{
public bool Equals(IEnumerable<T> first, IEnumerable<T> second)
{
if (first == second)
return true;
if ((first == null) || (second == null))
return false;
return first.ToHashSet().SetEquals(second);
}
public int GetHashCode(IEnumerable<T> enumerable)
{
int hash = 17;
foreach (T val in enumerable.OrderBy(x => x))
hash = hash * 23 + val.GetHashCode();
return hash;
}
}
Here is the ToHashSet() implementation I used. The hash code algorithm comes from Effective Java (by way of Jon Skeet).
In PowerShell, I like to use:
robocopy src dest | Out-Null
It avoids having to remember all the command line switches.
In Ubuntu 12.10 (Quantal Quetzal) or later, the certificates are held in the ca-certificates-java package. Using -Djavax.net.ssl.trustStore=/etc/ssl/certs/java/cacerts
will pick them up regardless of what JDK you're using.
In my case, the problem was caused by some Response.Write commands at Master Page of the website (code behind). They were there only for debugging purposes (that's not the best way, I know)...
You need to handle an event on Form1 that is raised as a result of user interaction. For example, if you have a "Settings" button that the user clicks in order to show the settings form (Form2), you should handle the Click
event for that button:
private void settingsButton_Click(Object sender, EventArgs e)
{
// Create a new instance of the Form2 class
Form2 settingsForm = new Form2();
// Show the settings form
settingsForm.Show();
}
In addition to the Show
method, you could also choose to use the ShowDialog
method. The difference is that the latter shows the form as a modal dialog, meaning that the user cannot interact with the other forms in your application until they close the modal form. This is the same way that a message box works. The ShowDialog
method also returns a value indicating how the form was closed.
When the user closes the settings form (by clicking the "X" in the title bar, for example), Windows will automatically take care of closing it.
If you want to close it yourself before the user asks to close it, you can call the form's Close
method:
this.Close();
SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE IN ('FUNCTION','PROCEDURE','PACKAGE')
The column STATUS tells you whether the object is VALID or INVALID. If it is invalid, you have to try a recompile, ORACLE can't tell you if it will work before.
Try using this library: https://github.com/jakiestfu/Blur.js-II
That should do it for ya.
Since I had everything being forwarded to index.php anyway I thought I would try setting the headers in PHP instead of the .htaccess file and it worked! YAY! Here's what I added to index.php for anyone else having this problem.
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
// should do a check here to match $_SERVER['HTTP_ORIGIN'] to a
// whitelist of safe domains
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
}
credit goes to slashingweapon for his answer on this question
Because I'm using Slim I added this route so that OPTIONS requests get a HTTP 200 response
// return HTTP 200 for HTTP OPTIONS requests
$app->map('/:x+', function($x) {
http_response_code(200);
})->via('OPTIONS');
Well you can hide the close button by changing the FormBorderStyle from the properties section or programmatically in the constructor using:
public Form1()
{
InitializeComponent();
this.FormBorderStyle = FormBorderStyle.None;
}
then you create a menu strip item to exit the application.
cheers
Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
//section.SectionInformation.UnprotectSection();
section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
config.Save();
I made a general class for combinations in C++. It is used like this.
char ar[] = "0ABCDEFGH";
nCr ncr(8, 3);
while(ncr.next()) {
for(int i=0; i<ncr.size(); i++) cout << ar[ncr[i]];
cout << ' ';
}
My library ncr[i] returns from 1, not from 0. That's why there is 0 in the array. If you want to consider order, just chage nCr class to nPr. Usage is identical.
Result
ABC ABD ABE ABF ABG ABH ACD ACE ACF ACG ACH ADE ADF ADG ADH AEF AEG AEH AFG AFH AGH BCD BCE BCF BCG BCH BDE BDF BDG BDH BEF BEG BEH BFG BFH BGH CDE CDF CDG CDH CEF CEG CEH CFG CFH CGH DEF DEG DEH DFG DFH DGH EFG EFH EGH FGH
Here goes the header file.
#pragma once
#include <exception>
class NRexception : public std::exception
{
public:
virtual const char* what() const throw() {
return "Combination : N, R should be positive integer!!";
}
};
class Combination
{
public:
Combination(int n, int r);
virtual ~Combination() { delete [] ar;}
int& operator[](unsigned i) {return ar[i];}
bool next();
int size() {return r;}
static int factorial(int n);
protected:
int* ar;
int n, r;
};
class nCr : public Combination
{
public:
nCr(int n, int r);
bool next();
int count() const;
};
class nTr : public Combination
{
public:
nTr(int n, int r);
bool next();
int count() const;
};
class nHr : public nTr
{
public:
nHr(int n, int r) : nTr(n,r) {}
bool next();
int count() const;
};
class nPr : public Combination
{
public:
nPr(int n, int r);
virtual ~nPr() {delete [] on;}
bool next();
void rewind();
int count() const;
private:
bool* on;
void inc_ar(int i);
};
And the implementation.
#include "combi.h"
#include <set>
#include<cmath>
Combination::Combination(int n, int r)
{
//if(n < 1 || r < 1) throw NRexception();
ar = new int[r];
this->n = n;
this->r = r;
}
int Combination::factorial(int n)
{
return n == 1 ? n : n * factorial(n-1);
}
int nPr::count() const
{
return factorial(n)/factorial(n-r);
}
int nCr::count() const
{
return factorial(n)/factorial(n-r)/factorial(r);
}
int nTr::count() const
{
return pow(n, r);
}
int nHr::count() const
{
return factorial(n+r-1)/factorial(n-1)/factorial(r);
}
nCr::nCr(int n, int r) : Combination(n, r)
{
if(r == 0) return;
for(int i=0; i<r-1; i++) ar[i] = i + 1;
ar[r-1] = r-1;
}
nTr::nTr(int n, int r) : Combination(n, r)
{
for(int i=0; i<r-1; i++) ar[i] = 1;
ar[r-1] = 0;
}
bool nCr::next()
{
if(r == 0) return false;
ar[r-1]++;
int i = r-1;
while(ar[i] == n-r+2+i) {
if(--i == -1) return false;
ar[i]++;
}
while(i < r-1) ar[i+1] = ar[i++] + 1;
return true;
}
bool nTr::next()
{
ar[r-1]++;
int i = r-1;
while(ar[i] == n+1) {
ar[i] = 1;
if(--i == -1) return false;
ar[i]++;
}
return true;
}
bool nHr::next()
{
ar[r-1]++;
int i = r-1;
while(ar[i] == n+1) {
if(--i == -1) return false;
ar[i]++;
}
while(i < r-1) ar[i+1] = ar[i++];
return true;
}
nPr::nPr(int n, int r) : Combination(n, r)
{
on = new bool[n+2];
for(int i=0; i<n+2; i++) on[i] = false;
for(int i=0; i<r; i++) {
ar[i] = i + 1;
on[i] = true;
}
ar[r-1] = 0;
}
void nPr::rewind()
{
for(int i=0; i<r; i++) {
ar[i] = i + 1;
on[i] = true;
}
ar[r-1] = 0;
}
bool nPr::next()
{
inc_ar(r-1);
int i = r-1;
while(ar[i] == n+1) {
if(--i == -1) return false;
inc_ar(i);
}
while(i < r-1) {
ar[++i] = 0;
inc_ar(i);
}
return true;
}
void nPr::inc_ar(int i)
{
on[ar[i]] = false;
while(on[++ar[i]]);
if(ar[i] != n+1) on[ar[i]] = true;
}
It's worth mentioning that in some cases
File myFolder = new File("directory");
doesn't point to the root elements. For example when you place your application on C:
drive (C:\myApp.jar
) then myFolder
points to (windows)
C:\Users\USERNAME\directory
instead of
C:\Directory
Thought this was a genuine defect but it turns out that my console size was limited, and caused the old content past 80000 characters to be cut off.
Right click on the console for the preferences and increase the console size limit.
try this
<c:forEach items="${list}" var="map">
<tr>
<c:forEach items="${map}" var="entry">
<td>${entry.value}</td>
</c:forEach>
</tr>
</c:forEach>
It seems like the 32-bit version of Excel was not installed. Remember that SSDT is a 32-bit IDE. Therefore, when data is access from SSDT the 32-bit data providers are used. When running the package outside of SSDT it runs in 64-bit mode (not always, but mostly) and uses the 64-bit data providers.
Always keep in mind that if you want to run your package in 64-bit (which you should aim for) you will need both the 32-bit data providers (for development in SSDT) as well as the 64-bit data providers (for executing the package in production).
I downloaded the 32-bit access drivers from:
After installation, I could see the worksheets
Source:
What is the difference between NULL, ‘\0’ and 0
"null character (NUL)" is easiest to rule out. '\0'
is a character literal.
In C, it is implemented as int
, so, it's the same as 0, which is of INT_TYPE_SIZE
. In C++, character literal is implemented as char
, which is 1 byte. This is normally different from NULL
or 0
.
Next, NULL
is a pointer value that specifies that a variable does not point to any address space. Set aside the fact that it is usually implemented as zeros, it must be able to express the full address space of the architecture. Thus, on a 32-bit architecture NULL (likely) is 4-byte and on 64-bit architecture 8-byte. This is up to the implementation of C.
Finally, the literal 0
is of type int
, which is of size INT_TYPE_SIZE
. The default value of INT_TYPE_SIZE
could be different depending on architecture.
Apple wrote:
The 64-bit data model used by Mac OS X is known as "LP64". This is the common data model used by other 64-bit UNIX systems from Sun and SGI as well as 64-bit Linux. The LP64 data model defines the primitive types as follows:
- ints are 32-bit
- longs are 64-bit
- long-longs are also 64-bit
- pointers are 64-bit
Wikipedia 64-bit:
Microsoft's VC++ compiler uses the LLP64 model.
64-bit data models
Data model short int long long long pointers Sample operating systems
LLP64 16 32 32 64 64 Microsoft Win64 (X64/IA64)
LP64 16 32 64 64 64 Most Unix and Unix-like systems (Solaris, Linux, etc.)
ILP64 16 64 64 64 64 HAL
SILP64 64 64 64 64 64 ?
Edit: Added more on the character literal.
#include <stdio.h>
int main(void) {
printf("%d", sizeof('\0'));
return 0;
}
The above code returns 4 on gcc and 1 on g++.
There is a minimal amount of "default" buffer when you startup a 'screen' session within your 'putty session'. I use screens a lot in my work, so I can tell you that you will not have a combination of 'screen' buffer & 'putty' buffer within your 'screen' session.
Setting the default number of scrollback lines by adding defscrollback 10000
to your ~/.screenrc
file is the correct solution.
By the way, I use "defscrollback 200000" in my ./screenrc
file.
This is what I do: perl -M{cpan_module}
If you don't receive any errors there is a good chance that the module is installed.
Here's my automatic solution...
This will follow your javac
executable's symlink (setup by yum
and/or alternatives --config java
) backwards to find the JAVA_HOME
. (Toss this in your in your /etc/profile
):
export JAVA_HOME=$(readlink -f /usr/bin/javac | sed 's:/bin/javac$::')
If you wanted a stable path (refreshed on boot) launch something like this:
export JAVA_HOME=$(readlink -f /usr/bin/javac | sed 's:/bin/javac$::')
ln -sfn "${JAVA_HOME}" /usr/lib/jvm/jdk-current
I'm kinda shocked the latter still isn't baked into alternatives
.
The following hack works:
xmlns:tools="http://schemas.android.com/tools"
line in the
manifest tag tools:replace="android:icon,android:theme,android:allowBackup,label"
in the application tagAnother option:
UPDATE `table` SET the_col = current_timestamp
Looks odd, but works as expected. If I had to guess, I'd wager this is slightly faster than calling now()
.
Types are dependent to your initialization:
var IsLoggedIn1 = "true"; //string
var IsLoggedIn2 = 1; //integer
var IsLoggedIn3 = true; //bool
But take a look at this example:
var IsLoggedIn1 = "true"; //string
IsLoggedIn1 = true; //now your variable is a boolean
Your variables' type depends on the assigned value in JavaScript.
fn
literally refers to the jquery prototype
.
This line of code is in the source code:
jQuery.fn = jQuery.prototype = {
//list of functions available to the jQuery api
}
But the real tool behind fn
is its availability to hook your own functionality into jQuery. Remember that jquery will be the parent scope to your function, so this
will refer to the jquery object.
$.fn.myExtension = function(){
var currentjQueryObject = this;
//work with currentObject
return this;//you can include this if you would like to support chaining
};
So here is a simple example of that. Lets say I want to make two extensions, one which puts a blue border, and which colors the text blue, and I want them chained.
jsFiddle Demo
$.fn.blueBorder = function(){
this.each(function(){
$(this).css("border","solid blue 2px");
});
return this;
};
$.fn.blueText = function(){
this.each(function(){
$(this).css("color","blue");
});
return this;
};
Now you can use those against a class like this:
$('.blue').blueBorder().blueText();
(I know this is best done with css such as applying different class names, but please keep in mind this is just a demo to show the concept)
This answer has a good example of a full fledged extension.
For persistently setting environment variables, you can use one of the existing roles over at Ansible Galaxy. I recommend weareinteractive.environment.
Using ansible-galaxy:
$ ansible-galaxy install weareinteractive.environment
Using requirements.yml:
- src: franklinkim.environment
Then in your playbook:
- hosts: all
sudo: yes
roles:
- role: franklinkim.environment
environment_config:
NODE_ENV: staging
DATABASE_NAME: staging
You could check if $profitloss < 0
if ($profitloss < 0):
echo "Less than 0\n";
endif;
This works because of PHP's string comparison logic. Simply you can check...
if ($startdate < $date) {// do something}
if ($startdate > $date) {// do something}
Both dates must be in the same format. Digits need to be zero-padded to the left and ordered from most significant to least significant. Y-m-d
and Y-m-d H:i:s
satisfy these conditions.
Please use Homebrew Formulae page to see the list of installable packages. https://formulae.brew.sh/formula/
To install any package => command to use is :
brew install node
Please click on this link it should work ..
http://www.php-guru.in/2013/html-to-pdf-conversion-in-codeigniter/
Or you can see below
There are number of PHP libraries on the web to convert HTML page to PDF file. They are easy to implement and deploy when you are working on any web application in core PHP. But when we try to integrate this libraries with any framework or template, then it becomes very tedious work if the framework which we are using does not have its own library to integrate it with any PDF library. The same situation came in front of me when there was one requirement to convert HTML page to PDF file and the framework I was using was codeigniter.
I searched on web and got number of PHP libraries to convert HTML page to PDF file. After lot of research and googling I decided to go with TCPDF PHP library to convert HTML page to PDF file for my requirement. I found TCPDf PHP library quite easy to integrate with codeigniter and stated working on it. After successfully completing my integration of codeigniter and TCPDF, I thought of sharing this script on web.
Now, let’s start with implimentation of the code.
Download the TCPDF library code, you can download it from TCPDF website http://www.tcpdf.org/.
Now create “tcpdf” folder in “application/helpers/” directory of your web application which is developed in codeigniter. Copy all TCPDF library files and paste it in “application/helpers/tcpdf/” directory. Update the configuration file “tcpdf_config.php” of TCPDF, which is located in “application/helpers/tcpdf/config” directory, do changes according to your applicatoin requirements. We can set logo, font, font size, with, height, header etc in the cofing file. Give read, write permissions to “cache” folder which is there in tcpdf folder. After defining your directory structure, updating configuration file and assigning permissions, here starts your actual coding part.
Create one PHP helper file in “application/helpers/” directory of codeigniter, say “pdf_helper.php”, then copy below given code and paste it in helper file
Helper: application/helpers/pdf_helper.php
function tcpdf()
{
require_once('tcpdf/config/lang/eng.php');
require_once('tcpdf/tcpdf.php');
}
Then in controller file call the above helper, suppose our controller file is “createpdf.php” and it has method as pdf(), so the method pdf() will load the “pdf_helper” helper and will also have any other code.
Controller: application/controllers/createpdf.php
function pdf()
{
$this->load->helper('pdf_helper');
/*
---- ---- ---- ----
your code here
---- ---- ---- ----
*/
$this->load->view('pdfreport', $data);
}
Now create one view file, say “pdfreport.php” in “application/views/” directory, which is also loaded in pdf() method in controller. So in view file we can directly call the tcpdf() function which we have defined in “pdf_helper” helper, which will load all required TCPDF classes, functions, variable etc. Then we can directly use the TCPDF example codes as it is in our current controller or view. Now in out current view “pdfreport” copy the given code below:
View: application/views/pdfreport.php
tcpdf();
$obj_pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$obj_pdf->SetCreator(PDF_CREATOR);
$title = "PDF Report";
$obj_pdf->SetTitle($title);
$obj_pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, $title, PDF_HEADER_STRING);
$obj_pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$obj_pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
$obj_pdf->SetDefaultMonospacedFont('helvetica');
$obj_pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$obj_pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
$obj_pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$obj_pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$obj_pdf->SetFont('helvetica', '', 9);
$obj_pdf->setFontSubsetting(false);
$obj_pdf->AddPage();
ob_start();
// we can have any view part here like HTML, PHP etc
$content = ob_get_contents();
ob_end_clean();
$obj_pdf->writeHTML($content, true, false, true, false, '');
$obj_pdf->Output('output.pdf', 'I');
Thus our HTML page will be converted to PDF using TCPDF in CodeIgniter. We can also embed images,css,modifications in PDF file by using TCPDF library.
What version of Excel?
In general, you cannot change the column letters. They are part of the Excel system.
You can use a row in the sheet to enter headers for a table that you are using. The table headers can be descriptive column names.
In Excel 2007 and later, you can convert a range of data into an Excel Table (Insert Ribbon > Table). An Excel Table can use structured table references instead of cell addresses, so the labels in the first row of the table now serve as a name reference for the data in the column.
If you have an Excel Table in your sheet (Excel 2007 and later) and scroll down, the column letters will be replaced with the column headers for the table column.
If this does not answer your question, please consider editing your question to include the detail you want to learn about.
Having the .htaccess file on the root folder, add this line. Make sure to delete all other useless rules you tried before:
Options -Indexes
Or try:
Options All -Indexes
^[0-9][0-9]?[^A-Za-z0-9]?po$
You can test it here: http://www.regextester.com/
To use this in C#,
Regex r = new Regex(@"^[0-9][0-9]?[^A-Za-z0-9]?po$");
if (r.Match(someText).Success) {
//Do Something
}
Remember, @ is a useful symbol that means the parser takes the string literally (eg, you don't need to write \\ for one backslash)
Using history.listen
For example like below:
In your component,
componentWillMount() {
this.props.history.listen(() => {
// Detecting, user has changed URL
console.info(this.props.history.location.pathname);
});
}
If you only need the indices, you could try numpy.ndindex
:
>>> a = numpy.arange(9).reshape(3, 3)
>>> [(x, y) for x, y in numpy.ndindex(a.shape)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
Shape shape = new Shape();
Shape.ZShape zshape = shape.new ZShape();
I am creating a java method for this purpose with dynamic character
public String insertSpace(String myString,int indexno,char myChar){
myString=myString.substring(0, indexno)+ myChar+myString.substring(indexno);
System.out.println(myString);
return myString;
}
In the load events, use Me.Hide
.
In WebBrowser1.DocuementCompleted, use Me.Show
The answer seems to be just no.
Although there are many good other answers, they either just hide the uglyness (which I did not ask for) or introduce new problems (edge cases).
Cookies are only sent at the time of the request, and therefore cannot be retrieved as soon as it is assigned (only available after reloading).
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.
Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.
The command
show full processlist
can be replaced by:
SELECT * FROM information_schema.processlist
but if you go with the latter version you can add WHERE
clause to it:
SELECT * FROM information_schema.processlist WHERE `INFO` LIKE 'SELECT %';
For more information visit this
The secret key is combined with the header and the payload to create a unique hash. You are only able to verify this hash if you have the secret key.
You can choose a good, long password. Or you can generate it from a site like this.
Example (but don't use this one now):
8Zz5tw0Ionm3XPZZfN0NOml3z9FMfmpgXwovR9fp6ryDIoGRM8EPHAB6iHsc0fb
I payed attention that lots of people are looking for strtolower()
in JavaScript. They are expecting the same function name as in other languages, that's why this post is here.
I would recommend using native Javascript function
"SomE StriNg".toLowerCase()
Here's the function that behaves exactly the same as PHP's one (for those who are porting PHP code into js)
function strToLower (str) {
return String(str).toLowerCase();
}
By default git revert
refuses to revert a merge commit as what that actually means is ambiguous. I presume that your HEAD
is in fact a merge commit.
If you want to revert the merge commit, you have to specify which parent of the merge you want to consider to be the main trunk, i.e. what you want to revert to.
Often this will be parent number one, for example if you were on master
and did git merge unwanted
and then decided to revert the merge of unwanted
. The first parent would be your pre-merge master
branch and the second parent would be the tip of unwanted
.
In this case you could do:
git revert -m 1 HEAD
Finally got this error to go away on a restore. I moved to SQL2012 out of frustration, but I guess this would probably still work on 2008R2. I had to use the logical names:
RESTORE FILELISTONLY
FROM DISK = ‘location of your.bak file’
And from there I ran a restore statement with MOVE
using logical names.
RESTORE DATABASE database1
FROM DISK = '\\database path\database.bak'
WITH
MOVE 'File_Data' TO 'E:\location\database.mdf',
MOVE 'File_DOCS' TO 'E:\location\database_1.ndf',
MOVE 'file' TO 'E:\location\database_2.ndf',
MOVE 'file' TO 'E:\location\database_3.ndf',
MOVE 'file_Log' TO 'E:\location\database.ldf'
When it was done restoring, I almost wept with joy.
Good luck!
I can not use the "int length" constructor for
StringBuilder
since the length of my CLOB is longer than aint
and needs along
value.
If the CLOB length is greater than fits in an int, the CLOB data won't fit in a String either. You'll have to use a streaming approach to deal with this much XML data.
If the actual length of the CLOB is smaller than Integer.MAX_VALUE
, just force the long
to int
by putting (int)
in front of it.
Slightly more compact:
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df = df.sort_index()
print(df)
Note:
sort
has been deprecated, replaced by sort_index
for this scenarioinplace
as it is usually harder to read and prevents chaining. See explanation in answer here:
Pandas: peculiar performance drop for inplace rename after dropnaI think your issue may be in the url pattern. Changing
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/Register</url-pattern>
</servlet-mapping>
and
<form action="/Register" method="post">
may fix your problem
See this blog post. It uses jQuery, but it should help you even if you are not using it.
Basically you add this to your document.ready()
$('iframe').load(function() {
RunAfterIFrameLoaded();
});
I have added line
$this->_productCollection->addAttributeToSelect('releasedate');
in
app/code/core/Mage/Catalog/Block/Product/List.php on line 95
in function _getProductCollection()
and then call it in
app/design/frontend/default/hellopress/template/catalog/product/list.phtml
By writing code
<div><?php echo $this->__('Release Date: %s', $this->dateFormat($_product->getReleasedate())) ?>
</div>
Now it is working in Magento 1.4.x
You need to pass an array of element to jsx
. The problem is that forEach
does not return anything (i.e it returns undefined
). So it's better to use map
because map
returns an array:
class QuestionSet extends Component {
render(){
<div className="container">
<h1>{this.props.question.text}</h1>
{this.props.question.answers.map((answer, i) => {
console.log("Entered");
// Return the element. Also pass key
return (<Answer key={answer} answer={answer} />)
})}
}
export default QuestionSet;
If you are running multiple instances of Tomcat on a single host you should set CATALINA_BASE
to be equal to the .../tomcat_instance1
or .../tomcat_instance2
directory as appropriate for each instance and the CATALINA_HOME
environment variable to the common Tomcat installation whose files will be shared between the two instances.
The CATALINA_BASE
environment is optional if you are running a single Tomcat instance on the host and will default to CATALINA_HOME
in that case. If you are running multiple instances as you are it should be provided.
There is a pretty good description of this setup in the RUNNING.txt
file in the root of the Apache Tomcat distribution under the heading Advanced Configuration - Multiple Tomcat Instances
You can render your icon using the SVG Path notation.
See Google documentation for more information.
Here is a basic example:
var icon = {
path: "M-20,0a20,20 0 1,0 40,0a20,20 0 1,0 -40,0",
fillColor: '#FF0000',
fillOpacity: .6,
anchor: new google.maps.Point(0,0),
strokeWeight: 0,
scale: 1
}
var marker = new google.maps.Marker({
position: event.latLng,
map: map,
draggable: false,
icon: icon
});
Here is a working example on how to display and scale a marker SVG icon:
Edit:
Another example here with a complex icon:
Edit 2:
And here is how you can have a SVG file as an icon:
This code is working fine for me,
var a = serializer.Deserialize<List<Entity>>(json);
Instead of downloading separate java files as suggested by Veer, you could just add this JAR file to your package.
To add the jar file to your project in Eclipse, do the following:
Try this
test2.removeAll(test1);
Removes from this set all of its elements that are contained in the specified collection (optional operation). If the specified collection is also a set, this operation effectively modifies this set so that its value is the asymmetric set difference of the two sets.
==
performs a reference equality check, whether the 2 objects (strings in this case) refer to the same object in the memory.
The equals()
method will check whether the contents or the states of 2 objects are the same.
Obviously ==
is faster, but will (might) give false results in many cases if you just want to tell if 2 String
s hold the same text.
Definitely the use of the equals()
method is recommended.
Don't worry about the performance. Some things to encourage using String.equals()
:
String.equals()
first checks for reference equality (using ==
), and if the 2 strings are the same by reference, no further calculation is performed!String.equals()
will next check the lengths of the strings. This is also a fast operation because the String
class stores the length of the string, no need to count the characters or code points. If the lengths differ, no further check is performed, we know they cannot be equal.When all is said and done, even if we have a guarantee that the strings are interns, using the equals()
method is still not that overhead that one might think, definitely the recommended way. If you want an efficient reference check, then use enums where it is guaranteed by the language specification and implementation that the same enum value will be the same object (by reference).
The answer shared by @mockinterface is correct. Although I would like to add my 2 cents to it.
If someone is using frameworks like scrapy
the you will have to use /html/body//a[contains(@href,'com')][2]/@href
along with get() like this:
response.xpath('//a[contains(@href,'com')][2]/@href').get()
Just using this code: If you want backpressed disable, you dont use super.OnBackPressed();
@Override
public void onBackPressed() {
}
May be it's too late to answer, but i found a very simple way to do this(without a hack).
Hope it helps
In Angular (currently on Angular-6) .subscribe()
is a method on the Observable type. The Observable type is a utility that asynchronously or synchronously streams data to a variety of components or services that have subscribed to the observable.
The observable is an implementation/abstraction over the promise chain and will be a part of ES7 as a proposed and very supported feature. In Angular it is used internally due to rxjs being a development dependency.
An observable itself can be thought of as a stream of data coming from a source, in Angular this source is an API-endpoint, a service, a database or another observable. But the power it has is that it's not expecting a single response. It can have one or many values that are returned.
Link to rxjs for observable/subscribe docs here: https://rxjs-dev.firebaseapp.com/api/index/class/Observable#subscribe-
Subscribe takes 3 methods as parameters each are functions:
Within each of these, there is the potentional to pipe (or chain) other utilities called operators onto the results to change the form or perform some layered logic.
In the simple example above:
.subscribe(hero => this.hero = hero);
basically says on this observable take the hero being emitted and set it to this.hero
.
Adding this answer to give more context to Observables based off the documentation and my understanding.
You can customize material styles by setting different color properties. For example custom application theme
<style name="CustomAppTheme" parent="Theme.AppCompat">
<item name="android:textColorPrimaryDisableOnly">#00838f</item>
<item name="colorAccent">#e91e63</item>
</style>
Custom switch theme
<style name="MySwitch" parent="@style/Widget.AppCompat.CompoundButton.Switch">
<item name="android:textColorPrimaryDisableOnly">#b71c1c</item>
<item name="android:colorControlActivated">#1b5e20</item>
<item name="android:colorForeground">#f57f17</item>
<item name="android:textAppearance">@style/TextAppearance.AppCompat</item>
</style>
You can customize switch track and switch thumb like below image by defining xml drawables. For more information http://www.zoftino.com/android-switch-button-and-custom-switch-examples
This is all perfectly normal. Microsoft added sequences
in SQL Server 2012, finally, i might add and changed the way identity keys are generated. Have a look here for some explanation.
If you want to have the old behaviour, you can:
Select yesterday to check past days or not with help of moment().subtract(1, "day");
Reference:- http://momentjs.com/docs/#/manipulating/subtract/
function myFunction() {_x000D_
var yesterday = moment().subtract(1, "day").format("YYYY-MM-DD");_x000D_
var SpecialToDate = document.getElementById("theDate").value;_x000D_
_x000D_
if (moment(SpecialToDate, "YYYY-MM-DD", true).isAfter(yesterday)) {_x000D_
alert("date is today or in future");_x000D_
console.log("date is today or in future");_x000D_
} else {_x000D_
alert("date is in the past");_x000D_
console.log("date is in the past");_x000D_
}_x000D_
}
_x000D_
<script src="http://momentjs.com/downloads/moment.js"></script>_x000D_
<input type="date" id="theDate" onchange="myFunction()">
_x000D_
select to_timestamp(cast(epoch_ms/1000 as bigint))::date
worked for me
You could do it this way ..
var mystr = 'is my name.';_x000D_
mystr = mystr.replace (/^/,'John ');_x000D_
_x000D_
console.log(mystr);
_x000D_
disclaimer: http://xkcd.com/208/
So when you call EntityManager.persist()
, it only makes the entity get managed by the EntityManager
and adds it (entity instance) to the Persistence Context
. An Explicit flush()
will make the entity now residing in the Persistence Context
to be moved to the database (using a SQL).
Without flush(), this (moving of entity from Persistence Context
to the database) will happen when the Transaction to which this Persistence Context
is associated is committed.
A simple tweak to Paresh's solution:
Date date = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(date);
I know this question is already answered, a long time ago, but this is for other people that may end up here and are having trouble finding what they need. I had trouble finding an existing plugin that did exactly what I needed, so I wrote my own jQuery UI plugin to accomplish this task. It's based on the combobox example on the jQuery UI site. Hopefully it might help someone.
This snippet will determine if the element has children using the :parent
selector:
if ($('#myfav').is(':parent')) {
// do something
}
Note that :parent
also considers an element with one or more text nodes to be a parent.
Thus the div
elements in <div>some text</div>
and <div><span>some text</span></div>
will each be considered a parent but <div></div>
is not a parent.
The -Xmx option changes the maximum Heap Space for the VM. java -Xmx1024m means that the VM can allocate a maximum of 1024 MB. In layman terms this means that the application can use a maximum of 1024MB of memory.
You can emulate javascript's encodeURIComponent
in perl. Here's the command:
perl -pe 's/([^a-zA-Z0-9_.!~*()'\''-])/sprintf("%%%02X", ord($1))/ge'
You could set this as a bash alias in .bash_profile
:
alias encodeURIComponent='perl -pe '\''s/([^a-zA-Z0-9_.!~*()'\''\'\'''\''-])/sprintf("%%%02X",ord($1))/ge'\'
Now you can pipe into encodeURIComponent
:
$ echo -n 'hèllo wôrld!' | encodeURIComponent
h%C3%A8llo%20w%C3%B4rld!
In addition to the answers above the command below will also work. I post it because it makes more sense to me. In each case it is 'using x-value-column: y-value-column'
plot 'ls.dat' using 1:2, 'ls.dat' using 1:3, 'ls.dat' using 1:4
note that the command above assumes that you have a file named ls.dat
with tab separated columns of data where column 1 is x, column 2 is y1, column 3 is y2 and column 4 is y3.
open powershell and run below command:
import-csv C:\Users\Documents\Weekly_Status.csv | export-csv C:\Users\Documents\Weekly_Status2.csv -NoTypeInformation -Encoding UTF8
I struggled with the same issue when trying to feed floats to the classifiers. I wanted to keep floats and not integers for accuracy. Try using regressor algorithms. For example:
import numpy as np
from sklearn import linear_model
from sklearn import svm
classifiers = [
svm.SVR(),
linear_model.SGDRegressor(),
linear_model.BayesianRidge(),
linear_model.LassoLars(),
linear_model.ARDRegression(),
linear_model.PassiveAggressiveRegressor(),
linear_model.TheilSenRegressor(),
linear_model.LinearRegression()]
trainingData = np.array([ [2.3, 4.3, 2.5], [1.3, 5.2, 5.2], [3.3, 2.9, 0.8], [3.1, 4.3, 4.0] ])
trainingScores = np.array( [3.4, 7.5, 4.5, 1.6] )
predictionData = np.array([ [2.5, 2.4, 2.7], [2.7, 3.2, 1.2] ])
for item in classifiers:
print(item)
clf = item
clf.fit(trainingData, trainingScores)
print(clf.predict(predictionData),'\n')
Here is my answer using the group by clause.
SELECT *
FROM feeds f
LEFT JOIN
(
SELECT artist_id, feed_id
FROM feeds_artists
GROUP BY artist_id, feed_id
) fa ON fa.feed_id = f.id
LEFT JOIN artists a ON a.artist_id = fa.artist_id
To conditionally check the length of the string, use CASE
.
SELECT CASE WHEN LEN(comments) <= 60
THEN comments
ELSE LEFT(comments, 60) + '...'
END As Comments
FROM myView
upgrade numpy to the latest version
pip install numpy --upgrade
Best:
std::string subCondition;
This creates an empty string.
This:
std::string myStr = "";
does a copy initialization - creates a temporary string from ""
, and then uses the copy constructor to create myStr
.
Bonus:
std::string myStr("");
does a direct initialization and uses the string(const char*)
constructor.
To check if a string is empty, just use empty()
.
for future visitors, you can add this functon that allow user to enter only numbers: you will only have to add jquery and the class name to the input check that into http://jsfiddle.net/celia/dvnL9has/2/
$('.phone_number').keypress(function(event){
var numero= String.fromCharCode(event.keyCode);
var myArray = ['0','1','2','3','4','5','6','7','8','9',0,1,2,3,4,5,6,7,8,9];
index = myArray.indexOf(numero);// 1
var longeur= $('.phone_number').val().length;
if(window.getSelection){
text = window.getSelection().toString();
} if(index>=0&text.length>0){
}else if(index>=0&longeur<10){
}else {return false;} });
Yes in Notepad++ you can do that!
Some hotkeys regarding comments:
Source: shortcutworld.com from the Comment / uncomment section.
On the link you will find many other useful shortcuts too.
The easiest might be:
Array(1, 2, 3) :+ 4
Actually, Array can be implcitly transformed in a WrappedArray