Shared preferences introduced a getStringSet
and putStringSet
methods in API Level 11, but that's not compatible with older versions of Android (which are still popular), and also is limited to sets of strings.
Android does not provide better methods, and looping over maps and arrays for saving and loading them is not very easy and clean, specially for arrays. But a better implementation isn't that hard:
package com.example.utils;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Context;
import android.content.SharedPreferences;
public class JSONSharedPreferences {
private static final String PREFIX = "json";
public static void saveJSONObject(Context c, String prefName, String key, JSONObject object) {
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(JSONSharedPreferences.PREFIX+key, object.toString());
editor.commit();
}
public static void saveJSONArray(Context c, String prefName, String key, JSONArray array) {
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(JSONSharedPreferences.PREFIX+key, array.toString());
editor.commit();
}
public static JSONObject loadJSONObject(Context c, String prefName, String key) throws JSONException {
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
return new JSONObject(settings.getString(JSONSharedPreferences.PREFIX+key, "{}"));
}
public static JSONArray loadJSONArray(Context c, String prefName, String key) throws JSONException {
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
return new JSONArray(settings.getString(JSONSharedPreferences.PREFIX+key, "[]"));
}
public static void remove(Context c, String prefName, String key) {
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
if (settings.contains(JSONSharedPreferences.PREFIX+key)) {
SharedPreferences.Editor editor = settings.edit();
editor.remove(JSONSharedPreferences.PREFIX+key);
editor.commit();
}
}
}
Now you can save any collection in shared preferences with this five methods. Working with JSONObject
and JSONArray
is very easy. You can use JSONArray (Collection copyFrom)
public constructor to make a JSONArray
out of any Java collection and use JSONArray
's get
methods to access the elements.
There is no size limit for shared preferences (besides device's storage limits), so these methods can work for most of usual cases where you want a quick and easy storage for some collection in your app. But JSON parsing happens here, and preferences in Android are stored as XMLs internally, so I recommend using other persistent data store mechanisms when you're dealing with megabytes of data.
This code is better than ours, you only need to add 2 libs: javax.servelet.jar and org.mortbay.jetty.jar.
Class Jetty:
package jetty;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.mortbay.http.SocketListener;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.ServletHttpContext;
public class Jetty {
public static void main(String[] args) {
try {
Server server = new Server();
SocketListener listener = new SocketListener();
System.out.println("Max Thread :" + listener.getMaxThreads() + " Min Thread :" + listener.getMinThreads());
listener.setHost("localhost");
listener.setPort(8070);
listener.setMinThreads(5);
listener.setMaxThreads(250);
server.addListener(listener);
ServletHttpContext context = (ServletHttpContext) server.getContext("/");
context.addServlet("/MO", "jetty.HelloWorldServlet");
server.start();
server.join();
/*//We will create our server running at http://localhost:8070
Server server = new Server();
server.addListener(":8070");
//We will deploy our servlet to the server at the path '/'
//it will be available at http://localhost:8070
ServletHttpContext context = (ServletHttpContext) server.getContext("/");
context.addServlet("/MO", "jetty.HelloWorldServlet");
server.start();
*/
} catch (Exception ex) {
Logger.getLogger(Jetty.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Servlet class:
package jetty;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorldServlet extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException
{
String appid = httpServletRequest.getParameter("appid");
String conta = httpServletRequest.getParameter("conta");
System.out.println("Appid : "+appid);
System.out.println("Conta : "+conta);
httpServletResponse.setContentType("text/plain");
PrintWriter out = httpServletResponse.getWriter();
out.println("Hello World!");
out.close();
}
}
How about just a simple reset button?
<form>
<input type="text" id="textfield1" size="5">
<input type="text" id="textfield2" size="5">
<input type="reset" value="Reset">
</form>
The solution was as simple as adding plt.show()
at the end of the code snippet:
import numpy as np
np.random.seed(123)
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras.datasets import mnist
(X_train,y_train),(X_test,y_test) = mnist.load_data()
print X_train.shape
from matplotlib import pyplot as plt
plt.imshow(X_train[0])
plt.show()
Using scala:
import xml._
val xml = XML.loadString("<tag><nested>hello</nested></tag>")
val formatted = new PrettyPrinter(150, 2).format(xml)
println(formatted)
You can do this in Java too, if you depend on the scala-library.jar. It looks like this:
import scala.xml.*;
public class FormatXML {
public static void main(String[] args) {
String unformattedXml = "<tag><nested>hello</nested></tag>";
PrettyPrinter pp = new PrettyPrinter(150, 3);
String formatted = pp.format(XML.loadString(unformattedXml), TopScope$.MODULE$);
System.out.println(formatted);
}
}
The PrettyPrinter
object is constructed with two ints, the first being max line length and the second being the indentation step.
you can use ajax calls to call different methods without a postback
$.ajax({
type: "POST",
url: "@(Url.Action("Action", "Controller"))",
data: {id: 'id', id1: 'id1' },
contentType: "application/json; charset=utf-8",
cache: false,
async: true,
success: function (result) {
//do something
}
});
you can easily do it with parseInt with format parameter.
Integer.parseInt("-FF", 16) ; // returns -255
Just run the following line in your favorite terminal application:
echo export PATH="/usr/local/bin:$PATH" >> ~/.bash_profile
Restart your terminal and run
brew doctor
the issue should be resolved
Not sure if this approach is published yet. This should work for any m*n board and a player is supposed to fill "winnerPos" consecutive position. The idea is based on running window.
private boolean validateWinner(int x, int y, int player) {
//same col
int low = x-winnerPos-1;
int high = low;
while(high <= x+winnerPos-1) {
if(isValidPos(high, y) && isFilledPos(high, y, player)) {
high++;
if(high - low == winnerPos) {
return true;
}
} else {
low = high + 1;
high = low;
}
}
//same row
low = y-winnerPos-1;
high = low;
while(high <= y+winnerPos-1) {
if(isValidPos(x, high) && isFilledPos(x, high, player)) {
high++;
if(high - low == winnerPos) {
return true;
}
} else {
low = high + 1;
high = low;
}
}
if(high - low == winnerPos) {
return true;
}
//diagonal 1
int lowY = y-winnerPos-1;
int highY = lowY;
int lowX = x-winnerPos-1;
int highX = lowX;
while(highX <= x+winnerPos-1 && highY <= y+winnerPos-1) {
if(isValidPos(highX, highY) && isFilledPos(highX, highY, player)) {
highX++;
highY++;
if(highX - lowX == winnerPos) {
return true;
}
} else {
lowX = highX + 1;
lowY = highY + 1;
highX = lowX;
highY = lowY;
}
}
//diagonal 2
lowY = y+winnerPos-1;
highY = lowY;
lowX = x-winnerPos+1;
highX = lowX;
while(highX <= x+winnerPos-1 && highY <= y+winnerPos-1) {
if(isValidPos(highX, highY) && isFilledPos(highX, highY, player)) {
highX++;
highY--;
if(highX - lowX == winnerPos) {
return true;
}
} else {
lowX = highX + 1;
lowY = highY + 1;
highX = lowX;
highY = lowY;
}
}
if(highX - lowX == winnerPos) {
return true;
}
return false;
}
private boolean isValidPos(int x, int y) {
return x >= 0 && x < row && y >= 0 && y< col;
}
public boolean isFilledPos(int x, int y, int p) throws IndexOutOfBoundsException {
return arena[x][y] == p;
}
Set line-height
to the vertical size of the picture, then do vertical-align:middle
like Josh said.
so if the picture is 20px
, you would have
{
line-height:20px;
font-size:14px;
vertical-align:middle;
}
/usr/bin/
/usr/bin/wkhtmltopdf
wkhtmltopdf http://www.google.com test.pdf
hint: detail information from this linkHow about either of:
>>> df
date duration user_id
0 2013-04-01 30 0001
1 2013-04-01 15 0001
2 2013-04-01 20 0002
3 2013-04-02 15 0002
4 2013-04-02 30 0002
>>> df.groupby("date").agg({"duration": np.sum, "user_id": pd.Series.nunique})
duration user_id
date
2013-04-01 65 2
2013-04-02 45 1
>>> df.groupby("date").agg({"duration": np.sum, "user_id": lambda x: x.nunique()})
duration user_id
date
2013-04-01 65 2
2013-04-02 45 1
UPDATE:3 Now that I have upgraded to new Router, @borislemke's approach will not work if you use CanDeactivate
guard. I'm degrading to my old method, ie:
this answer
UPDATE2: Router events in new-router look promising and the answer by @borislemke seems to cover the main aspect of spinner implementation, I havent't tested it but I recommend it.
UPDATE1: I wrote this answer in the era of Old-Router
, when there used to be only one event route-changed
notified via router.subscribe()
. I also felt overload of the below approach and tried to do it using only router.subscribe()
, and it backfired because there was no way to detect canceled navigation
. So I had to revert back to lengthy approach(double work).
If you know your way around in Angular2, this is what you'll need
Boot.ts
import {bootstrap} from '@angular/platform-browser-dynamic';
import {MyApp} from 'path/to/MyApp-Component';
import { SpinnerService} from 'path/to/spinner-service';
bootstrap(MyApp, [SpinnerService]);
Root Component- (MyApp)
import { Component } from '@angular/core';
import { SpinnerComponent} from 'path/to/spinner-component';
@Component({
selector: 'my-app',
directives: [SpinnerComponent],
template: `
<spinner-component></spinner-component>
<router-outlet></router-outlet>
`
})
export class MyApp { }
Spinner-Component (will subscribe to Spinner-service to change the value of active accordingly)
import {Component} from '@angular/core';
import { SpinnerService} from 'path/to/spinner-service';
@Component({
selector: 'spinner-component',
'template': '<div *ngIf="active" class="spinner loading"></div>'
})
export class SpinnerComponent {
public active: boolean;
public constructor(spinner: SpinnerService) {
spinner.status.subscribe((status: boolean) => {
this.active = status;
});
}
}
Spinner-Service (bootstrap this service)
Define an observable to be subscribed by spinner-component to change the status on change, and function to know and set the spinner active/inactive.
import {Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';
import 'rxjs/add/operator/share';
@Injectable()
export class SpinnerService {
public status: Subject<boolean> = new Subject();
private _active: boolean = false;
public get active(): boolean {
return this._active;
}
public set active(v: boolean) {
this._active = v;
this.status.next(v);
}
public start(): void {
this.active = true;
}
public stop(): void {
this.active = false;
}
}
All Other Routes' Components
(sample):
import { Component} from '@angular/core';
import { SpinnerService} from 'path/to/spinner-service';
@Component({
template: `<div *ngIf="!spinner.active" id="container">Nothing is Loading Now</div>`
})
export class SampleComponent {
constructor(public spinner: SpinnerService){}
ngOnInit(){
this.spinner.stop(); // or do it on some other event eg: when xmlhttp request completes loading data for the component
}
ngOnDestroy(){
this.spinner.start();
}
}
You can try this extension
public static bool IsSubClassOfGenericClass(this Type type, Type genericClass,Type t)
{
return type.IsSubclassOf(genericClass.MakeGenericType(new[] { t }));
}
The @see
tag is a bit different than the @link
tag,
limited in some ways and more flexible in others:
@see
items, commas in the description make the output confusingSee the results below:
JavaDoc generation results with different link types
Best regards.
You could map it to a key, for instance F3, in .vimrc
inoremap <F3> <Esc>GA
<div class="container"> _x000D_
<section class="main-content">_x000D_
<center><a href="#"><button id="view-fullscreen">view full size page large</button></a><center>_x000D_
<script>(function () {_x000D_
var viewFullScreen = document.getElementById("view-fullscreen");_x000D_
if (viewFullScreen) {_x000D_
viewFullScreen.addEventListener("click", function () {_x000D_
var docElm = document.documentElement;_x000D_
if (docElm.requestFullscreen) {_x000D_
docElm.requestFullscreen();_x000D_
}_x000D_
else if (docElm.mozRequestFullScreen) {_x000D_
docElm.mozRequestFullScreen();_x000D_
}_x000D_
else if (docElm.webkitRequestFullScreen) {_x000D_
docElm.webkitRequestFullScreen();_x000D_
}_x000D_
}, false);_x000D_
}_x000D_
})();</script>_x000D_
</section>_x000D_
</div>
_x000D_
for view demo clcik here demo of click to open page in fullscreen
function arrayColumn(arr, n) {_x000D_
return arr.map(x=> x[n]);_x000D_
}_x000D_
_x000D_
var twoDimensionalArray = [_x000D_
[1, 2, 3],_x000D_
[4, 5, 6],_x000D_
[7, 8, 9]_x000D_
];_x000D_
_x000D_
console.log(arrayColumn(twoDimensionalArray, 1));
_x000D_
This works fine for me.
$(document).ready(function () {
$('#btn_move').click( function(){
var dateformat = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
var Val_date=$('#txt_date').val();
if(Val_date.match(dateformat)){
var seperator1 = Val_date.split('/');
var seperator2 = Val_date.split('-');
if (seperator1.length>1)
{
var splitdate = Val_date.split('/');
}
else if (seperator2.length>1)
{
var splitdate = Val_date.split('-');
}
var dd = parseInt(splitdate[0]);
var mm = parseInt(splitdate[1]);
var yy = parseInt(splitdate[2]);
var ListofDays = [31,28,31,30,31,30,31,31,30,31,30,31];
if (mm==1 || mm>2)
{
if (dd>ListofDays[mm-1])
{
alert('Invalid date format!');
return false;
}
}
if (mm==2)
{
var lyear = false;
if ( (!(yy % 4) && yy % 100) || !(yy % 400))
{
lyear = true;
}
if ((lyear==false) && (dd>=29))
{
alert('Invalid date format!');
return false;
}
if ((lyear==true) && (dd>29))
{
alert('Invalid date format!');
return false;
}
}
}
else
{
alert("Invalid date format!");
return false;
}
});
});
Function MySheet()
' uncomment the below line to make it Volatile
'Application.Volatile
MySheet = Application.Caller.Worksheet.Name
End Function
This should be the function you are looking for
Put your code in a method.
Try this:
public class MyClass {
public static void main(String[] args) {
UserInput input = new UserInput();
input.name();
}
}
Then "run" the class from your IDE
You can easily increase your VM's RAM by modifying the memory property of config.vm.provider section in your vagrant file.
config.vm.provider "virtualbox" do |vb|
vb.memory = "4096"
end
This allocates about 4GB of RAM to your VM. You can change this according to your requirement. For example, following setting would allocate 2GB of RAM to your VM.
config.vm.provider "virtualbox" do |vb|
vb.memory = "2048"
end
Try removing the config.vm.customize ["modifyvm", :id, "--memory", 1024]
in your file, and adding the above code.
For the network configuration, try modifying the config.vm.network :hostonly, "199.188.44.20"
in your file toconfig.vm.network "private_network", ip: "199.188.44.20"
You can detect this only in limited circumstances. Specifically, in chrome if a file was selected earlier and then the file dialog is clicked and cancel clicked, Chrome clears the file and fires the onChange event.
https://code.google.com/p/chromium/issues/detail?id=2508
In this scenario, you can detect this by handling the onChange event and checking the files property.
Double Click the Login Button in the NETBEANS or add the Event Listener on Click Event (ActionListener)
btnLogin.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
this.setVisible(false);
new FrmMain().setVisible(true); // Main Form to show after the Login Form..
}
});
Yor $.post
has no data. You need to pass the form data. You can use serialize()
to post the form data. Try this
$("#post-btn").click(function(){
$.post("process.php", $('#reg-form').serialize() ,function(data){
alert(data);
});
});
You could do $stmt->queryString
to obtain the SQL query used in the statement. If you want to save the entire $stmt variable (I can't see why), you could just copy it. It is an instance of PDOStatement so there is apparently no advantage in storing it.
change the focused border to none
TextField(
decoration: new InputDecoration(
border: InputBorder.none,
focusedBorder: InputBorder.none,
contentPadding: EdgeInsets.only(left: 15, bottom: 11, top: 11, right: 15),
hintText: 'Subject'
),
),
The compiler is telling you that there are problems starting at line 122 in the middle of that strange FBI-CIA warning message. That message is not valid C++ code and is NOT commented out so of course it will cause compiler errors. Try removing that entire message.
Also, I agree with In silico: you should always tell us what you tried and exactly what error messages you got.
Position the cursor inside the class, then press ALT + Ins and select Getters and Setters
from the contextual menu.
FAST "FROM" AND "TO" METHODS
I am late to the party, but I compounded previous answers and improved over them. I think these two methods are faster than any others posted so far. I was able to convert 1,000,000 numbers from and to base 36 in under 400ms in a single core machine.
Example below is for base 62. Change the BaseChars
array to convert from and to any other base.
private static readonly char[] BaseChars =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".ToCharArray();
private static readonly Dictionary<char, int> CharValues = BaseChars
.Select((c,i)=>new {Char=c, Index=i})
.ToDictionary(c=>c.Char,c=>c.Index);
public static string LongToBase(long value)
{
long targetBase = BaseChars.Length;
// Determine exact number of characters to use.
char[] buffer = new char[Math.Max(
(int) Math.Ceiling(Math.Log(value + 1, targetBase)), 1)];
var i = buffer.Length;
do
{
buffer[--i] = BaseChars[value % targetBase];
value = value / targetBase;
}
while (value > 0);
return new string(buffer, i, buffer.Length - i);
}
public static long BaseToLong(string number)
{
char[] chrs = number.ToCharArray();
int m = chrs.Length - 1;
int n = BaseChars.Length, x;
long result = 0;
for (int i = 0; i < chrs.Length; i++)
{
x = CharValues[ chrs[i] ];
result += x * (long)Math.Pow(n, m--);
}
return result;
}
EDIT (2018-07-12)
Fixed to address the corner case found by @AdrianBotor (see comments) converting 46655 to base 36. This is caused by a small floating-point error calculating Math.Log(46656, 36)
which is exactly 3, but .NET returns 3 + 4.44e-16
, which causes an extra character in the output buffer.
WordPress does not execute PHP in post/page content by default unless it has a shortcode.
The quickest and easiest way to do this is to use a plugin that allows you to run PHP embedded in post content.
There are two other "quick and easy" ways to accomplish it without a plugin:
Make it a shortcode (put it in functions.php
and have it echo the country name) which is very easy - see here: Shortcode API at WP Codex
Put it in a template file - make a custom template for that page based on your default page template and add the PHP into the template file rather than the post content: Custom Page Templates
Further to aduchis answer above - if you then need to filter based on those group by keys, you can define a class to wrap the many keys.
return customers.GroupBy(a => new CustomerGroupingKey(a.Country, a.Gender))
.Where(a => a.Key.Country == "Ireland" && a.Key.Gender == "M")
.SelectMany(a => a)
.ToList();
Where CustomerGroupingKey takes the group keys:
private class CustomerGroupingKey
{
public CustomerGroupingKey(string country, string gender)
{
Country = country;
Gender = gender;
}
public string Country { get; }
public string Gender { get; }
}
cordova-check-plugins --update=auto --force
use the command line
var element = document.getElementById('sample_id');
element.style.removeProperty("width");
element.style.removeProperty("height");
This is default by iOS7 design. try to do the below:
[tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
You can set the 'Separator Inset' from the storyboard:
For me all the things stated here https://stackoverflow.com/a/6395750/939501 were true but still it was throwing error, reason was I created a View class with name ABCView and then deleted it later I added a view controller as ABCViewController so somehow it was referring to old ABCView in new view controller, I had to delete the ABCViewController and add a new one with different name that solved my issue.
Thanks
You could do:
if($('.input1').length && $('.input1').val().length)
length
evaluates to false
in a condition, when the value is 0
.
Swift 2
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
//All stuff here
})
REST is just a software architecture style for exposing resources.
A typical REST call to return information about customer 34456 could look like:
http://example.com/customer/34456
Have a look at the IBM tutorial for REST web services
Some of the above values are easily available from the appropriate WIN32 API, I just list them here for completeness. Others, however, need to be obtained from the Performance Data Helper library (PDH), which is a bit "unintuitive" and takes a lot of painful trial and error to get to work. (At least it took me quite a while, perhaps I've been only a bit stupid...)
Note: for clarity all error checking has been omitted from the following code. Do check the return codes...!
Total Virtual Memory:
#include "windows.h"
MEMORYSTATUSEX memInfo;
memInfo.dwLength = sizeof(MEMORYSTATUSEX);
GlobalMemoryStatusEx(&memInfo);
DWORDLONG totalVirtualMem = memInfo.ullTotalPageFile;
Note: The name "TotalPageFile" is a bit misleading here. In reality this parameter gives the "Virtual Memory Size", which is size of swap file plus installed RAM.
Virtual Memory currently used:
Same code as in "Total Virtual Memory" and then
DWORDLONG virtualMemUsed = memInfo.ullTotalPageFile - memInfo.ullAvailPageFile;
Virtual Memory currently used by current process:
#include "windows.h"
#include "psapi.h"
PROCESS_MEMORY_COUNTERS_EX pmc;
GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc));
SIZE_T virtualMemUsedByMe = pmc.PrivateUsage;
Total Physical Memory (RAM):
Same code as in "Total Virtual Memory" and then
DWORDLONG totalPhysMem = memInfo.ullTotalPhys;
Physical Memory currently used:
Same code as in "Total Virtual Memory" and then
DWORDLONG physMemUsed = memInfo.ullTotalPhys - memInfo.ullAvailPhys;
Physical Memory currently used by current process:
Same code as in "Virtual Memory currently used by current process" and then
SIZE_T physMemUsedByMe = pmc.WorkingSetSize;
CPU currently used:
#include "TCHAR.h"
#include "pdh.h"
static PDH_HQUERY cpuQuery;
static PDH_HCOUNTER cpuTotal;
void init(){
PdhOpenQuery(NULL, NULL, &cpuQuery);
// You can also use L"\\Processor(*)\\% Processor Time" and get individual CPU values with PdhGetFormattedCounterArray()
PdhAddEnglishCounter(cpuQuery, L"\\Processor(_Total)\\% Processor Time", NULL, &cpuTotal);
PdhCollectQueryData(cpuQuery);
}
double getCurrentValue(){
PDH_FMT_COUNTERVALUE counterVal;
PdhCollectQueryData(cpuQuery);
PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &counterVal);
return counterVal.doubleValue;
}
CPU currently used by current process:
#include "windows.h"
static ULARGE_INTEGER lastCPU, lastSysCPU, lastUserCPU;
static int numProcessors;
static HANDLE self;
void init(){
SYSTEM_INFO sysInfo;
FILETIME ftime, fsys, fuser;
GetSystemInfo(&sysInfo);
numProcessors = sysInfo.dwNumberOfProcessors;
GetSystemTimeAsFileTime(&ftime);
memcpy(&lastCPU, &ftime, sizeof(FILETIME));
self = GetCurrentProcess();
GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);
memcpy(&lastSysCPU, &fsys, sizeof(FILETIME));
memcpy(&lastUserCPU, &fuser, sizeof(FILETIME));
}
double getCurrentValue(){
FILETIME ftime, fsys, fuser;
ULARGE_INTEGER now, sys, user;
double percent;
GetSystemTimeAsFileTime(&ftime);
memcpy(&now, &ftime, sizeof(FILETIME));
GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);
memcpy(&sys, &fsys, sizeof(FILETIME));
memcpy(&user, &fuser, sizeof(FILETIME));
percent = (sys.QuadPart - lastSysCPU.QuadPart) +
(user.QuadPart - lastUserCPU.QuadPart);
percent /= (now.QuadPart - lastCPU.QuadPart);
percent /= numProcessors;
lastCPU = now;
lastUserCPU = user;
lastSysCPU = sys;
return percent * 100;
}
On Linux the choice that seemed obvious at first was to use the POSIX APIs like getrusage()
etc. I spent some time trying to get this to work, but never got meaningful values. When I finally checked the kernel sources themselves, I found out that apparently these APIs are not yet completely implemented as of Linux kernel 2.6!?
In the end I got all values via a combination of reading the pseudo-filesystem /proc
and kernel calls.
Total Virtual Memory:
#include "sys/types.h"
#include "sys/sysinfo.h"
struct sysinfo memInfo;
sysinfo (&memInfo);
long long totalVirtualMem = memInfo.totalram;
//Add other values in next statement to avoid int overflow on right hand side...
totalVirtualMem += memInfo.totalswap;
totalVirtualMem *= memInfo.mem_unit;
Virtual Memory currently used:
Same code as in "Total Virtual Memory" and then
long long virtualMemUsed = memInfo.totalram - memInfo.freeram;
//Add other values in next statement to avoid int overflow on right hand side...
virtualMemUsed += memInfo.totalswap - memInfo.freeswap;
virtualMemUsed *= memInfo.mem_unit;
Virtual Memory currently used by current process:
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
int parseLine(char* line){
// This assumes that a digit will be found and the line ends in " Kb".
int i = strlen(line);
const char* p = line;
while (*p <'0' || *p > '9') p++;
line[i-3] = '\0';
i = atoi(p);
return i;
}
int getValue(){ //Note: this value is in KB!
FILE* file = fopen("/proc/self/status", "r");
int result = -1;
char line[128];
while (fgets(line, 128, file) != NULL){
if (strncmp(line, "VmSize:", 7) == 0){
result = parseLine(line);
break;
}
}
fclose(file);
return result;
}
Total Physical Memory (RAM):
Same code as in "Total Virtual Memory" and then
long long totalPhysMem = memInfo.totalram;
//Multiply in next statement to avoid int overflow on right hand side...
totalPhysMem *= memInfo.mem_unit;
Physical Memory currently used:
Same code as in "Total Virtual Memory" and then
long long physMemUsed = memInfo.totalram - memInfo.freeram;
//Multiply in next statement to avoid int overflow on right hand side...
physMemUsed *= memInfo.mem_unit;
Physical Memory currently used by current process:
Change getValue() in "Virtual Memory currently used by current process" as follows:
int getValue(){ //Note: this value is in KB!
FILE* file = fopen("/proc/self/status", "r");
int result = -1;
char line[128];
while (fgets(line, 128, file) != NULL){
if (strncmp(line, "VmRSS:", 6) == 0){
result = parseLine(line);
break;
}
}
fclose(file);
return result;
}
CPU currently used:
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
static unsigned long long lastTotalUser, lastTotalUserLow, lastTotalSys, lastTotalIdle;
void init(){
FILE* file = fopen("/proc/stat", "r");
fscanf(file, "cpu %llu %llu %llu %llu", &lastTotalUser, &lastTotalUserLow,
&lastTotalSys, &lastTotalIdle);
fclose(file);
}
double getCurrentValue(){
double percent;
FILE* file;
unsigned long long totalUser, totalUserLow, totalSys, totalIdle, total;
file = fopen("/proc/stat", "r");
fscanf(file, "cpu %llu %llu %llu %llu", &totalUser, &totalUserLow,
&totalSys, &totalIdle);
fclose(file);
if (totalUser < lastTotalUser || totalUserLow < lastTotalUserLow ||
totalSys < lastTotalSys || totalIdle < lastTotalIdle){
//Overflow detection. Just skip this value.
percent = -1.0;
}
else{
total = (totalUser - lastTotalUser) + (totalUserLow - lastTotalUserLow) +
(totalSys - lastTotalSys);
percent = total;
total += (totalIdle - lastTotalIdle);
percent /= total;
percent *= 100;
}
lastTotalUser = totalUser;
lastTotalUserLow = totalUserLow;
lastTotalSys = totalSys;
lastTotalIdle = totalIdle;
return percent;
}
CPU currently used by current process:
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
#include "sys/times.h"
#include "sys/vtimes.h"
static clock_t lastCPU, lastSysCPU, lastUserCPU;
static int numProcessors;
void init(){
FILE* file;
struct tms timeSample;
char line[128];
lastCPU = times(&timeSample);
lastSysCPU = timeSample.tms_stime;
lastUserCPU = timeSample.tms_utime;
file = fopen("/proc/cpuinfo", "r");
numProcessors = 0;
while(fgets(line, 128, file) != NULL){
if (strncmp(line, "processor", 9) == 0) numProcessors++;
}
fclose(file);
}
double getCurrentValue(){
struct tms timeSample;
clock_t now;
double percent;
now = times(&timeSample);
if (now <= lastCPU || timeSample.tms_stime < lastSysCPU ||
timeSample.tms_utime < lastUserCPU){
//Overflow detection. Just skip this value.
percent = -1.0;
}
else{
percent = (timeSample.tms_stime - lastSysCPU) +
(timeSample.tms_utime - lastUserCPU);
percent /= (now - lastCPU);
percent /= numProcessors;
percent *= 100;
}
lastCPU = now;
lastSysCPU = timeSample.tms_stime;
lastUserCPU = timeSample.tms_utime;
return percent;
}
I would assume, that some of the Linux code also works for the Unixes, except for the parts that read the /proc pseudo-filesystem. Perhaps on Unix these parts can be replaced by getrusage()
and similar functions?
If someone with Unix know-how could edit this answer and fill in the details?!
Maybe can help to check that the path to the xsd file has not 'strange' characters like 'é', or similar: I was having the same issue but when I changed to a path without the 'é' the error dissapeared.
Here’s some PHP and JavaScript demonstration code that shows a simple way to create indexed fields on a form (fields that have the same name) and then process them in both JavaScript and PHP. The fields must have both "ID" names and "NAME" names. Javascript uses the ID and PHP uses the NAME.
<?php
// How to use same field name multiple times on form
// Process these fields in Javascript and PHP
// Must use "ID" in Javascript and "NAME" in PHP
echo "<HTML>";
echo "<HEAD>";
?>
<script type="text/javascript">
function TestForm(form) {
// Loop through the HTML form field (TheId) that is returned as an array.
// The form field has multiple (n) occurrences on the form, each which has the same name.
// This results in the return of an array of elements indexed from 0 to n-1.
// Use ID in Javascript
var i = 0;
document.write("<P>Javascript responding to your button click:</P>");
for (i=0; i < form.TheId.length; i++) {
document.write(form.TheId[i].value);
document.write("<br>");
}
}
</script>
<?php
echo "</HEAD>";
echo "<BODY>";
$DQ = '"'; # Constant for building string with double quotes in it.
if (isset($_POST["MyButton"])) {
$TheNameArray = $_POST["TheName"]; # Use NAME in PHP
echo "<P>Here are the names you submitted to server:</P>";
for ($i = 0; $i <3; $i++) {
echo $TheNameArray[$i] . "<BR>";
}
}
echo "<P>Enter names and submit to server or Javascript</P>";
echo "<FORM NAME=TstForm METHOD=POST ACTION=" ;
echo $DQ . "TestArrayFormToJavascript2.php" . $DQ . "OnReset=" . $DQ . "return allowreset(this)" . $DQ . ">";
echo "<FORM>";
echo "<INPUT ID = TheId NAME=" . $DQ . "TheName[]" . $DQ . " VALUE=" . $DQ . "" . $DQ . ">";
echo "<INPUT ID = TheId NAME=" . $DQ . "TheName[]" . $DQ . " VALUE=" . $DQ . "" . $DQ . ">";
echo "<INPUT ID = TheId NAME=" . $DQ . "TheName[]" . $DQ . " VALUE=" . $DQ . "" . $DQ . ">";
echo "<P><INPUT TYPE=submit NAME=MyButton VALUE=" . $DQ . "Submit to server" . $DQ . "></P>";
echo "<P><BUTTON onclick=" . $DQ . "TestForm(this.form)" . $DQ . ">Submit to Javascript</BUTTON></P>";
echo "</FORM>";
echo "</BODY>";
echo "</HTML>";
After some years have passed, you can do that now with ES6 Array.from
(or spread syntax):
const navbar = Array.from(document.querySelectorAll('#navbar>ul>li'));_x000D_
console.log('Get first: ', navbar[0].textContent);_x000D_
_x000D_
// If you need to iterate once over all these nodes, you can use the callback function:_x000D_
console.log('Iterate with Array.from callback argument:');_x000D_
Array.from(document.querySelectorAll('#navbar>ul>li'),li => console.log(li.textContent))_x000D_
_x000D_
// ... or a for...of loop:_x000D_
console.log('Iterate with for...of:');_x000D_
for (const li of document.querySelectorAll('#navbar>ul>li')) {_x000D_
console.log(li.textContent);_x000D_
}
_x000D_
.as-console-wrapper { max-height: 100% !important; top: 0; }
_x000D_
<div id="navbar">_x000D_
<ul>_x000D_
<li id="navbar-One">One</li>_x000D_
<li id="navbar-Two">Two</li>_x000D_
<li id="navbar-Three">Three</li>_x000D_
</ul>_x000D_
</div>
_x000D_
The real answer is you need to set the escape character to '\': SET ESCAPE ON
The problem may have occurred either because escaping was disabled, or the escape character was set to something other than '\'. The above statement will enable escaping and set it to '\'.
None of the other answers previously posted actually answer the original question. They all work around the problem but don't resolve it.
As of Python 3.2+, you can also accomplish this using the to_bytes
native int method:
newFileBytes = [123, 3, 255, 0, 100]
# make file
newFile = open("filename.txt", "wb")
# write to file
for byte in newFileBytes:
newFile.write(byte.to_bytes(1, byteorder='big'))
I.e., each single call to to_bytes
in this case creates a string of length 1, with its characters arranged in big-endian order (which is trivial for length-1 strings), which represents the integer value byte
. You can also shorten the last two lines into a single one:
newFile.write(''.join([byte.to_bytes(1, byteorder='big') for byte in newFileBytes]))
The data would probably have been posted originally from a web form looking a bit like this (but probably much more complicated):
<form action="http://example.com" method="post">
User login <input name="user[login]" /><br />
User password <input name="user[password]" /><br />
<input type="submit" />
</form>
If the method were "get" instead of "post", clicking the submit button would take you to a URL looking a bit like this:
http://example.com/?user%5Blogin%5D=username&user%5Bpassword%5D=123456
or:
http://example.com/?user[login]=username&user[password]=123456
The web server on the other end will likely take the user[login]
and user[password]
parameters, and make them into a user
object with login
and password
fields containing those values.
Partially. The text is inserted, but the warning is still generated.
I found a discussion that indicated the text needed to be preceded with 'E', as such:
insert into EscapeTest (text) values (E'This is the first part \n And this is the second');
This suppressed the warning, but the text was still not being returned correctly. When I added the additional slash as Michael suggested, it worked.
As such:
insert into EscapeTest (text) values (E'This is the first part \\n And this is the second');
From the manpage, I believe these are the droids you are looking for:
-F/--form <name=content>
(HTTP) This lets curl emulate a filled-in form in which a user has pressed the submit button. This causes curl to POST data using the Content-Type multipart/form-data according to RFC2388. This enables uploading of binary files etc. To force the 'content' part to be a file, prefix the file name with an @ sign.
Example, to send your password file to the server, where 'password' is the name of the form-field to which /etc/passwd will be the input:
curl -F password=@/etc/passwd www.mypasswords.com
So in your case, this would be something like
curl -F file=@/some/file/on/your/local/disk http://localhost:8080
Version Code - It's a positive integer that's used for comparison with other version codes. It's not shown to the user, it's just for record-keeping in a way. You can set it to any integer you like but it's suggested that you linearly increment it for successive versions.
Version Name - This is the version string seen by the user. It isn't used for internal comparisons or anything, it's just for users to see.
For example: Say you release an app, its initial versionCode could be 1 and versionName could also be 1. Once you make some small changes to the app and want to publish an update, you would set versionName to "1.1" (since the changes aren't major) while logically your versionCode should be 2 (regardless of size of changes).
Say in another condition you release a completely revamped version of your app, you could set versionCode and versionName to "2".
Hope that helps.
You can read more about it here
Alternatives:
>>> map(a.__getitem__, b)
[1, 5, 5]
>>> import operator
>>> operator.itemgetter(*b)(a)
(1, 5, 5)
string nonNormalized = "\r\n\n\r";
string normalized = nonNormalized.Replace("\r", "\n").Replace("\n", "\r\n");
I stoped the tomcat on the computer and started the service (tomcat) using the eclipse IDE.
I have a rooted Samsung Galaxy Trend Plus (GT-S7580).
Running 'adb root' gives me the same 'adbd cannot run as root in production builds' error.
For devices that have Developer Options -> Root access, choose "ADB only" to provide adb root access to the device (as suggested by NgaNguyenDuy).
Then try to run the command as per the solution at Launch a script as root through ADB. In my case, I just wanted to run the 'netcfg rndis0 dhcp' command, and I did it this way:
adb shell "su -c netcfg rndis0 dhcp"
Please check whether you are making any mistakes while running it this way.
If it still does not work, check whether you rooted the device correctly. If still no luck, try installing a custom ROM such as Cyanogen Mod in order for 'adb root' to work.
You have to distinct sub routines and functions in vba... Generally (as far as I know), sub routines do not return anything and the surrounding parantheses are optional. For functions, you need to write the parantheses.
As for your example, MsgBox is not a function but a sub routine and therefore the parantheses are optional in that case. One exception with functions is, when you do not assign the returned value, or when the function does not consume a parameter, you can leave away the parantheses too.
This answer goes into a bit more detail, but basically you should be on the save side, when you provide parantheses for functions and leave them away for sub routines.
I had a similar instance where I wanted to use .toFixed()
where necessary, but I didn't want the padding when it wasn't. So I ended up using parseFloat in conjunction with toFixed.
toFixed without padding
parseFloat(n.toFixed(4));
Another option that does almost the same thing
This answer may help your decision
Number(n.toFixed(4));
toFixed
will round/pad the number to a specific length, but also convert it to a string. Converting that back to a numeric type will not only make the number safer to use arithmetically, but also automatically drop any trailing 0's. For example:
var n = "1.234000";
n = parseFloat(n);
// n is 1.234 and in number form
Because even if you define a number with trailing zeros they're dropped.
var n = 1.23000;
// n == 1.23;
The constructor is a method which is automatically called on class instantiation. Which means the contents of a constructor are processed without separate method calls. The contents of a the class keyword parenthesis are passed to the constructor method.
<?xml version="1.0" encoding="utf-8"?>
<gradient
android:angle="90"
android:startColor="@color/colorPrimary"
android:endColor="@color/colorPrimary"
android:centerColor="@color/white"
android:type="linear"/>
<corners android:bottomRightRadius="10dp"
android:bottomLeftRadius="10dp"
android:topRightRadius="10dp"
android:topLeftRadius="10dp"/>
I think this is the simplest way to get to what you want.
Credit to JMK's answer for the first part, and the hyperlink part was adapted from http://msdn.microsoft.com/en-us/library/office/ff822490(v=office.15).aspx
'Gets the entire path to the file including the filename using the open file dialog
Dim filename As String
filename = Application.GetOpenFilename
'Adds a hyperlink to cell b5 in the currently active sheet
With ActiveSheet
.Hyperlinks.Add Anchor:=.Range("b5"), _
Address:=filename, _
ScreenTip:="The screenTIP", _
TextToDisplay:=filename
End With
Due to PermGen removal some options were removed (like -XX:MaxPermSize
), but options -Xms
and -Xmx
work in Java 8. It's possible that under Java 8 your application simply needs somewhat more memory. Try to increase -Xmx
value. Alternatively you can try to switch to G1 garbage collector using -XX:+UseG1GC
.
Note that if you use any option which was removed in Java 8, you will see a warning upon application start:
$ java -XX:MaxPermSize=128M -version
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=128M; support was removed in 8.0
java version "1.8.0_25"
Java(TM) SE Runtime Environment (build 1.8.0_25-b18)
Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)
import time
int(time.time())
Output:
1521462189
echo $this->bb;
The variable is inherited and is not private, so it is a part of the current object.
Here is additional information in response to your request for more information about using parent::
:
Use parent::
when you want add extra functionality to a method from the parent class. For example, imagine an Airplane
class:
class Airplane {
private $pilot;
public function __construct( $pilot ) {
$this->pilot = $pilot;
}
}
Now suppose we want to create a new type of Airplane that also has a navigator. You can extend the __construct() method to add the new functionality, but still make use of the functionality offered by the parent:
class Bomber extends Airplane {
private $navigator;
public function __construct( $pilot, $navigator ) {
$this->navigator = $navigator;
parent::__construct( $pilot ); // Assigns $pilot to $this->pilot
}
}
In this way, you can follow the DRY principle of development but still provide all of the functionality you desire.
This has been a recurring question for many years. (The numbers keep changing, but the concept is the same: how do I view or edit files that are larger than memory?)
Obviously more
or less
are good approaches to merely reading the files --- less
even offers vi
like keybindings for scrolling and searching.
A Freshmeat search on "large files" suggests that two editors would be particularly suited to your needs.
One would be: lfhex ... a large file hex editor (which depends on Qt). That one, obviously, entails using a GUI.
Another would seem to be suited to console use: hed ... and it claims to have a vim
-like interface (including an ex
mode?).
I'm sure I've seen other editors for Linux/UNIX that were able to page through files without loading their entirety into memory. However, I don't recall any of their names. I'm making this response a "wiki" entry to encourage others to add their links to such editors. (Yes, I am familiar with ways to work around the issue using split
and cat
; but I'm thinking of editors, especially console/curses editors which can dispense with that and save us the time/latencies and disk space overhead that such approaches entail).
If your web server is IIS, you need to make sure that the new Office 2007 (I see the xlsx suffix) mime types are added to the list of mime types in IIS, otherwise it will refuse to serve the unknown file type.
Here's one link to tell you how:
Other folks have suggested array_search()
which gives the key of the array element where the value is found. You can ensure that the array keys are contiguous integers by using array_values()
:
$list = array(0=>'string1', 'foo'=>'string2', 42=>'string3');
$index = array_search('string2', array_values($list));
print "$index\n";
// result: 1
You said in your question that array_search()
was no use. Can you explain why? What did you try and how did it not meet your needs?
You can add the configuration name as the ASPNETCORE_ENVIRONMENT
in the launchSettings.json
as below
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:58446/",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"environmentVariables": {
ASPNETCORE_ENVIRONMENT": "$(Configuration)"
}
}
}
That sure must seem confusing. So this is what is going on. The first value of enumerate (in this case i) returns the next index value starting at 0 so 0, 1, 2, 3, ... It will always return these numbers regardless of what is in the dictionary. The second value of enumerate (in this case j) is returning the values in your dictionary/enumm (we call it a dictionary in Python). What you really want to do is what roadrunner66 responded with.
Efran Cobisi's suggestion of using an Auto Mapper is a good one. I have used Auto Mapper for a while and it worked well, until I found the much faster alternative, Mapster.
Given a large list or IEnumerable, Mapster outperforms Auto Mapper. I found a benchmark somewhere that showed Mapster being 6 times as fast, but I could not find it again. You could look it up and then, if it is suits you, use Mapster.
First Off, I object to this other question regarding Visual Studio 2015 as a duplicate question. How do I open SSRS (.rptproj) and SSIS (.dtproj) files in Visual Studio 2015? [duplicate]
Basically this question has the title ...Visual Studio 2012 / 2013
What about ALL the improvements and changes to VS 2015 ??? SSDT has been updated and changed. The entire way of doing various additions and updates is different.
So having vented / rant - I did open a VS 2015 update 2 instance and proceeded to open an existing solution that include a .rptproj
project. Now this computer does not yet have sql server installed on it yet.
Solution for ME : Tools --> Extension and Updates --> Updates --> sql server tooling updates
Click on Update button and wait a long time and SSDT then installs and close visual studio 2015 and re-open and it works for me.
In case it is NOT found in VS 2015 for some reason : scroll to the bottom, pick your language iso https://msdn.microsoft.com/en-us/mt186501.aspx?f=255&MSPPError=-2147217396
Woohoo my first post even though this is a year old. To avoid the background-coloring issues with wrappers, you could use inline-block with hr (nobody said that explicitly). Text-align should center correctly since they are inline elements.
<div style="text-align:center">
<hr style="display:inline-block; position:relative; top:4px; width:45%" />
New Section
<hr style="display:inline-block; position:relative; top:4px; width:45%" />
</div>
Current route properties are present in this.$route
, this.$router
is the instance of router object which gives the configuration of the router. You can get the current route query using this.$route.query
C/program files/
and user/sukhendra/AppData
then only Anaconda is remaining in my PC so opened Anaconda and then it's all working fine for me
This is the most up-to-date solution.
<form name="frmChkForm" id="frmChkForm">
<input type="checkbox" name="chkcc9" id="group1" />Check Me
<input type="checkbox" name="chk9[120]" class="group1" />
<input type="checkbox" name="chk9[140]" class="group1" />
<input type="checkbox" name="chk9[150]" class="group1" />
</form>
$(function() {
enable_cb();
$("#group1").click(enable_cb);
});
function enable_cb() {
$("input.group1").prop("disabled", !this.checked);
}
Here is the usage details for .attr()
and .prop()
.
Use the new .prop()
function:
$("input.group1").prop("disabled", true);
$("input.group1").prop("disabled", false);
The .prop()
function is not available, so you need to use .attr()
.
To disable the checkbox (by setting the value of the disabled attribute) do
$("input.group1").attr('disabled','disabled');
and for enabling (by removing the attribute entirely) do
$("input.group1").removeAttr('disabled');
If you're working with just one element, it will always be fastest to use DOMElement.disabled = true
. The benefit to using the .prop()
and .attr()
functions is that they will operate on all matched elements.
// Assuming an event handler on a checkbox
if (this.disabled)
Well, actually I'll have to say David is right with his solution, but there are some topics disturbing me:
ViewModel
, and include the Model as member in the ViewModel
, then you effectively sent your model to the View => this is BADSo how can you create a better coupling?
I would use a tool like AutoMapper
or ValueInjecter to map between ViewModel
and Model.
AutoMapper
does seem to have the better syntax and feel to it, but the current version lacks a
very severe topic: It is not able to perform the mapping from ViewModel
to Model (under certain circumstances like flattening, etc., but this is off topic)
So at present I prefer to use ValueInjecter
.
So you create a ViewModel
with the fields you need in the view.
You add the SelectList items you need as lookups.
And you add them as SelectLists already. So you can query from a LINQ enabled sourc, select the ID and text field and store it as a selectlist:
You gain that you do not have to create a new type (dictionary) as lookup and you just move the new SelectList
from the view to the controller.
// StaffTypes is an IEnumerable<StaffType> from dbContext
// viewModel is the viewModel initialized to copy content of Model Employee
// viewModel.StaffTypes is of type SelectList
viewModel.StaffTypes =
new SelectList(
StaffTypes.OrderBy( item => item.Name )
"StaffTypeID",
"Type",
viewModel.StaffTypeID
);
In the view you just have to call
@Html.DropDownListFor( model => mode.StaffTypeID, model.StaffTypes )
Back in the post element of your method in the controller you have to take a parameter of the type of your ViewModel
. You then check for validation.
If the validation fails, you have to remember to re-populate the viewModel.StaffTypes
SelectList, because this item will be null on entering the post function.
So I tend to have those population things separated into a function.
You just call back return new View(viewModel)
if anything is wrong.
Validation errors found by MVC3 will automatically be shown in the view.
If you have your own validation code you can add validation errors by specifying which field they belong to. Check documentation on ModelState
to get info on that.
If the viewModel
is valid you have to perform the next step:
If it is a create of a new item, you have to populate a model from the viewModel
(best suited is ValueInjecter
). Then you can add it to the EF collection of that type and commit changes.
If you have an update, you get the current db item first into a model. Then you can copy the values from the viewModel
back to the model (again using ValueInjecter
gets you do that very quick).
After that you can SaveChanges
and are done.
Feel free to ask if anything is unclear.
sometimes mysql_upgrade -u root -p --force
is not realy enough,
please refer to this question : Table 'performance_schema.session_variables' doesn't exist
according to it:
cd [installation_path]\eds-binaries\dbserver\mysql5711x86x160420141510\bin
mysql_upgrade -u root -p --force
While I think this compiler error is a good thing, there is a way you can work around it. Use a condition you know will be true:
public void myMethod(){
someCodeHere();
if(1 < 2) return; // compiler isn't smart enough to complain about this
moreCodeHere();
}
The compiler is not smart enough to complain about that.
Redirecting stderr
to stdout
seems to also do the trick without any other commands/scriptblock wrappers although I can't find an explanation why it works that way..
# test.ps1
$ErrorActionPreference = "Stop"
aws s3 ls s3://xxx
echo "==> pass"
aws s3 ls s3://xxx 2>&1
echo "shouldn't be here"
This will output the following as expected (the command aws s3 ...
returns $LASTEXITCODE = 255
)
PS> .\test.ps1
An error occurred (AccessDenied) when calling the ListObjectsV2 operation: Access Denied
==> pass
According to the docs (http://ca3.php.net/language.oop5.cloning):
$a = clone $b;
The standard library includes the ordered and the unordered map (std::map
and std::unordered_map
) containers. In an ordered map the elements are sorted by the key, insert and access is in O(log n). Usually the standard library internally uses red black trees for ordered maps. But this is just an implementation detail. In an unordered map insert and access is in O(1). It is just another name for a hashtable.
An example with (ordered) std::map
:
#include <map>
#include <iostream>
#include <cassert>
int main(int argc, char **argv)
{
std::map<std::string, int> m;
m["hello"] = 23;
// check if key is present
if (m.find("world") != m.end())
std::cout << "map contains key world!\n";
// retrieve
std::cout << m["hello"] << '\n';
std::map<std::string, int>::iterator i = m.find("hello");
assert(i != m.end());
std::cout << "Key: " << i->first << " Value: " << i->second << '\n';
return 0;
}
Output:
23 Key: hello Value: 23
If you need ordering in your container and are fine with the O(log n) runtime then just use std::map
.
Otherwise, if you really need a hash-table (O(1) insert/access), check out std::unordered_map
, which has a similar to std::map
API (e.g. in the above example you just have to search and replace map
with unordered_map
).
The unordered_map
container was introduced with the C++11 standard revision. Thus, depending on your compiler, you have to enable C++11 features (e.g. when using GCC 4.8 you have to add -std=c++11
to the CXXFLAGS).
Even before the C++11 release GCC supported unordered_map
- in the namespace std::tr1
. Thus, for old GCC compilers you can try to use it like this:
#include <tr1/unordered_map>
std::tr1::unordered_map<std::string, int> m;
It is also part of boost, i.e. you can use the corresponding boost-header for better portability.
The Java compiler (javac
) does not build jars, it translates Java files into class files. The Jar tool (jar
) creates the actual jars. If no custom manifest was specified, the default manifest will specify which version of the JDK was used to create the jar.
I review your url in use:
https://www.facebook.com/sharer/sharer.php?s=100&p[title]=EXAMPLE&p[summary]=EXAMPLE&p[url]=EXAMPLE&p[images][0]=EXAMPLE
and see this differences:
I use this URL string:
http://www.facebook.com/sharer.php?s=100&p[url]=http://www.example.com/&p[images][0]=/images/image.jpg&p[title]=Title&p[summary]=Summary
In the "title" and "summary" section, I use the php function urlencode();
like this:
<?php echo urlencode($detail->title); ?>
And working fine for me.
Solution for me was (thx to David Ljung Madison post)
adb kill-server
None of the solution worked. You have to recompile your python again; once all the required packages were completely installed.
Follow this:
./configure --enable-optimizations
https://gist.github.com/jerblack/798718c1910ccdd4ede92481229043be
pushing a value (not necessarily stored in a register) means writing it to the stack.
popping means restoring whatever is on top of the stack into a register. Those are basic instructions:
push 0xdeadbeef ; push a value to the stack
pop eax ; eax is now 0xdeadbeef
; swap contents of registers
push eax
mov eax, ebx
pop ebx
for(File f : files) {
f.delete();
}
files.delete(); // will work
Alternatively, you can use requests.Session
and observe cookies
before and after a request:
>>> import requests
>>> session = requests.Session()
>>> print(session.cookies.get_dict())
{}
>>> response = session.get('http://google.com')
>>> print(session.cookies.get_dict())
{'PREF': 'ID=5514c728c9215a9a:FF=0:TM=1406958091:LM=1406958091:S=KfAG0U9jYhrB0XNf', 'NID': '67=TVMYiq2wLMNvJi5SiaONeIQVNqxSc2RAwVrCnuYgTQYAHIZAGESHHPL0xsyM9EMpluLDQgaj3db_V37NjvshV-eoQdA8u43M8UwHMqZdL-S2gjho8j0-Fe1XuH5wYr9v'}
datetime.datetime.strptime
has problems with timezone parsing. Have a look at the dateutil
package:
>>> from dateutil import parser
>>> parser.parse("Tue May 08 15:14:45 +0800 2012")
datetime.datetime(2012, 5, 8, 15, 14, 45, tzinfo=tzoffset(None, 28800))
org.apache.commons.io.FilenameUtils version 2.4 gives the following answer
public static String removeExtension(String filename) {
if (filename == null) {
return null;
}
int index = indexOfExtension(filename);
if (index == -1) {
return filename;
} else {
return filename.substring(0, index);
}
}
public static int indexOfExtension(String filename) {
if (filename == null) {
return -1;
}
int extensionPos = filename.lastIndexOf(EXTENSION_SEPARATOR);
int lastSeparator = indexOfLastSeparator(filename);
return lastSeparator > extensionPos ? -1 : extensionPos;
}
public static int indexOfLastSeparator(String filename) {
if (filename == null) {
return -1;
}
int lastUnixPos = filename.lastIndexOf(UNIX_SEPARATOR);
int lastWindowsPos = filename.lastIndexOf(WINDOWS_SEPARATOR);
return Math.max(lastUnixPos, lastWindowsPos);
}
public static final char EXTENSION_SEPARATOR = '.';
private static final char UNIX_SEPARATOR = '/';
private static final char WINDOWS_SEPARATOR = '\\';
Others have answered your question perfectly, but I just thought I would throw out another way. It's always a good idea to separate HTML markup, CSS styling, and javascript code when possible. The cleanest way to hide something, with that in mind, is using a class. It allows the definition of "hide" to be defined in the CSS where it belongs. Using this method, you could later decide you want the ul
to hide by scrolling up or fading away using CSS transition
, all without changing your HTML or code. This is longer, but I feel it's a better overall solution.
Demo: http://jsfiddle.net/ThinkingStiff/RkQCF/
HTML:
<a id="showTags" href="#" title="Show Tags">Show All Tags</a>
<ul id="subforms" class="subforums hide"><li>one</li><li>two</li><li>three</li></ul>
CSS:
#subforms {
overflow-x: visible;
overflow-y: visible;
}
.hide {
display: none;
}
Script:
document.getElementById( 'showTags' ).addEventListener( 'click', function () {
document.getElementById( 'subforms' ).toggleClass( 'hide' );
}, false );
Element.prototype.toggleClass = function ( className ) {
if( this.className.split( ' ' ).indexOf( className ) == -1 ) {
this.className = ( this.className + ' ' + className ).trim();
} else {
this.className = this.className.replace( new RegExp( '(\\s|^)' + className + '(\\s|$)' ), ' ' ).trim();
};
};
I had a similar problem and found that if you remove the size definition, it works for some reason.
Remove:
<size
android:width="60dp"
android:height="40dp" />
from the shape.
Let me know if this works!
This line
<h2>{{hero.name}} details!</h2>
is outside *ngFor
and there is no hero
therefore hero.name
fails.
As mentioned in the error, the official manual and the comments:
Replace
public function TSStatus($host, $queryPort)
with
public function __construct($host, $queryPort)
With the recent release of bootstrap 3, and the glyphicons being merged back to the main Bootstrap repo, Bootstrap CDN is now serving the complete Bootstrap 3.0 css including Glyphicons. The Bootstrap css reference is all you need to include: Glyphicons and its dependencies are on relative paths on the CDN site and are referenced in bootstrap.min.css
.
In html:
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
In css:
@import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css");
Here is a working demo.
Note that you have to use .glyphicon
classes instead of .icon
:
Example:
<span class="glyphicon glyphicon-heart"></span>
Also note that you would still need to include bootstrap.min.js
for usage of Bootstrap JavaScript components, see Bootstrap CDN for url.
If you want to use the Glyphicons separately, you can do that by directly referencing the Glyphicons css on Bootstrap CDN.
In html:
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet">
In css:
@import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css");
Since the css
file already includes all the needed Glyphicons dependencies (which are in a relative path on the Bootstrap CDN site), adding the css
file is all there is to do to start using Glyphicons.
Here is a working demo of the Glyphicons without Bootstrap.
The reason is your base class is not public-ed, then Mockito cannot intercept it due to visibility, if you change base class as public, or @Override in sub class (as public), then Mockito can mock it correctly.
public class BaseService{
public boolean foo(){
return true;
}
}
public ChildService extends BaseService{
}
@Test
@Mock ChildService childService;
public void testSave() {
Mockito.when(childService.foo()).thenReturn(false);
// When
assertFalse(childService.foo());
}
@FunctionalInterface
annotation is useful for compilation time checking of your code. You cannot have more than one method besides static
, default
and abstract methods that override methods in Object
in your @FunctionalInterface
or any other interface used as a functional interface.
But you can use lambdas without this annotation as well as you can override methods without @Override
annotation.
From docs
a functional interface has exactly one abstract method. Since default methods have an implementation, they are not abstract. If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere
This can be used in lambda expression:
public interface Foo {
public void doSomething();
}
This cannot be used in lambda expression:
public interface Foo {
public void doSomething();
public void doSomethingElse();
}
But this will give compilation error:
@FunctionalInterface
public interface Foo {
public void doSomething();
public void doSomethingElse();
}
Invalid '@FunctionalInterface' annotation; Foo is not a functional interface
yourEnum.ordinal()
EnumType.values()[someInt]
EnumType.valueOf(yourString)
yourEnum.name()
A side-note:
As you correctly point out, the ordinal()
may be "unstable" from version to version. This is the exact reason why I always store constants as strings in my databases. (Actually, when using MySql, I store them as MySql enums!)
To test the efficiancy of earlier awnser by Konrad Holl, I did a quick comparison with what I thought would be the slow way of doing it:
package util.collections;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
/**
*
* @author Earl Bosch
* @param <E> Comparable Element
*
*/
public class SortedList<E extends Comparable> implements List<E> {
/**
* The list of elements
*/
private final List<E> list = new ArrayList();
public E first() {
return list.get(0);
}
public E last() {
return list.get(list.size() - 1);
}
public E mid() {
return list.get(list.size() >>> 1);
}
@Override
public void clear() {
list.clear();
}
@Override
public boolean add(E e) {
list.add(e);
Collections.sort(list);
return true;
}
@Override
public int size() {
return list.size();
}
@Override
public boolean isEmpty() {
return list.isEmpty();
}
@Override
public boolean contains(Object obj) {
return list.contains((E) obj);
}
@Override
public Iterator<E> iterator() {
return list.iterator();
}
@Override
public Object[] toArray() {
return list.toArray();
}
@Override
public <T> T[] toArray(T[] arg0) {
return list.toArray(arg0);
}
@Override
public boolean remove(Object obj) {
return list.remove((E) obj);
}
@Override
public boolean containsAll(Collection<?> c) {
return list.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends E> c) {
list.addAll(c);
Collections.sort(list);
return true;
}
@Override
public boolean addAll(int index, Collection<? extends E> c) {
throw new UnsupportedOperationException("Not supported.");
}
@Override
public boolean removeAll(Collection<?> c) {
return list.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
return list.retainAll(c);
}
@Override
public E get(int index) {
return list.get(index);
}
@Override
public E set(int index, E element) {
throw new UnsupportedOperationException("Not supported.");
}
@Override
public void add(int index, E element) {
throw new UnsupportedOperationException("Not supported.");
}
@Override
public E remove(int index) {
return list.remove(index);
}
@Override
public int indexOf(Object obj) {
return list.indexOf((E) obj);
}
@Override
public int lastIndexOf(Object obj) {
return list.lastIndexOf((E) obj);
}
@Override
public ListIterator<E> listIterator() {
return list.listIterator();
}
@Override
public ListIterator<E> listIterator(int index) {
return list.listIterator(index);
}
@Override
public List<E> subList(int fromIndex, int toIndex) {
throw new UnsupportedOperationException("Not supported.");
}
}
Turns out its about twice as fast! I think its because of SortedLinkList slow get - which make's it not a good choice for a list.
Compared times for same random list:
Seems glazedlists.SortedList is really fast...
You can use the pathlib module.
from pathlib import Path
x = Path('./')
print(list(filter(lambda y:y.is_file(), x.iterdir())))
All you have to do is read the code on getbootstrap.com:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
_x000D_
<nav class="navbar navbar-inverse navbar-static-top" role="navigation">_x000D_
<div class="container">_x000D_
<div class="navbar-header">_x000D_
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">_x000D_
<span class="sr-only">Toggle navigation</span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
</button>_x000D_
</div>_x000D_
_x000D_
<!-- Collect the nav links, forms, and other content for toggling -->_x000D_
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
<ul class="nav navbar-nav">_x000D_
<li><a href="index.php">Home</a></li>_x000D_
<li><a href="about.php">About</a></li>_x000D_
<li><a href="#portfolio">Portfolio</a></li>_x000D_
<li><a href="#">Blog</a></li>_x000D_
<li><a href="contact.php">Contact</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
</nav>
_x000D_
I just saw this test:
bool getFileExists(const TCHAR *file)
{
return (GetFileAttributes(file) != 0xFFFFFFFF);
}
I read that you have a c# background. So a good starting point might be a mixin implementation for .NET.
You might want to check out the codeplex project at http://remix.codeplex.com/
Watch the lang.net Symposium link to get an overview. There is still more to come on documentation on codeplex page.
regards Stefan
In my Windows case the listener would not start, and 'lsnrctl start' would hang forever. The solution was to kill all processes of extproc. I suspect it had something funny to do with my vpn
Android MediaPlayer doesn't support streaming of MP3 natively until 2.2. In older versions of the OS it appears to only stream 3GP natively. You can try the pocketjourney code, although it's old (there's a new version here) and I had trouble making it sticky — it would stutter whenever it refilled the buffer.
The NPR News app for Android is open source and uses a local proxy server to handle MP3 streaming in versions of the OS before 2.2. You can see the relevant code in lines 199-216 (r94) here: http://code.google.com/p/npr-android-app/source/browse/Npr/src/org/npr/android/news/PlaybackService.java?r=7cf2352b5c3c0fbcdc18a5a8c67d836577e7e8e3
And this is the StreamProxy class: http://code.google.com/p/npr-android-app/source/browse/Npr/src/org/npr/android/news/StreamProxy.java?r=e4984187f45c39a54ea6c88f71197762dbe10e72
The NPR app is also still getting the "error (-38, 0)" sometimes while streaming. This may be a threading issue or a network change issue. Check the issue tracker for updates.
<img style="width: 50%;" src="..." />
worked just fine for me ... Or am I missing something?
Edit: But see Shawn's caveat about accidentally upsizing.
I got this problem on Android studio, there in either sync or build square were this link like blue text about this issue, press that button and it download something that fix this problem
Paint.NET will create and edit PNGs with gusto. It's an excellent program in many respects. It's free as in beer and speech.
//Delete all cookies
function deleteAllCookies() {
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf("=");
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + '=;' +
'expires=Thu, 01-Jan-1970 00:00:01 GMT;' +
'path=' + '/;' +
'domain=' + window.location.host + ';' +
'secure=;';
}
}
You can simply use linq
Directory.EnumerateFiles(LoanFolder).Select(file => Path.GetFileName(file));
Note: EnumeratesFiles is more efficient compared to Directory.GetFiles as you can start enumerating the collection of names before the whole collection is returned.
Since you say "semantically equivalent" I assume you mean that you want to do more than just literally verify that the xml outputs are (string) equals, and that you'd want something like
<foo> some stuff here</foo></code>
and
<foo>some stuff here</foo></code>
do read as equivalent. Ultimately it's going to matter how you're defining "semantically equivalent" on whatever object you're reconstituting the message from. Simply build that object from the messages and use a custom equals() to define what you're looking for.
This is definitely the cleanest answer to the question: https://stackoverflow.com/a/14025331/1008519.
In combination with table-layout: fixed
I often find <colgroup>
a great tool to make columns act as you want (see codepen here):
table {_x000D_
/* When set to 'fixed', all columns that do not have a width applied will get the remaining space divided between them equally */_x000D_
table-layout: fixed;_x000D_
}_x000D_
.fixed-width {_x000D_
width: 100px;_x000D_
}_x000D_
.col-12 {_x000D_
width: 100%;_x000D_
}_x000D_
.col-11 {_x000D_
width: 91.666666667%;_x000D_
}_x000D_
.col-10 {_x000D_
width: 83.333333333%;_x000D_
}_x000D_
.col-9 {_x000D_
width: 75%;_x000D_
}_x000D_
.col-8 {_x000D_
width: 66.666666667%;_x000D_
}_x000D_
.col-7 {_x000D_
width: 58.333333333%;_x000D_
}_x000D_
.col-6 {_x000D_
width: 50%;_x000D_
}_x000D_
.col-5 {_x000D_
width: 41.666666667%;_x000D_
}_x000D_
.col-4 {_x000D_
width: 33.333333333%;_x000D_
}_x000D_
.col-3 {_x000D_
width: 25%;_x000D_
}_x000D_
.col-2 {_x000D_
width: 16.666666667%;_x000D_
}_x000D_
.col-1 {_x000D_
width: 8.3333333333%;_x000D_
}_x000D_
_x000D_
/* Stylistic improvements from here */_x000D_
_x000D_
.align-left {_x000D_
text-align: left;_x000D_
}_x000D_
.align-right {_x000D_
text-align: right;_x000D_
}_x000D_
table {_x000D_
width: 100%;_x000D_
}_x000D_
table > tbody > tr > td,_x000D_
table > thead > tr > th {_x000D_
padding: 8px;_x000D_
border: 1px solid gray;_x000D_
}
_x000D_
<table cellpadding="0" cellspacing="0" border="0">_x000D_
<colgroup>_x000D_
<col /> <!-- take up rest of the space -->_x000D_
<col class="fixed-width" /> <!-- fixed width -->_x000D_
<col class="col-3" /> <!-- percentage width -->_x000D_
<col /> <!-- take up rest of the space -->_x000D_
</colgroup>_x000D_
<thead>_x000D_
<tr>_x000D_
<th class="align-left">Title</th>_x000D_
<th class="align-right">Count</th>_x000D_
<th class="align-left">Name</th>_x000D_
<th class="align-left">Single</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td class="align-left">This is a very looooooooooong title that may break into multiple lines</td>_x000D_
<td class="align-right">19</td>_x000D_
<td class="align-left">Lisa McArthur</td>_x000D_
<td class="align-left">No</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td class="align-left">This is a shorter title</td>_x000D_
<td class="align-right">2</td>_x000D_
<td class="align-left">John Oliver Nielson McAllister</td>_x000D_
<td class="align-left">Yes</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
_x000D_
_x000D_
<table cellpadding="0" cellspacing="0" border="0">_x000D_
<!-- define everything with percentage width -->_x000D_
<colgroup>_x000D_
<col class="col-6" />_x000D_
<col class="col-1" />_x000D_
<col class="col-4" />_x000D_
<col class="col-1" />_x000D_
</colgroup>_x000D_
<thead>_x000D_
<tr>_x000D_
<th class="align-left">Title</th>_x000D_
<th class="align-right">Count</th>_x000D_
<th class="align-left">Name</th>_x000D_
<th class="align-left">Single</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td class="align-left">This is a very looooooooooong title that may break into multiple lines</td>_x000D_
<td class="align-right">19</td>_x000D_
<td class="align-left">Lisa McArthur</td>_x000D_
<td class="align-left">No</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td class="align-left">This is a shorter title</td>_x000D_
<td class="align-right">2</td>_x000D_
<td class="align-left">John Oliver Nielson McAllister</td>_x000D_
<td class="align-left">Yes</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
You can also get this error if you don't specify center
or zoom
in your map options.
sed
doesn't support \t
, nor other escape sequences like \n
for that matter. The only way I've found to do it was to actually insert the tab character in the script using sed
.
That said, you may want to consider using Perl or Python. Here's a short Python script I wrote that I use for all stream regex'ing:
#!/usr/bin/env python
import sys
import re
def main(args):
if len(args) < 2:
print >> sys.stderr, 'Usage: <search-pattern> <replace-expr>'
raise SystemExit
p = re.compile(args[0], re.MULTILINE | re.DOTALL)
s = sys.stdin.read()
print p.sub(args[1], s),
if __name__ == '__main__':
main(sys.argv[1:])
I ran into this same issue when using the Python MySQLdb module. Since MySQL will let you store just about any binary data you want in a text field regardless of character set, I found my solution here:
Using UTF8 with Python MySQLdb
Edit: Quote from the above URL to satisfy the request in the first comment...
"UnicodeEncodeError:'latin-1' codec can't encode character ..."
This is because MySQLdb normally tries to encode everythin to latin-1. This can be fixed by executing the following commands right after you've etablished the connection:
db.set_character_set('utf8')
dbc.execute('SET NAMES utf8;')
dbc.execute('SET CHARACTER SET utf8;')
dbc.execute('SET character_set_connection=utf8;')
"db" is the result of
MySQLdb.connect()
, and "dbc" is the result ofdb.cursor()
.
There is a new charting library in town: JChartlib JChartLib http://freshmeat.net/projects/jchartlib
It's been a while since I C++'d but these answers are off a bit.
As far as the size goes, 'int' isn't anything. It's a notional value of a standard integer; assumed to be fast for purposes of things like iteration. It doesn't have a preset size.
So, the answers are correct with respect to the differences between int and uint, but are incorrect when they talk about "how large they are" or what their range is. That size is undefined, or more accurately, it will change with the compiler and platform.
It's never polite to discuss the size of your bits in public.
When you compile a program, int does have a size, as you've taken the abstract C/C++ and turned it into concrete machine code.
So, TODAY, practically speaking with most common compilers, they are correct. But do not assume this.
Specifically: if you're writing a 32 bit program, int will be one thing, 64 bit, it can be different, and 16 bit is different. I've gone through all three and briefly looked at 6502 shudder
A brief google search shows this: https://www.tutorialspoint.com/cprogramming/c_data_types.htm This is also good info: https://docs.oracle.com/cd/E19620-01/805-3024/lp64-1/index.html
use int if you really don't care how large your bits are; it can change.
Use size_t and ssize_t if you want to know how large something is.
If you're reading or writing binary data, don't use int. Use a (usually platform/source dependent) specific keyword. WinSDK has plenty of good, maintainable examples of this. Other platforms do too.
I've spent a LOT of time going through code from people that "SMH" at the idea that this is all just academic/pedantic. These ate the people that write unmaintainable code. Sure, it's easy to use type 'int' and use it without all the extra darn typing. It's a lot of work to figure out what they really meant, and a bit mind-numbing.
It's crappy coding when you mix int.
use int and uint when you just want a fast integer and don't care about the range (other than signed/unsigned).
You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015
> 01/02/2016
because 09
> 01
. You need to either put your date in a comparable string format or compare DateTime
objects which are comparable.
<?php
$date_now = date("Y-m-d"); // this format is string comparable
if ($date_now > '2016-01-02') {
echo 'greater than';
}else{
echo 'Less than';
}
Or
<?php
$date_now = new DateTime();
$date2 = new DateTime("01/02/2016");
if ($date_now > $date2) {
echo 'greater than';
}else{
echo 'Less than';
}
.htaccess
is in DOS format, change it to UNIX format (in Notepad++, click Edit>Convert
).htaccess
is in UTF8 Without-BOM, make it WITH BOM.if you use a negative translateX/Y
width and height are not necessary and the style is really short
#form_login {
left : 50%;
top : 50%;
position : absolute;
transform : translate(-50%, -50%);
}
_x000D_
<form id="form_login">
<p>
<input type="text" id="username" placeholder="username" />
</p>
<p>
<input type="password" id="password" placeholder="password" />
</p>
<p>
<input type="text" id="server" placeholder="server" />
</p>
<p>
<button id="submitbutton" type="button">Se connecter</button>
</p>
</form>
_x000D_
Alternatively you could use display: grid
(check the full page view)
body {
margin : 0;
padding : 0;
display : grid;
place-content : center;
min-height : 100vh;
}
_x000D_
<form id="form_login">
<p>
<input type="text" id="username" placeholder="username" />
</p>
<p>
<input type="password" id="password" placeholder="password" />
</p>
<p>
<input type="text" id="server" placeholder="server" />
</p>
<p>
<button id="submitbutton" type="button">Se connecter</button>
</p>
</form>
_x000D_
In JavaScript 1.8.5, Object.getOwnPropertyNames
returns an array of all properties found directly upon a given object.
Object.getOwnPropertyNames ( obj )
and another method Object.keys
, which returns an array containing the names of all of the given object's own enumerable properties.
Object.keys( obj )
I used forEach
to list values and keys in obj, same as for (var key in obj) ..
Object.keys(obj).forEach(function (key) {
console.log( key , obj[key] );
});
This all are new features in ECMAScript , the mothods getOwnPropertyNames
, keys
won't supports old browser's.
If you're using ASP.NET 2.0 or greater, you can turn it on in the Web.config file. In the <system.web> section, add the following line:
<httpCookies httpOnlyCookies="true"/>
There really seems no way for fooling the <a href= ..
into a POST method. However, given that you have access to CSS of a page, this can be substituted by using a form instead.
Unfortunately, the obvious way of just styling the button in CSS as an anchor tag, is not cross-browser compatible, since different browsers treat <button value= ...
differently.
Incorrect:
<form action='actbusy.php' method='post'>
<button type='submit' name='parameter' value='One'>Two</button>
</form>
The above example will be showing 'Two' and transmit 'parameter:One' in FireFox, while it will show 'One' and transmit also 'parameter:One' in IE8.
The way around is to use hidden input field(s) for delivering data and the button just for submitting it.
<form action='actbusy.php' method='post'>
<input class=hidden name='parameter' value='blaah'>
<button type='submit' name='delete' value='Delete'>Delete</button>
</form>
Note, that this method has a side effect that besides 'parameter:blaah' it will also deliver 'delete:Delete' as surplus parameters in POST.
You want to keep for a button the value attribute and button label between tags both the same ('Delete' on this case), since (as stated above) some browsers will display one and some display another as a button label.
I'm sticking to the question as the title states and not the discussion. Which view is top visible on any given point?
@implementation UIView (Extra)
- (UIView *)findTopMostViewForPoint:(CGPoint)point
{
for(int i = self.subviews.count - 1; i >= 0; i--)
{
UIView *subview = [self.subviews objectAtIndex:i];
if(!subview.hidden && CGRectContainsPoint(subview.frame, point))
{
CGPoint pointConverted = [self convertPoint:point toView:subview];
return [subview findTopMostViewForPoint:pointConverted];
}
}
return self;
}
- (UIWindow *)topmostWindow
{
UIWindow *topWindow = [[[UIApplication sharedApplication].windows sortedArrayUsingComparator:^NSComparisonResult(UIWindow *win1, UIWindow *win2) {
return win1.windowLevel - win2.windowLevel;
}] lastObject];
return topWindow;
}
@end
Can be used directly with any UIWindow as receiver or any UIView as receiver.
The following rather compact solution uses the PCRE positive lookahead assertion to match the last occurrence of the substring of interest, that is, an occurrence of the substring which is not followed by any other occurrences of the same substring. Thus the example replaces the last 'fox'
with 'dog'
.
$string = 'The quick brown fox, fox, fox jumps over the lazy fox!!!';
echo preg_replace('/(fox(?!.*fox))/', 'dog', $string);
OUTPUT:
The quick brown fox, fox, fox jumps over the lazy dog!!!
If you have a $_POST['param'] and assume it's string type then
isset($_POST['param']) && $_POST['param'] != '' && $_POST['param'] != '0'
is identical to
!empty($_POST['param'])
Try to add title
and alt
properties to your image.... Gmail and some others blocks images without some attributes.. and it is also a logic to include your email to be read as spam.
No. Actually it's the "same" as
char array[] = {'O', 'n', 'e', ..... 'i','c','\0');
Every character is a separate element, with an additional \0
character as a string terminator.
I quoted "same", because there are some differences between char * array
and char array[]
.
If you want to read more, take a look at C: differences between char pointer and array
Use prevent default
Dojo Toolkit
dojo.connect(form, "onsubmit", function(evt) {
evt.preventDefault();
window.history.back();
});
jQuery
$('#form').submit(function (evt) {
evt.preventDefault();
window.history.back();
});
Vanilla JavaScript
if (element.addEventListener) {
element.addEventListener("submit", function(evt) {
evt.preventDefault();
window.history.back();
}, true);
}
else {
element.attachEvent('onsubmit', function(evt){
evt.preventDefault();
window.history.back();
});
}
Thanks for Ripon Al Wasim's answer. I did some improvement. because of network problems, I retry three times until break loop.
driver.get(url)
# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")
try_times = 0
while True:
# Scroll down to bottom
driver.execute_script("window.scrollBy(0,2000)")
# Wait to load page
time.sleep(scroll_delay)
# Calculate new scroll height and compare with last scroll height
new_height = driver.execute_script("return document.body.scrollHeight")
if last_height == new_height:
try_times += 1
if try_times > 3:
try_times = 0
break
last_height = new_height
I personally like the following Java 1.8 code:
mySwitch("YY")
.myCase("AA", (o) -> {
System.out.println(o+"aa");
})
.myCase("BB", (o) -> {
System.out.println(o+"bb");
})
.myCase("YY", (o) -> {
System.out.println(o+"yy");
})
.myCase("ZZ", (o) -> {
System.out.println(o+"zz");
});
Will output:
YYyy
The sample code uses Strings but you can use any object type, including Class. e.g. .myCase(this.getClass(), (o) -> ...
Needs the following snippet:
public Case mySwitch(Object reference) {
return new Case(reference);
}
public class Case {
private Object reference;
public Case(Object reference) {
this.reference = reference;
}
public Case myCase(Object b, OnMatchDo task) {
if (reference.equals(b)) {
task.task(reference);
}
return this;
}
}
public interface OnMatchDo {
public void task(Object o);
}
For an easy workaround, just copy the HTML file to some cloud share, such as Dropbox, and use the shared link in your browser. Easy.
<style>
form div {
width: 400px;
border: 1px solid black;
}
form input[type='submit'] {
display: inline-block;
width: 70px;
}
div.submitWrapper {
text-align: center;
}
</style>
<form>
<div class='submitWrapper'>
<input type='submit' name='submit' value='Submit'>
</div>
Also Check this jsfiddle
In R2013b or later you can use a table:
>> table = readtable('myfile.txt','Delimiter',';','ReadVariableNames',false)
>> table =
Var1 Var2 Var3 Var4 Var5 Var6 Var7 Var8 Var9 Var10
____ _____ _____ _____ _____ __________ __________ ________ ____ _____
4 'abc' 'def' 'ghj' 'klm' '' '' '' NaN NaN
NaN '' '' '' '' 'Test' 'text' '0xFF' NaN NaN
NaN '' '' '' '' 'asdfhsdf' 'dsafdsag' '0x0F0F' NaN NaN
Here is more info.
Look into the Thinktecture IdentityModel library -- it has full CORS support:
http://brockallen.com/2012/06/28/cors-support-in-webapi-mvc-and-iis-with-thinktecture-identitymodel/
And it can dynamically emit the ACA-Origin you want.
You may get your answer here: Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
UPDATE
It might be due to various issues.I cant say which one is there in your case. It may be because:
Some WMI related services are:
For DCOM settings refer to registry key HKLM\Software\Microsoft\OLE
, value EnableDCOM
. The value should be set to 'Y'.
Try to get the position:relative;
in your #container
. Add an exact width to #container
:
#main_content {
top: 160px;
left: 160px;
width: 800px;
min-height: 500px;
height: auto;
background-color: #2185C5;
position: relative;
}
#container {
width: 600px;
height: auto;
margin: auto;
padding: 10px;
}
The error message which you specified is nothing but you are not specifying goal for maven build.
you can specify any goal in your run configuration for maven build like clear, compile, install, package.
please following below step to resolve it.
Max OS: If you want to toggle comment multiple individual lines versus block comment an entire selection, you can do multi line edit, shift+cmd+L, then cmd+/ in that sequence.
One small point to Andy Hayden's solution – it doesn't work (anymore?) because np.nan == np.nan
yields False
, so the replace
function doesn't actually do anything.
What worked for me was this:
df['b'] = df['b'].apply(lambda x: x if not np.isnan(x) else -1)
(At least that's the behavior for Pandas 0.19.2. Sorry to add it as a different answer, I do not have enough reputation to comment.)
For 'replacement' of deprecated ActionBar, I changed the type of my ActionBar-type variables to PagerTabStrip, as per (old code in comment):
// ActionBar bigActionBar;
PagerTabStrip bigActionBar;
A 'replacement' for ~actionBar's .selectTab(tabindex) was to use my associated ViewPager's .setCurrentItem(int) method, like this (old code in comment):
/*
ActionBar.Tab eventTab = bigActionBar.getTabAt(2);
bigActionBar.selectTab(eventTab);
*/
mViewPager.setCurrentItem(2);
Hope this is helpful.
This is quite a difficult situation, you can get the package name from the apk file, but i assume you want to do it automatically.
AndroLib has the package names for lots of apps but you would have to parse it as there is no API that i could find. Theres a dev section that may have some tools to help you.
Good Luck
Better approach may be a polyfill like this
jQuery.fn.load = function(callback){ $(window).on("load", callback) };
With this you can leave the legacy code untouched. If you use webpack be sure to use script-loader.
You can declare an overloaded function by declaring the function as having a type which has multiple invocation signatures:
interface IFoo
{
bar: {
(s: string): number;
(n: number): string;
}
}
Then the following:
var foo1: IFoo = ...;
var n: number = foo1.bar('baz'); // OK
var s: string = foo1.bar(123); // OK
var a: number[] = foo1.bar([1,2,3]); // ERROR
The actual definition of the function must be singular and perform the appropriate dispatching internally on its arguments.
For example, using a class (which could implement IFoo
, but doesn't have to):
class Foo
{
public bar(s: string): number;
public bar(n: number): string;
public bar(arg: any): any
{
if (typeof(arg) === 'number')
return arg.toString();
if (typeof(arg) === 'string')
return arg.length;
}
}
What's interesting here is that the any
form is hidden by the more specifically typed overrides.
var foo2: new Foo();
var n: number = foo2.bar('baz'); // OK
var s: string = foo2.bar(123); // OK
var a: number[] = foo2.bar([1,2,3]); // ERROR
Try this one:
import Data.List (unfoldr)
separateBy :: Eq a => a -> [a] -> [[a]]
separateBy chr = unfoldr sep where
sep [] = Nothing
sep l = Just . fmap (drop 1) . break (== chr) $ l
Only works for a single char, but should be easily extendable.
I had the same error, but in my case it was caused by the DEBUG mode in Intellij IDE. The debug slowed down the library and then server ended communication at handshake phase. The standard "RUN" worked perfectly.
Using parameter --force:
npm i -f
The following seems to work for my use cases:
$ tern 1 YES NO
YES
$ tern 0 YES NO
NO
$ tern 52 YES NO
YES
$ tern 52 YES NO 52
NO
and can be used in a script like so:
RESULT=$(tern 1 YES NO)
echo "The result is $RESULT"
function show_help()
{
echo ""
echo "usage: BOOLEAN VALUE_IF_TRUE VALUE_IF_FALSE {FALSE_VALUE}"
echo ""
echo "e.g. "
echo ""
echo "tern 1 YES NO => YES"
echo "tern 0 YES NO => NO"
echo "tern "" YES NO => NO"
echo "tern "ANY STRING THAT ISNT 1" YES NO => NO"
echo "ME=$(tern 0 YES NO) => ME contains NO"
echo ""
exit
}
if [ "$1" == "help" ]
then
show_help
fi
if [ -z "$3" ]
then
show_help
fi
# Set a default value for what is "false" -> 0
FALSE_VALUE=${4:-0}
function main
{
if [ "$1" == "$FALSE_VALUE" ]; then
echo $3
exit;
fi;
echo $2
}
main "$1" "$2" "$3"
Here is a way how I found how to extend a enum into other enum, is a very straighfoward approach:
Suposse you have a enum with common constants:
public interface ICommonInterface {
String getName();
}
public enum CommonEnum implements ICommonInterface {
P_EDITABLE("editable"),
P_ACTIVE("active"),
P_ID("id");
private final String name;
EnumCriteriaComun(String name) {
name= name;
}
@Override
public String getName() {
return this.name;
}
}
then you can try to do a manual extends in this way:
public enum SubEnum implements ICommonInterface {
P_EDITABLE(CommonEnum.P_EDITABLE ),
P_ACTIVE(CommonEnum.P_ACTIVE),
P_ID(CommonEnum.P_ID),
P_NEW_CONSTANT("new_constant");
private final String name;
EnumCriteriaComun(CommonEnum commonEnum) {
name= commonEnum.name;
}
EnumCriteriaComun(String name) {
name= name;
}
@Override
public String getName() {
return this.name;
}
}
of course every time you need to extend a constant you have to modify your SubEnum files.
you may try like this using jquery
var arr = [1,2,2,3,4,5,5,5,6,7,7,8,9,10,10];
var uniqueVals = [];
$.each(arr, function(i, el){
if($.inArray(el, uniqueVals) === -1) uniqueVals.push(el);
});
If you use eclipse just go to the top menu
Source --> Generate equals() and hashCode()
Integer
objects are immutable, so you cannot modify the value once they have been created. You will need to create a new Integer
and replace the existing one.
playerID = new Integer(playerID.intValue() + 1);
This error happens if you did not set the password on install, in this case the mysql using unix-socket plugin.
But if delete the plugin link from settings (table mysql.user) will other problem. This does not fix the problem and creates another problem. To fix the deleted link and set password ("PWD") do:
1) Run with --skip-grant-tables
as said above.
If it doesnt works then add the string skip-grant-tables
in section [mysqld]
of /etc/mysql/mysql.conf.d/mysqld.cnf
. Then do
sudo service mysql restart
.
2) Run mysql -u root -p
, then (change "PWD"):
update mysql.user
set authentication_string=PASSWORD("PWD"), plugin="mysql_native_password"
where User='root' and Host='localhost';
flush privileges;
quit
then sudo service mysql restart
. Check: mysql -u root -p
.
Before restart
remove that string from file mysqld.cnf, if you set it there.
It's best to use miske's answer.
If you really want to use natecarlson's repository, the instructions just below can do any of the following:
apt-get update
gives a 404
error after add-apt-repository
apt-get update
gives a NO_PUBKEY
error after manually adding it to /etc/apt/sources.list
Open a terminal and run the following:
sudo -i
Enter your password if necessary, then paste the following into the terminal:
export GOOD_RELEASE='precise'
export BAD_RELEASE="`lsb_release -cs`"
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-add-repository -y ppa:natecarlson/maven3
mv natecarlson-maven3-${BAD_RELEASE}.list natecarlson-maven3-${GOOD_RELEASE}.list
sed -i "s/${BAD_RELEASE}/${GOOD_RELEASE}/" natecarlson-maven3-${GOOD_RELEASE}.list
apt-get update
exit
echo Done!
If you installed natecarlson's repository (either using add-apt-repository
or manually added to /etc/apt/sources.list
) and you don't want it anymore, open a terminal and run the following:
sudo -i
Enter your password if necessary, then paste the following into the terminal:
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-get update
exit
echo Done!
It tells the compiler to try to use a CPU register, instead of RAM, to store the variable. Registers are in the CPU and much faster to access than RAM. But it's only a suggestion to the compiler, and it may not follow through.
You might use datejs to do that. Check the FormatSpecifiers, MMMM gives you the month's name:
var objDate = new Date("10/11/2009");
document.write(objDate.toString("MMMM"));
And datejs got that localized for more than 150 locales! See here
Although I take the risk of not being popular I say they are not useful nowadays.
I think they were well intended and useful in the past when for example DELETE told the server to delete the resource found at supplied URL and PUT (with its sibling PATCH) told the server to do update in an idempotent manner.
Things evolved and URLs became virtual (see url rewriting for example) making resources lose their initial meaning of real folder/subforder/file and so, CRUD action verbs covered by HTTP protocol methods (GET, POST, PUT/PATCH, DELETE) lost track.
Let's take an example:
On the left side is not written the HTTP method, essentially it doesn't matter (POST and GET are enough) and on the right side appropriate HTTP methods are used.
Right side looks elegant, clean and professional. Imagine now you have to maintain a code that's been using the elegant API and you have to search where deletion call is done. You'll search for "api/entity" and among results you'll have to see which one is doing DELETE. Or even worse, you have a junior programmer which by mistake switched PUT with DELETE and as URL is the same shit happened.
In my opinion putting the action verb in the URL has advantages over using the appropriate HTTP method for that action even if it's not so elegant. If you want to see where delete call is made you just have to search for "api/entity/delete" and you'll find it straight away.
Building an API without the whole HTTP array of methods makes it easier to be consumed and maintained afterwards
Swift 5
extension UIView {
fileprivate struct Constants {
static let externalBorderName = "externalBorder"
}
func addExternalBorder(borderWidth: CGFloat = 2.0, borderColor: UIColor = UIColor.white) -> CALayer {
let externalBorder = CALayer()
externalBorder.frame = CGRect(x: -borderWidth, y: -borderWidth, width: frame.size.width + 2 * borderWidth, height: frame.size.height + 2 * borderWidth)
externalBorder.borderColor = borderColor.cgColor
externalBorder.borderWidth = borderWidth
externalBorder.name = Constants.ExternalBorderName
layer.insertSublayer(externalBorder, at: 0)
layer.masksToBounds = false
return externalBorder
}
func removeExternalBorders() {
layer.sublayers?.filter() { $0.name == Constants.externalBorderName }.forEach() {
$0.removeFromSuperlayer()
}
}
func removeExternalBorder(externalBorder: CALayer) {
guard externalBorder.name == Constants.externalBorderName else { return }
externalBorder.removeFromSuperlayer()
}
}
>>> import collections
>>> D1 = collections.defaultdict(list)
>>> for element in L1:
... D1[element[1]].append(element[0])
...
>>> L2 = D1.values()
>>> print L2
[['A', 'C'], ['B'], ['D', 'E']]
>>>
As others said, you can't actually strictly do what you are asking for. That said, all of the tools available to the angular framework are actually available to you as well! What that means is you can actually write your own elements and provide this feature yourself. I wrote one of these up as an example which you can see at the following plunkr (http://plnkr.co/edit/Qrz9zFjc7Ud6KQoNMEI1).
The key parts of this are that I define a "clickable" element (don't do this if you need older IE support). In code that looks like:
<clickable>
<h1>Hello World!</h1>
</clickable>
Then I defined a directive to take this clickable element and turn it into what I want (something that automatically sets up my click event):
app.directive('clickable', function() {
return {
transclude: true,
restrict: 'E',
template: '<div ng-transclude ng-click="handleClick($event)"></div>'
};
});
Finally in my controller I have the click event ready to go:
$scope.handleClick = function($event) {
var i = 0;
};
Now, its worth stating that this hard codes the name of the method that handles the click event. If you wanted to eliminate this, you should be able to provide the directive with the name of your click handler and "tada" - you have an element (or attribute) that you can use and never have to inject "$event" again.
Hope that helps!
static nested class is just like any other outer class, as it doesn't have access to outer class members.
Just for packaging convenience we can club static nested classes into one outer class for readability purpose. Other than this there is no other use case of static nested class.
Example for such kind of usage, you can find in Android R.java (resources) file. Res folder of android contains layouts (containing screen designs), drawable folder (containing images used for project), values folder (which contains string constants), etc..
Sine all the folders are part of Res folder, android tool generates a R.java (resources) file which internally contains lot of static nested classes for each of their inner folders.
Here is the look and feel of R.java file generated in android: Here they are using only for packaging convenience.
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.techpalle.b17_testthird;
public final class R {
public static final class drawable {
public static final int ic_launcher=0x7f020000;
}
public static final class layout {
public static final int activity_main=0x7f030000;
}
public static final class menu {
public static final int main=0x7f070000;
}
public static final class string {
public static final int action_settings=0x7f050001;
public static final int app_name=0x7f050000;
public static final int hello_world=0x7f050002;
}
}
Ya, though w3c says the right click can be detected by the click event, onClick is not triggered through right click in usual browsers.
In fact, right click only trigger onMouseDown onMouseUp and onContextMenu.
Thus, you can regard "onContextMenu" as the right click event. It's an HTML5.0 standard.
best way using Object.keys();
example for getting multi variables names in global scope
// multi varibles for testing
var x = 5 , b = true , m = 6 , v = "str";
// pass all varibles you want in object
function getVarsNames(v = {}){
// getting keys or names !
let names = Object.keys(v);
// return array has real names of varibles
return names;
}
//testing if that work or not
let VarsNames = getVarsNames({x , b , m , v});
console.log(VarsNames); // output is array [x , b , m , v]
Modified code of Tapas's answer:
Dim searcher As New ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem")
Dim collection As ManagementObjectCollection = searcher.[Get]()
Dim username As String
For Each oReturn As ManagementObject In collection
username = oReturn("UserName")
Next
Created a shell script to solve the problem.
https://antofthy.gitlab.io/software/#logrotate_one
This script will run just the single logrotate sub-configuration file found in "/etc/logrotate.d", but include the global settings from in the global configuration file "/etc/logrotate.conf". You can also use other otpions for testing it...
For example...
logrotate_one -d syslog
It seems that the most accurate (and seamless) method of adding the padding for iPhone X/8 using env()...
padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);
Here's a link describing this:
For correlations you can just use the corr function (statistics toolbox)
corr(A_1(:), A_2(:))
Note that you can also just use
corr(A_1, A_2)
But the linear indexing guarantees that your vectors don't need to be transposed.
In my case the path is not set in VPATH, after added the error gone.
Have you checked the docstring of write()
? It says:
write(str) -> None. Write string str to file.
Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written.
So you need to convert y
to str
first.
Also note that the string will be written at the current position which will be at the end of the file, because you'll already have read the old value. Use f.seek(0)
to get to the beginning of the file.`
Edit: As for the IOError
, this issue seems related. A cite from there:
For the modes where both read and writing (or appending) are allowed (those which include a "+" sign), the stream should be flushed (fflush) or repositioned (fseek, fsetpos, rewind) between either a reading operation followed by a writing operation or a writing operation followed by a reading operation.
So, I suggest you try f.seek(0)
and maybe the problem goes away.
Try this: Right click on your project -> Go to properties -> Click signing which is left side of the screen -> Uncheck the Sign the click once manifests -> Save & Build
If by "cursor speed", you mean the repeat rate when holding down a key - then have a look here: http://hints.macworld.com/article.php?story=20090823193018149
To summarize, open up a Terminal window and type the following command:
defaults write NSGlobalDomain KeyRepeat -int 0
More detail from the article:
Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:
defaults write NSGlobalDomain KeyRepeat -int 0
Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.
You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.
Suppose we have a collection like below:
{
"_id":"1234"
"open":"Yes"
"things":{
"paper":1234
"bottle":"Available"
"bottle_count":40
}
}
We want to know if the bottle field is present or not?
Ans:
db.products.find({"things.bottle":{"$exists":true}})
$scope.clearSearch = function () {
$scope.searchAll = "";
};
JsFiddle of how you could do it without using inline JS.
For those coming here from Google like I did, later versions of Powershell have a $foreach
automatic variable. You can find the "current" object with $foreach.Current
The easiest way to print full paths is replace relative start path with absolute path:
grep -r --include="*.sh" "pattern" ${PWD}
According with the HTTP/1.1 standard, the shared IP hosted site can be accessed by a GET request with the IP as URL and a header of the host.
Here there are two examples(wget and curl):
$ wget --header 'Host:somerandomservice.com' http://67.225.235.59
$ curl --header 'Host:somerandomservice.com' http://67.225.235.59
Resources:
https://en.wikipedia.org/wiki/Shared_web_hosting_service
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.23
Yes, you can program Android apps in C++ (for the most part), using the Native Development Kit (NDK), although Java is the primary/preferred language for programming Android, and your C++ code will likely have to interface with Java components, and you'll likely need to read and understand the documentation for Java components, as well. Therefore, I'd advise you to use Java unless you have some existing C++ code base that you need to port and that isn't practical to rewrite in Java.
Java is very similar to C++, I don't think you will have any problems picking it up... going from C++ to Java is incredibly easy; going from Java to C++ is a little more difficult, though not terrible. Java for C++ Programmers does a pretty good job at explaining the differences. Writing your Android code in Java will be more idiomatic and will also make the development process easier for you (as the tooling for the Java Android SDK is significantly better than the corresponding NDK tooling)
In terms of setup, Google provides the Android Studio IDE for both Java and C++ Android development (with Gradle as the build system), but you are free to use whatever IDE or build system you want so long as, under the hood, you are using the Android SDK / NDK to produce the final outputs.
In your case you can do that without using push
at all:
var myArray = [
[1,1,1,1,1],
[1,1,1,1,1],
[1,1,1,1,1]
]
var newRows = 8;
var newCols = 7;
var item;
for (var i = 0; i < newRows; i++) {
item = myArray[i] || (myArray[i] = []);
for (var k = item.length; k < newCols; k++)
item[k] = 0;
}
Ripgrep, which is a fast alternative to grep, has just introduced the --count-matches
flag allowing counting each match in version 0.9 (I'm using the above example to stay consistent):
> echo afoobarfoobar | rg --count foo
1
> echo afoobarfoobar | rg --count-matches foo
2
As asked by OP, ripgrep allows for regex pattern as well (--regexp <PATTERN>
).
Also it can print each (line) match on a separate line:
> echo -e "line1foo\nline2afoobarfoobar" | rg foo
line1foo
line2afoobarfoobar
After installing it http://meldmerge.org/ I had to tell git where it was:
git config --global merge.tool meld
git config --global diff.tool meld
git config --global mergetool.meld.path “C:\Program Files (x86)\Meld\meld.exe”
And that seems to work. Both merging and diffing with “git difftool” or “git mergetool”
If someone facing issue such as Meld crash after starting (problem indication with python) then you need to set up Meld/lib to your system environment variable as bellow
C:\Program Files (x86)\Meld\lib
You can find the codes in the DB2 Information Center. Here's a definition of the -302
from the z/OS Information Center:
THE VALUE OF INPUT VARIABLE OR PARAMETER NUMBER position-number IS INVALID OR TOO LARGE FOR THE TARGET COLUMN OR THE TARGET VALUE
On Linux/Unix/Windows DB2, you'll look under SQL Messages to find your error message. If the code is positive, you'll look for SQLxxxxW
, if it's negative, you'll look for SQLxxxxN
, where xxxx is the code you're looking up.
It wasn't working for me either. vbcrlf and Environment.Newline() both had no effect. My problem was that the Placeholder Properties had a Markup type of HTML. When I changed it to None, it worked like a champ!
None of the above answers worked for me.
This was the solution, from the parent directory run:
git submodule update --init;
cd submodule-directory;
git pull;
cd ..;
git add submodule-directory;
now you can git commit
and git push
This extension helps you to constraint a UIVIew to its superview and superview+safeArea:
extension UIView {
///Constraints a view to its superview
func constraintToSuperView() {
guard let superview = superview else { return }
translatesAutoresizingMaskIntoConstraints = false
topAnchor.constraint(equalTo: superview.topAnchor).isActive = true
leftAnchor.constraint(equalTo: superview.leftAnchor).isActive = true
bottomAnchor.constraint(equalTo: superview.bottomAnchor).isActive = true
rightAnchor.constraint(equalTo: superview.rightAnchor).isActive = true
}
///Constraints a view to its superview safe area
func constraintToSafeArea() {
guard let superview = superview else { return }
translatesAutoresizingMaskIntoConstraints = false
topAnchor.constraint(equalTo: superview.safeAreaLayoutGuide.topAnchor).isActive = true
leftAnchor.constraint(equalTo: superview.safeAreaLayoutGuide.leftAnchor).isActive = true
bottomAnchor.constraint(equalTo: superview.safeAreaLayoutGuide.bottomAnchor).isActive = true
rightAnchor.constraint(equalTo: superview.safeAreaLayoutGuide.rightAnchor).isActive = true
}
}
Using LINQ your query should look something like this:
public User GetUser(int userID){
return
(
from p in "MyTable" //(Your Entity Model)
where p.UserID == userID
select p.Name
).SingleOrDefault();
}
Of course to do this you need to have an ADO.Net Entity Model in your solution.
While make itself is available as a standalone executable (gnuwin32.sourceforge.net
package make
), using it in a proper development environment means using msys2.
Git 2.24 (Q4 2019) illustrates that:
See commit 4668931, commit b35304b, commit ab7d854, commit be5d88e, commit 5d65ad1, commit 030a628, commit 61d1d92, commit e4347c9, commit ed712ef, commit 5b8f9e2, commit 41616ef, commit c097b95 (04 Oct 2019), and commit dbcd970 (30 Sep 2019) by Johannes Schindelin (dscho
).
(Merged by Junio C Hamano -- gitster
-- in commit 6d5291b, 15 Oct 2019)
test-tool run-command
: learn to run (parts of) the testsuiteSigned-off-by: Johannes Schindelin
Git for Windows jumps through hoops to provide a development environment that allows to build Git and to run its test suite.
To that end, an entire MSYS2 system, including GNU make and GCC is offered as "the Git for Windows SDK".
It does come at a price: an initial download of said SDK weighs in with several hundreds of megabytes, and the unpacked SDK occupies ~2GB of disk space.A much more native development environment on Windows is Visual Studio. To help contributors use that environment, we already have a Makefile target
vcxproj
that generates a commit with project files (and other generated files), and Git for Windows'vs/master
branch is continuously re-generated using that target.The idea is to allow building Git in Visual Studio, and to run individual tests using a Portable Git.
Code supporting arbitrary byte orders, ready to be put into a file called order32.h
:
#ifndef ORDER32_H
#define ORDER32_H
#include <limits.h>
#include <stdint.h>
#if CHAR_BIT != 8
#error "unsupported char size"
#endif
enum
{
O32_LITTLE_ENDIAN = 0x03020100ul,
O32_BIG_ENDIAN = 0x00010203ul,
O32_PDP_ENDIAN = 0x01000302ul, /* DEC PDP-11 (aka ENDIAN_LITTLE_WORD) */
O32_HONEYWELL_ENDIAN = 0x02030001ul /* Honeywell 316 (aka ENDIAN_BIG_WORD) */
};
static const union { unsigned char bytes[4]; uint32_t value; } o32_host_order =
{ { 0, 1, 2, 3 } };
#define O32_HOST_ORDER (o32_host_order.value)
#endif
You would check for little endian systems via
O32_HOST_ORDER == O32_LITTLE_ENDIAN
I wanto to display the count of rows in the excel sheet after the filter option has been applied.
So I declared the count of last rows as a variable that can be added to the Msgbox
Sub lastrowcall()
Dim hm As Worksheet
Dim dm As Worksheet
Set dm = ActiveWorkbook.Sheets("datecopy")
Set hm = ActiveWorkbook.Sheets("Home")
Dim lngStart As String, lngEnd As String
lngStart = hm.Range("E23").Value
lngEnd = hm.Range("E25").Value
Dim last_row As String
last_row = dm.Cells(Rows.Count, 1).End(xlUp).Row
MsgBox ("Number of test results between the selected dates " + lngStart + "
and " + lngEnd + " are " + last_row + ". Please Select Yes to continue
Analysis")
End Sub
You could use the URI Class:
$this->uri->segment(n); // n=1 for controller, n=2 for method, etc
I've also been told that the following work, but am currently unable to test:
$this->router->fetch_class();
$this->router->fetch_method();
Oh okay, makes sense. So I did this:
char foo[10] = "hello";
char padded[16];
strcpy(padded, foo);
printf("%s", StringPadRight(padded, 15, " "));
Thanks!
transient
is used to indicate that a class field doesn't need to be serialized.
Probably the best example is a Thread
field. There's usually no reason to serialize a Thread
, as its state is very 'flow specific'.
The default argument allows you to call the function without passing an argument. If you don't pass the argument, then the default argument is supplied. So using your code, this...
test()
...is exactly the same as this:
test(nil)
If you leave out the default argument like this...
func test(firstThing: Int?) {
if firstThing != nil {
print(firstThing!)
}
print("done")
}
...then you can no longer do this...
test()
If you do, you will get the "missing argument" error that you described. You must pass an argument every time, even if that argument is just nil
:
test(nil) // this works
There is solution for you :)
You must run your script after window loaded
if you use jQuery, you can use simple way:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'your-app-id',
xfbml : true,
status : true,
version : 'v2.5'
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<script>
$(window).load(function() {
var comment_callback = function(response) {
console.log("comment_callback");
console.log(response);
}
FB.Event.subscribe('comment.create', comment_callback);
FB.Event.subscribe('comment.remove', comment_callback);
});
</script>
You can use Ctrl + /. This works for me.