Pawel Sawicz .NET blog has a real good explanation and example code, explaining how to call the library;
GET:
var client = new RestClient("192.168.0.1");
var request = new RestRequest("api/item/", Method.GET);
var queryResult = client.Execute<List<Items>>(request).Data;
POST:
var client = new RestClient("http://192.168.0.1");
var request = new RestRequest("api/item/", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(new Item
{
ItemName = someName,
Price = 19.99
});
client.Execute(request);
DELETE:
var item = new Item(){//body};
var client = new RestClient("http://192.168.0.1");
var request = new RestRequest("api/item/{id}", Method.DELETE);
request.AddParameter("id", idItem);
client.Execute(request)
The RestSharp GitHub page has quite an exhaustive sample halfway down the page. To get started install the RestSharp NuGet package in your project, then include the necessary namespace references in your code, then above code should work (possibly negating your need for a full example application).
var i2 = JsonConvert.DeserializeObject(obj["id"].ToString(), type);
throws a parsing exception due to missing quotes around the first argument (I think). I got it to work by adding the quotes:
var i2 = JsonConvert.DeserializeObject("\"" + obj["id"].ToString() + "\"", type);
Hope this will help someone. It worked for me -
RestClient client = new RestClient("http://www.example.com/");
RestRequest request = new RestRequest("login", Method.POST);
request.AddHeader("Accept", "application/json");
var body = new
{
Host = "host_environment",
Username = "UserID",
Password = "Password"
};
request.AddJsonBody(body);
var response = client.Execute(request).Content;
it is better to use json after post your resuest like below
var clien = new RestClient("https://smple.com/");
var request = new RestRequest("index", Method.POST);
request.AddHeader("Sign", signinstance);
request.AddJsonBody(JsonConvert.SerializeObject(yourclass));
var response = client.Execute<YourReturnclassSample>(request);
if (response.StatusCode == System.Net.HttpStatusCode.Created)
{
return Ok(response.Content);
}
The Rest Client answer is perfect! (I upvoted it)
But, just in case you want to go "raw"
..........
I got this to work with HttpClient.
/*
.nuget\packages\newtonsoft.json\12.0.1
.nuget\packages\system.net.http\4.3.4
*/
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
private static async Task<Token> GetElibilityToken(HttpClient client)
{
string baseAddress = @"https://blah.blah.blah.com/oauth2/token";
string grant_type = "client_credentials";
string client_id = "myId";
string client_secret = "shhhhhhhhhhhhhhItsSecret";
var form = new Dictionary<string, string>
{
{"grant_type", grant_type},
{"client_id", client_id},
{"client_secret", client_secret},
};
HttpResponseMessage tokenResponse = await client.PostAsync(baseAddress, new FormUrlEncodedContent(form));
var jsonContent = await tokenResponse.Content.ReadAsStringAsync();
Token tok = JsonConvert.DeserializeObject<Token>(jsonContent);
return tok;
}
internal class Token
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("expires_in")]
public int ExpiresIn { get; set; }
[JsonProperty("refresh_token")]
public string RefreshToken { get; set; }
}
Here is another working example (based off the answer above)......with a few more tweaks. Sometimes the token-service is finicky:
private static async Task<Token> GetATokenToTestMyRestApiUsingHttpClient(HttpClient client)
{
/* this code has lots of commented out stuff with different permutations of tweaking the request */
/* this is a version of asking for token using HttpClient. aka, an alternate to using default libraries instead of RestClient */
OAuthValues oav = GetOAuthValues(); /* object has has simple string properties for TokenUrl, GrantType, ClientId and ClientSecret */
var form = new Dictionary<string, string>
{
{ "grant_type", oav.GrantType },
{ "client_id", oav.ClientId },
{ "client_secret", oav.ClientSecret }
};
/* now tweak the http client */
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("cache-control", "no-cache");
/* try 1 */
////client.DefaultRequestHeaders.Add("content-type", "application/x-www-form-urlencoded");
/* try 2 */
////client.DefaultRequestHeaders .Accept .Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));//ACCEPT header
/* try 3 */
////does not compile */client.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
////application/x-www-form-urlencoded
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, oav.TokenUrl);
/////req.RequestUri = new Uri(baseAddress);
req.Content = new FormUrlEncodedContent(form);
////string jsonPayload = "{\"grant_type\":\"" + oav.GrantType + "\",\"client_id\":\"" + oav.ClientId + "\",\"client_secret\":\"" + oav.ClientSecret + "\"}";
////req.Content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");//CONTENT-TYPE header
req.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
/* now make the request */
////HttpResponseMessage tokenResponse = await client.PostAsync(baseAddress, new FormUrlEncodedContent(form));
HttpResponseMessage tokenResponse = await client.SendAsync(req);
Console.WriteLine(string.Format("HttpResponseMessage.ReasonPhrase='{0}'", tokenResponse.ReasonPhrase));
if (!tokenResponse.IsSuccessStatusCode)
{
throw new HttpRequestException("Call to get Token with HttpClient failed.");
}
var jsonContent = await tokenResponse.Content.ReadAsStringAsync();
Token tok = JsonConvert.DeserializeObject<Token>(jsonContent);
return tok;
}
APPEND
Bonus Material!
If you ever get a
"The remote certificate is invalid according to the validation procedure."
exception......you can wire in a handler to see what is going on (and massage if necessary)
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
using System.Net;
namespace MyNamespace
{
public class MyTokenRetrieverWithExtraStuff
{
public static async Task<Token> GetElibilityToken()
{
using (HttpClientHandler httpClientHandler = new HttpClientHandler())
{
httpClientHandler.ServerCertificateCustomValidationCallback = CertificateValidationCallBack;
using (HttpClient client = new HttpClient(httpClientHandler))
{
return await GetElibilityToken(client);
}
}
}
private static async Task<Token> GetElibilityToken(HttpClient client)
{
// throws certificate error if your cert is wired to localhost //
//string baseAddress = @"https://127.0.0.1/someapp/oauth2/token";
//string baseAddress = @"https://localhost/someapp/oauth2/token";
string baseAddress = @"https://blah.blah.blah.com/oauth2/token";
string grant_type = "client_credentials";
string client_id = "myId";
string client_secret = "shhhhhhhhhhhhhhItsSecret";
var form = new Dictionary<string, string>
{
{"grant_type", grant_type},
{"client_id", client_id},
{"client_secret", client_secret},
};
HttpResponseMessage tokenResponse = await client.PostAsync(baseAddress, new FormUrlEncodedContent(form));
var jsonContent = await tokenResponse.Content.ReadAsStringAsync();
Token tok = JsonConvert.DeserializeObject<Token>(jsonContent);
return tok;
}
private static bool CertificateValidationCallBack(
object sender,
System.Security.Cryptography.X509Certificates.X509Certificate certificate,
System.Security.Cryptography.X509Certificates.X509Chain chain,
System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
// If the certificate is a valid, signed certificate, return true.
if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
{
return true;
}
// If there are errors in the certificate chain, look at each error to determine the cause.
if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0)
{
if (chain != null && chain.ChainStatus != null)
{
foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus)
{
if ((certificate.Subject == certificate.Issuer) &&
(status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot))
{
// Self-signed certificates with an untrusted root are valid.
continue;
}
else
{
if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError)
{
// If there are any other errors in the certificate chain, the certificate is invalid,
// so the method returns false.
return false;
}
}
}
}
// When processing reaches this line, the only errors in the certificate chain are
// untrusted root errors for self-signed certificates. These certificates are valid
// for default Exchange server installations, so return true.
return true;
}
/* overcome localhost and 127.0.0.1 issue */
if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch) != 0)
{
if (certificate.Subject.Contains("localhost"))
{
HttpRequestMessage castSender = sender as HttpRequestMessage;
if (null != castSender)
{
if (castSender.RequestUri.Host.Contains("127.0.0.1"))
{
return true;
}
}
}
}
return false;
}
public class Token
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("expires_in")]
public int ExpiresIn { get; set; }
[JsonProperty("refresh_token")]
public string RefreshToken { get; set; }
}
}
}
........................
I recently found (Jan/2020) an article about all this. I'll add a link here....sometimes having 2 different people show/explain it helps someone trying to learn it.
http://luisquintanilla.me/2017/12/25/client-credentials-authentication-csharp/
Concerning the answer by BoltClock and John, I personally had issues with the initial keyword when using IE11. It works fine in Chrome, but in IE it seems to have no effect.
According to this answer IE does not support the initial keyword: Div display:initial not working as intended in ie10 and chrome 29
I tried setting it blank instead as suggested here: how to revert back to normal after display:none for table row
This worked and was good enough for my scenario. Of course to set the real initial value the above answer is the only good one I could find.
One huge difference is that if you invoke toString()
in a null object you'll get a NullPointerException
whereas, using String.valueOf()
you may not check for null.
wget cant download in multiple connections, instead you can try to user other program like aria2.
Below link saved the day
https://msdn.microsoft.com/en-us/library/ms229076(VS.80).aspx
use the relevant RegSvcs as specified in the above link
c:\Windows\Microsoft. NET\Framework\v4.0.30319\RegSvcs.exe ....\Shared\Your.dll /tlb:Your.tlb
Note: this answer applies only to Angular components and directives, NOT services.
I had this same issue when ngOnInit
(and other lifecycle hooks) were not firing for my components, and most searches led me here.
The issue is that I was using the arrow function syntax (=>
) like this:
class MyComponent implements OnInit {
// Bad: do not use arrow function
public ngOnInit = () => {
console.log("ngOnInit");
}
}
Apparently that does not work in Angular 6. Using non-arrow function syntax fixes the issue:
class MyComponent implements OnInit {
public ngOnInit() {
console.log("ngOnInit");
}
}
For UNIX, try this. It worked for me:
UPDATE mysql.user
SET authentication_string = PASSWORD('MyNewPass'), password_expired = 'N'
WHERE User = 'root' AND Host = 'localhost';
FLUSH PRIVILEGES;
The same query is written as below for psql command prompt of postgres.
D:\TOOLS\Postgresql-9.4.1-3\bin>psql -U postgres -d DatabaseName -h localhost - t -c "Select u.\"UserName\" from users u Where u.\"UserId\"=1;
For me the issue was because of Case sensitivity. I was using ~{fragments/Base}
instead of ~{fragments/base}
(The name of the file was base.html
)
My development environment was windows but the server hosting the application was Linux so I was not seeing this issue during development since windows' paths are not case sensitive.
myfun <- function(x, arg1) {
# doing something here with x and arg1
}
x
is a vector or a list and myfun
in lapply(x, myfun)
is called for each element of x
separately.
Option 1
If you'd like to use whole arg1
in each myfun
call (myfun(x[1], arg1)
, myfun(x[2], arg1)
etc.), use lapply(x, myfun, arg1)
(as stated above).
Option 2
If you'd however like to call myfun
to each element of arg1
separately alongside elements of x
(myfun(x[1], arg1[1])
, myfun(x[2], arg1[2])
etc.), it's not possible to use lapply
. Instead, use mapply(myfun, x, arg1)
(as stated above) or apply
:
apply(cbind(x,arg1), 1, myfun)
or
apply(rbind(x,arg1), 2, myfun).
I made a small benchmark as well. My results were the same. But I need the decode performance. Where I noticed, like a few people above said as well, unserialize
is faster than json_decode
. unserialize
takes roughly 60-70% of the json_decode
time. So the conclusion is fairly simple:
When you need performance in encoding, use json_encode
, when you need performance when decoding, use unserialize
. Because you can not merge the two functions you have to make a choise where you need more performance.
My benchmark in pseudo:
On avarage: unserialize won 96 times over 4 times the json_decode. With an avarage of roughly 1.5ms over 2.5ms.
Following are eight ways to find the Uptime in Windows OS.
In Windows Vista and Windows Server 2008, the Task Manager has been beefed up to show additional information about the system. One of these pieces of info is the server’s running time.
The current system uptime is shown under System or Performance ⇒ CPU for Win 8/10.
The systeminfo
command line utility checks and displays various system statistics such as installation date, installed hotfixes and more.
Open a Command Prompt and type the following command:
systeminfo
You can also narrow down the results to just the line you need:
systeminfo | find "System Boot Time:"
Microsoft have published a tool called Uptime.exe. It is a simple command line tool that analyses the computer's reliability and availability information. It can work locally or remotely. In its simple form, the tool will display the current system uptime. An advanced option allows you to access more detailed information such as shutdown, reboots, operating system crashes, and Service Pack installation.
Read the following KB for more info and for the download links:
To use it, follow these steps:
uptime.exe
utility. You can add a /? to the command in order
to get more options.
It does not offer many command line parameters:
C:\uptimefromcodeplex\> uptime /?
usage: Uptime [-V]
-V display version
C:\uptimefromcodeplex\> uptime -V
version 1.1.0
There is an older version of the "uptime.exe" utility. This has the advantage of NOT needing .NET. (It also has a lot more features beyond simple uptime.)
Download link: Windows NT 4.0 Server Uptime Tool (uptime.exe) (final x86)
C:\uptimev100download>uptime.exe /?
UPTIME, Version 1.00
(C) Copyright 1999, Microsoft Corporation
Uptime [server] [/s ] [/a] [/d:mm/dd/yyyy | /p:n] [/heartbeat] [/? | /help]
server Name or IP address of remote server to process.
/s Display key system events and statistics.
/a Display application failure events (assumes /s).
/d: Only calculate for events after mm/dd/yyyy.
/p: Only calculate for events in the previous n days.
/heartbeat Turn on/off the system's heartbeat
/? Basic usage.
/help Additional usage information.
Another easy method, if you can remember it, is to use the approximate information found in the statistics displayed by the NET STATISTICS command. Open a Command Prompt and type the following command:
net statistics workstation
The statistics should tell you how long it’s been running, although in some cases this information is not as accurate as other methods.
Probably the most accurate of them all, but it does require some clicking. It does not display an exact day or hour count since the last reboot, but it will display important information regarding why the computer was rebooted and when it did so. We need to look at Event ID 6005, which is an event that tells us that the computer has just finished booting, but you should be aware of the fact that there are virtually hundreds if not thousands of other event types that you could potentially learn from.
Note: BTW, the 6006 Event ID is what tells us when the server has gone down, so if there’s much time difference between the 6006 and 6005 events, the server was down for a long time.
Note: You can also open the Event Viewer by typing eventvwr.msc in the Run command, and you might as well use the shortcut found in the Administrative tools folder.
Get-WinEvent -ProviderName eventlog | Where-Object {$_.Id -eq 6005 -or $_.Id -eq 6006}
GetTickCount64 retrieves the number of milliseconds that have elapsed since the system was started.
wmic os get lastbootuptime
Like the tool from Microsoft, but compatible with all operating systems up to and including Windows 10 and Windows Server 2016, this uptime utility does not require an elevated command prompt and offers an option to show the uptime in both DD:HH:MM:SS and in human-readable formats (when executed with the -h
command-line parameter).
Additionally, this version of uptime.exe
will run and show the system uptime even when launched normally from within an explorer.exe session (i.e. not via the command line) and pause for the uptime to be read:
and when executed as uptime -h
:
The function that I use to find the length of the string is length
, used as follows:
SELECT * FROM table ORDER BY length(column);
If you used a raw socket (SOCK_RAW
) and re-implemented TCP in userland, I think the answer is limited in this case only by the number of (local address, source port, destination address, destination port)
tuples (~2^64 per local address).
It would of course take a lot of memory to keep the state of all those connections, and I think you would have to set up some iptables rules to keep the kernel TCP stack from getting upset &/or responding on your behalf.
The string is surrounded by double quotes. Yes, that's not a valid character in a path.
You should probably tackle it at the source, but you can strip them out with:
path = path.Replace("\"", "");
use this in kotlin for print key hash in log
try {
val info = context.getPackageManager().getPackageInfo(context.packageName,
PackageManager.GET_SIGNATURES);
for (signature in info.signatures) {
val md = MessageDigest.getInstance("SHA")
md.update(signature.toByteArray())
Log.d("Key hash ", android.util.Base64.encodeToString(md.digest(), android.util.Base64.DEFAULT))
}
}catch (e:Exception){
}
How about
for (int k = 0; k < 10; k = k + 2) {
if (k == 2) {
break;
}
System.out.println(k);
}
The other way is a labelled loop
myloop: for (int i=0; i < 5; i++) {
for (int j=0; j < 5; j++) {
if (i * j > 6) {
System.out.println("Breaking");
break myloop;
}
System.out.println(i + " " + j);
}
}
For an even better explanation you can check here
you could submit all parameters with such naming:
params[0][topdiameter]
params[0][bottomdiameter]
params[1][topdiameter]
params[1][bottomdiameter]
then later you do something like this:
foreach ($_REQUEST['params'] as $item) {
echo $item['topdiameter'];
echo $item['bottomdiameter'];
}
I would use a single Context class inheriting from IdentityDbContext. This way you can have the context be aware of any relations between your classes and the IdentityUser and Roles of the IdentityDbContext. There is very little overhead in the IdentityDbContext, it is basically a regular DbContext with two DbSets. One for the users and one for the roles.
There could be many reason why document.getElementById
doesn't work
You have an invalid ID
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). (resource: What are valid values for the id attribute in HTML?)
you used some id that you already used as <meta>
name in your header (e.g. copyright, author... ) it looks weird but happened to me: if your 're using IE take a look at
(resource: http://www.phpied.com/getelementbyid-description-in-ie/)
you're targeting an element inside a frame or iframe. In this case if the iframe loads a page within the same domain of the parent you should target the contentdocument
before looking for the element
(resource: Calling a specific id inside a frame)
you're simply looking to an element when the node is not effectively loaded in the DOM, or maybe it's a simple misspelling
I doubt you used same ID twice or more: in that case document.getElementById
should return at least the first element
Programmatically you can use:
/* Here you get int representation of an HTML color resources */
int yourColorWhenEnabled = ContextCompat.getColor(getContext(), R.color.your_color_enabled);
int yourColorWhenDisabled = ContextCompat.getColor(getContext(), R.color.your_color_disabled);
/* Here you get matrix of states, I suppose it is a matrix because using a matrix you can set the same color (you have an array of colors) for different states in the same array */
int[][] states = new int[][]{new int[]{android.R.attr.state_enabled}, new int[]{-android.R.attr.state_enabled}};
/* You pass a ColorStateList instance to "setDefaultHintTextColor" method, remember that you have a matrix for the states of the view and an array for the colors. So the color in position "colors[0x0]" will be used for every states inside the array in the same position inside the matrix "states", so in the array "states[0x0]". So you have "colors[pos] -> states[pos]", or "colors[pos] -> color used for every states inside the array of view states -> states[pos] */
myTextInputLayout.setDefaultHintTextColor(new ColorStateList(states, new int[]{yourColorWhenEnabled, yourColorWhenDisabled})
Explanation:
Get int color value from a color resource (a way to present rgb colors used by android). I wrote ColorEnabled, but really it should be, for this answer, ColorHintExpanded & ColorViewCollapsed. Anyway this is the color you will see when the hint of a view "TextInputLayout" is on Expanded or Collapsed state; you will set it by using next array on function "setDefaultHintTextColor" of the view. Reference: Reference for TextInputLayout - search in this page the method "setDefaultHintTextColor" for more info
Looking to docs above you can see that the functions set the colors for Expanded & Collapsed hint by using a ColorStateList.
To create the ColorStateList I first created a matrix with the states I want, in my case state_enabled & state_disabled (whose are, in TextInputLayout, equals to Hint Expanded and Hint Collapsed [I don't remember in which order lol, anyway I found it just doing a test]). Then I pass to the constructor of the ColorStateList the arrays with int values of color resources, these colors have a correspondences with the states matrix (every element in colors array correspond to the respective array in states matrix at same position). So the first element of the colors array will be used as color for every state in the first array of the states matrix (in our case the array has only 1 element: enabled state = hint expanded state for TextInputLayut). Last things states have positive / negative values, and you have only the positive values, so the state "disabled" in android attrs is "-android.state.enabled", the state "not focused" is "-android.state.focused" ecc.. ecc..
Hope this is helpful. Bye have a nice coding (:
First you need to publish the file by:
BUILD -> PUBLISH or by right clicking project on Solution Explorer -> properties -> publish or select project in Solution Explorer and press Alt + Enter NOTE: if you are using Visual Studio 2013 then in properties you have to go to BUILD and then you have to disable define DEBUG constant and define TRACE constant and you are ready to go.
Save your file to a particular folder.
Find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the bin\Debug
folder below the project file (.csproj).
In Visual Studio they are in the Application Files folder and inside that you just need the .exe and dll files.
(You have to delete ClickOnce and other files and then make this folder a zip file and distribute it.)
NOTE: The ClickOnce application does install the project to system, but it has one advantage. You DO NOT require administrative privileges here to run (if your application follows the normal guidelines for which folders to use for application data, etc.).
For apache-tomcat-8.5.28
modify JDPA_OPTS
like the below then run like catalina.bat jpda start
JPDA_OPTS="-agentlib:jdwp=transport=$JPDA_TRANSPORT,address=$JPDA_ADDRESS,server=y,suspend=$JPDA_SUSPEND"
JPDA_OPTS="-agentlib:jdwp=transport=$JPDA_TRANSPORT,address=8000,server=y,suspend=$JPDA_SUSPEND"
BalusC's answer is right! but I have to mention according to the user instance variable such as:
rSet.last();
total = rSet.getRow();
and then which you are missing
rSet.beforeFirst();
the remaining code is same you will get your desire result.
if you want to follow Android 10 practices to write in storage, check here and if you only want the images to be app specific, here for example if you want to store an image just to be used by your app:
viewModelScope.launch(Dispatchers.IO) {
getApplication<Application>().openFileOutput(filename, Context.MODE_PRIVATE).use {
bitmap.compress(Bitmap.CompressFormat.PNG, 50, it)
}
}
getApplication is a method to give you context for ViewModel and it's part of AndroidViewModel later if you want to read it:
viewModelScope.launch(Dispatchers.IO) {
val savedBitmap = BitmapFactory.decodeStream(
getApplication<App>().openFileInput(filename).readBytes().inputStream()
)
}
One more scenario of this error:
locally
and run the command without npm run
First, it is important to notice this is a "general" terminal error (Even if you write hello bla.js
-or- wowowowow index.js
):
"hello world" example of this error:
-g
) ==> npm install typescript
.
https://docs.npmjs.com/downloading-and-installing-packages-locallytsc
commands available if you run npm run
inside your local project. For example: npm run tsc -v
:-or- install typescript globally (Like other answer mention).
WHERE p.[Type] = isnull(@SearchType, p.[Type])
For the complete system you can add the Microsoft.VisualBasic Framework as a reference;
Console.WriteLine("You have {0} bytes of RAM",
new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory);
Console.ReadLine();
Update:
I'm not sure when or if the license changed for the iText# library, but it is licensed under AGPL which means it must be licensed if included with a closed-source product. The question does not (currently) require free or open-source libraries. One should always investigate the license type of any library used in a project.
I have used iText# with success in .NET C# 3.5; it is a port of the open source Java library for PDF generation and it's free.
There is a NuGet package available for iTextSharp version 5 and the official developer documentation, as well as C# examples, can be found at itextpdf.com
Steps to Fix this issue:
Now clean and rebuild the project, this issue will resolve.
You can't use variable names to bind columns or other system objects, you need dynamic sql
DECLARE @value varchar(10)
SET @value = 'intStep'
DECLARE @sqlText nvarchar(1000);
SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)
As others have noted, it is usually preferable to specify a minimum logging level to log that level and any others more severe than it. It seems like you are just thinking about the logging levels backwards.
However, if you want more fine-grained control over logging individual levels, you can tell log4net to log only one or more specific levels using the following syntax:
<filter type="log4net.Filter.LevelMatchFilter">
<levelToMatch value="WARN"/>
</filter>
Or to exclude a specific logging level by adding a "deny" node to the filter.
You can stack multiple filters together to specify multiple levels. For instance, if you wanted only WARN and FATAL levels. If the levels you wanted were consecutive, then the LevelRangeFilter is more appropriate.
Reference Doc: log4net.Filter.LevelMatchFilter
If the other answers haven't given you enough information, hopefully this will help you get what you want out of log4net.
The code you have posted doesn't include a call to mysql_fetch_array()
. However, what is most likely going wrong is that you are issuing a query that returns an error message, in which case the return value from the query function is false
, and attempting to call mysql_fetch_array()
on it doesn't work (because boolean false
is not a mysql result object).
Do you want to do this?
SELECT id, parent_id, name,
(select Name from tbl where id = t.parent_id) parent_name
FROM tbl t start with id = 1 CONNECT BY PRIOR id = parent_id
Edit Another option based on OMG's one (but I think that will perform equally):
select
t1.id,
t1.parent_id,
t1.name,
t2.name AS parent_name,
t2.id AS parent_id
from
(select id, parent_id, name
from tbl
start with id = 1
connect by prior id = parent_id) t1
left join
tbl t2 on t2.id = t1.parent_id
The issue is that, even though you removed the files, they are still present in previous revisions. That's the whole point of git, is that even if you delete something, you can still get it back by accessing the history.
What you are looking to do is called rewriting history, and it involved the git filter-branch
command.
GitHub has a good explanation of the issue on their site. https://help.github.com/articles/remove-sensitive-data
To answer your question more directly, what you basically need to run is this command with unwanted_filename_or_folder
replaced accordingly:
git filter-branch --index-filter 'git rm -r --cached --ignore-unmatch unwanted_filename_or_folder' --prune-empty
This will remove all references to the files from the active history of the repo.
Next step, to perform a GC cycle to force all references to the file to be expired and purged from the packfile. Nothing needs to be replaced in these commands.
git for-each-ref --format='delete %(refname)' refs/original | git update-ref --stdin
# or, for older git versions (e.g. 1.8.3.1) which don't support --stdin
# git update-ref $(git for-each-ref --format='delete %(refname)' refs/original)
git reflog expire --expire=now --all
git gc --aggressive --prune=now
For anyone looking at this now, on systemd systems (in my case, specifically Ubuntu 16.04) there is another limit enforced by the cgroup pids.max parameter.
This is set to 12,288 by default, and can be overriden in /etc/systemd/logind.conf
Other advice still applies including pids_max, threads-max, max_maps_count, ulimits, etc.
This is how it can be fixed easily through Storyboard (iOS 11 and Xcode 9.1):
Select Table View > Size Inspector > Content Insets: Never
You can wrap all tasks which can fail in block, and use ignore_errors: yes
with that block.
tasks:
- name: ls
command: ls -la
- name: pwd
command: pwd
- block:
- name: ls non-existing txt file
command: ls -la no_file.txt
- name: ls non-existing pic
command: ls -la no_pic.jpg
ignore_errors: yes
Read more about error handling in blocks here.
proxy = urllib2.ProxyHandler({'http': '127.0.0.1'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
urllib2.urlopen('http://www.google.com')
I want to give a more generalized answer. One that will handle any case when you want to select only the first item in a LEFT JOIN.
You can use a subquery that GROUP_CONCATS what you want (sorted, too!), then just split the GROUP_CONCAT'd result and take only its first item, like so...
LEFT JOIN Person ON Person.id = (
SELECT SUBSTRING_INDEX(
GROUP_CONCAT(FirstName ORDER BY FirstName DESC SEPARATOR "_" ), '_', 1)
) FROM Person
);
Since we have DESC as our ORDER BY option, this will return a Person id for someone like "Zack". If we wanted someone with the name like "Andy", we would change ORDER BY FirstName DESC to ORDER BY FirstName ASC.
This is nimble, as this places the power of ordering totally within your hands. But, after much testing, it will not scale well in a situation with lots of users and lots of data.
It is, however, useful in running data-intensive reports for admin.
SELECT *
FROM my_table
WHERE substr(my_field,1,5) = "abcde";
If you have format dd-mm-yyyy then in PHP it won't work as expected. In PHP document they have below guideline.
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
So, you just can't use as you wish. When your try to use dd/mm/yyyy format with this then it will remove FALSE. You can tweak with the following.
$date = "23/02/2013";
$timestamp = strtotime($date);
if ($timestamp === FALSE) {
$timestamp = strtotime(str_replace('/', '-', $date));
}
echo $timestamp; // prints 1361577600
Addressing the question as updated.
#...part of script without redirection...
{
#...part of script with redirection...
} > file1 2>file2 # ...and others as appropriate...
#...residue of script without redirection...
The braces '{ ... }' provide a unit of I/O redirection. The braces must appear where a command could appear - simplistically, at the start of a line or after a semi-colon. (Yes, that can be made more precise; if you want to quibble, let me know.)
You are right that you can preserve the original stdout and stderr with the redirections you showed, but it is usually simpler for the people who have to maintain the script later to understand what's going on if you scope the redirected code as shown above.
The relevant sections of the Bash manual are Grouping Commands and I/O Redirection. The relevant sections of the POSIX shell specification are Compound Commands and I/O Redirection. Bash has some extra notations, but is otherwise similar to the POSIX shell specification.
For Apache Cassandra 2.0 you need to take into account the following TCP ports: (See EC2 security group configuration and Apache Cassandra FAQ)
com.sun.management.jmxremote.rmi.port
property.A possible architecture with Cassandra + OpsCenter on EC2 could look like this:
All you need to do is add:
html {
overflow-y: scroll;
}
In your css file as this will have the scroller whether it is needed or not though you just won't be able to scroll
This means that the viewport will have the same width for both
I think there is a much simpler and more elegant solution. Some of the above-mentioned methods may even throw unhandled exceptions in some cases. Here is a fool-proof (as in never goes wrong) and very fast code. Just try it and compare the results in terms of speed and compactness:
#include <string>
// Convert string of chars to its representative string of hex numbers
void stream2hex(const std::string str, std::string& hexstr, bool capital = false)
{
hexstr.resize(str.size() * 2);
const size_t a = capital ? 'A' - 1 : 'a' - 1;
for (size_t i = 0, c = str[0] & 0xFF; i < hexstr.size(); c = str[i / 2] & 0xFF)
{
hexstr[i++] = c > 0x9F ? (c / 16 - 9) | a : c / 16 | '0';
hexstr[i++] = (c & 0xF) > 9 ? (c % 16 - 9) | a : c % 16 | '0';
}
}
// Convert string of hex numbers to its equivalent char-stream
void hex2stream(const std::string hexstr, std::string& str)
{
str.resize((hexstr.size() + 1) / 2);
for (size_t i = 0, j = 0; i < str.size(); i++, j++)
{
str[i] = (hexstr[j] & '@' ? hexstr[j] + 9 : hexstr[j]) << 4, j++;
str[i] |= (hexstr[j] & '@' ? hexstr[j] + 9 : hexstr[j]) & 0xF;
}
}
#include <iostream>
int main()
{
std::string s = "Hello World!";
std::cout << "original string: " << s << '\n';
stream2hex(s, s);
std::cout << "hex format: " << s << '\n';
hex2stream(s, s);
std::cout << "original one: " << s << '\n';
}
and the result is:
original string: Hello World!
hex format: 48656C6C6F20576F726C6421
original one: Hello World!
If you need a list, not a generator, use list():
from itertools import chain
x = [["a","b"], ["c"]]
y = list(chain(*x))
Public strHostName As String
Public strIPAddress As String
strHostName = System.Net.Dns.GetHostName()
strIPAddress = System.Net.Dns.GetHostEntry(strHostName).AddressList(0).ToString()
MessageBox.Show("Host Name: " & strHostName & "; IP Address: " & strIPAddress)
I have been working on this for some time now. Tough to get right, and I don't claim I do, but I'm happy with it so far. My code and several demos can be found at
Its use is very similar to the TouchInterceptor (on which the code is based), although significant implementation changes have been made.
DragSortListView has smooth and predictable scrolling while dragging and shuffling items. Item shuffles are much more consistent with the position of the dragging/floating item. Heterogeneous-height list items are supported. Drag-scrolling is customizable (I demonstrate rapid drag scrolling through a long list---not that an application comes to mind). Headers/Footers are respected. etc.?? Take a look.
Prior to working on Stack Overflow, I was against NOLOCK
on the principal that you could potentially perform a SELECT
with NOLOCK
and get back results with data that may be out of date or inconsistent. A factor to think about is how many records may be inserted/updated at the same time another process may be selecting data from the same table. If this happens a lot then there's a high probability of deadlocks unless you use a database mode such as READ COMMITED SNAPSHOT
.
I have since changed my perspective on the use of NOLOCK
after witnessing how it can improve SELECT
performance as well as eliminate deadlocks on a massively loaded SQL Server. There are times that you may not care that your data isn't exactly 100% committed and you need results back quickly even though they may be out of date.
Ask yourself a question when thinking of using NOLOCK
:
Does my query include a table that has a high number of
INSERT
/UPDATE
commands and do I care if the data returned from a query may be missing these changes at a given moment?
If the answer is no, then use NOLOCK
to improve performance.
NOLOCK
keyword within the code base for Stack Overflow and found 138 instances, so we use it in quite a few places.
There is not a Google Chrome extension comparable to Selenium IDE.
Scirocco is only a partial (and reportedly unreliable) implementation.
There is another plugin, the Bug Buster Test Recorder, but it only works with their service. I don't know it's effectiveness.
Sahi and TestComplete can also record, but neither are free, and are not browser plugins.
iMacros is a plugin that allows record and playback, but is not geared towards testing, and is not compatible with Selenium.
It sounds like there is a demand for a tool like this, and Firefox is becoming unsupported by Selenium. So, while I know Stack Overflow isn't the forum for this, anyone interested in helping make it happen, let me know.
I'd be interested in what the limitations are and why it hasn't been done. Is it just that the official Selenium team doesn't want to support it, or is there a technical limitation?
Just add margin: 0 auto;
to your table
. No need of adding any property to div
<div style="background-color:lightgrey">_x000D_
<table width="80%" style="margin: 0 auto; border:1px solid;text-align:center">_x000D_
<tr>_x000D_
<th>Name </th>_x000D_
<th>Country</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>John</td>_x000D_
<td>US </td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Bob</td>_x000D_
<td>India </td>_x000D_
</tr>_x000D_
</table>_x000D_
<div>
_x000D_
Note: Added background color to div to visualize the alignment of table to its center
You need to disable Script Debugging In Visual Studio
System.Environment.ExitCode
http://msdn.microsoft.com/en-us/library/system.environment.exitcode.aspx
Another aproach is:
let result = { ...item, location : { ...response } }
But Object spread isn't yet standardized.
May also be helpful: https://stackoverflow.com/a/32926019/5341953
The easiest way to do this is :
ALTER TABLE db.TABLENAME ADD COLUMN [datatype] NOT NULL DEFAULT 'value'
Ex : Adding a column x (bit datatype) to a table ABC with default value 0
ALTER TABLE db.ABC ADD COLUMN x bit NOT NULL DEFAULT 0
PS : I am not a big fan of using the table designer for this. Its so much easier being conventional / old fashioned sometimes. :). Hope this helps answer
Swift 5
To make it easy, create a file "DispatchQueue+Extensions.swift" with this content :
import Foundation
typealias Dispatch = DispatchQueue
extension Dispatch {
static func background(_ task: @escaping () -> ()) {
Dispatch.global(qos: .background).async {
task()
}
}
static func main(_ task: @escaping () -> ()) {
Dispatch.main.async {
task()
}
}
}
Usage :
Dispatch.background {
// do stuff
Dispatch.main {
// update UI
}
}
On Docker for Windows and Mac, and probably others too, it is possible to use the tail option. For example:
docker logs -f --tail 100
This way, only the last 100 lines are shown, and you don't have first to scroll through 1M lines...
(And thus, deleting the log is probably unnecessary)
you can use regexp.
{ "_id" : "1", "name" : "John Doeman" , "function" : "Janitor"}
{ "_id" : "2", "name" : "Jane Doewoman","function" : "Teacher" }
{ "_id" : "3", "name" : "Jimmy Jackal" ,"function" : "Student" }
if you use this query :
{
"query": {
"regexp": {
"name": "J.*"
}
}
}
you will given all of data that their name start with "J".Consider you want to receive just the first two record that their name end with "man" so you can use this query :
{
"query": {
"regexp": {
"name": ".*man"
}
}
}
and if you want to receive all record that in their name exist "m" , you can use this query :
{
"query": {
"regexp": {
"name": ".*m.*"
}
}
}
This works for me .And I hope my answer be suitable for solve your problem.
You can create your own personal API token (OAuth) and use it the same way as you would use your normal credentials (at: /settings/tokens
). For example:
git remote add fork https://[email protected]/foo/bar
git push fork
.netrc
Another method is to configure your user/password in ~/.netrc
(_netrc
on Windows), e.g.
machine github.com
login USERNAME
password PASSWORD
For HTTPS, add the extra line:
protocol https
To cache your GitHub password in Git when using HTTPS, you can use a credential helper to tell Git to remember your GitHub username and password every time it talks to GitHub.
git config --global credential.helper osxkeychain
(osxkeychain helper
is required),git config --global credential.helper wincred
git config --global credential.helper cache
Related:
Inherit Activity Class instead of ListActivity you can resolve this problem.
public class ExampleActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainlist);
}
}
Component:
import { Component, AfterViewInit, ViewChild } from @angular/core;
import { MatPaginator } from @angular/material;
export class ClassName implements AfterViewInit {
@ViewChild(MatPaginator) paginator: MatPaginator;
length = 1000;
pageSize = 10;
pageSizeOptions: number[] = [5, 10, 25, 100];
ngAfterViewInit() {
this.paginator.page.subscribe(
(event) => console.log(event)
);
}
HTML
<mat-paginator
[length]="length"
[pageSize]="pageSize"
[pageSizeOptions]="pageSizeOptions"
[showFirstLastButtons]="true">
</mat-paginator>
Default value for parameters are evaluated at "compilation", once. So obviously you can't access self
. The classic example is list
as default parameter. If you add elements into it, the default value for the parameter changes!
The workaround is to use another default parameter, typically None
, and then check and update the variable.
If your method has no side effects, and doesn't return anything, then it's not doing anything.
If your method does some computation and returns the result of that computation, you can obviously enough assert that the result returned is correct.
If your code doesn't return anything but does have side effects, you can call the code and then assert that the correct side effects have happened. What the side effects are will determine how you do the checks.
In your example, you are calling static methods from your non-returning functions, which makes it tricky unless you can inspect that the result of all those static methods are correct. A better way - from a testing point of view - is to inject actual objects in that you call methods on. You can then use something like EasyMock or Mockito to create a Mock Object in your unit test, and inject the mock object into the class. The Mock Object then lets you assert that the correct functions were called, with the correct values and in the correct order.
For example:
private ErrorFile errorFile;
public void setErrorFile(ErrorFile errorFile) {
this.errorFile = errorFile;
}
private void method1(arg1) {
if (arg1.indexOf("$") == -1) {
//Add an error message
errorFile.addErrorMessage("There is a dollar sign in the specified parameter");
}
}
Then in your test you can write:
public void testMethod1() {
ErrorFile errorFile = EasyMock.createMock(ErrorFile.class);
errorFile.addErrorMessage("There is a dollar sign in the specified parameter");
EasyMock.expectLastCall(errorFile);
EasyMock.replay(errorFile);
ClassToTest classToTest = new ClassToTest();
classToTest.setErrorFile(errorFile);
classToTest.method1("a$b");
EasyMock.verify(errorFile); // This will fail the test if the required addErrorMessage call didn't happen
}
Use .closest()
with a selector:
var $div = $('#divid').closest('div[class^="div-a"]');
LinkedHashMap maintains the order of the keys.
java.util.LinkedHashMap appears to work just like a normal HashMap otherwise.
array_search should work fine, just tested this and it returns the keys as expected:
$list = array('string1', 'string2', 'string3');
echo "Key = ".array_search('string1', $list);
echo " Key = ".array_search('string2', $list);
echo " Key = ".array_search('string3', $list);
Or for the index, you could use
$list = array('string1', 'string2', 'string3');
echo "Index = ".array_search('string1', array_merge($list));
echo " Index = ".array_search('string2', array_merge($list));
echo " Index = ".array_search('string3', array_merge($list));
I'm running version 1.0.2 of flask right now. The above file structures did not work for me, but I found one that did, which are as follows:
app_folder/ flask_app.py/ static/ style.css/ templates/
index.html
(Please note that 'static' and 'templates' are folders, which should be named exactly the same thing.)
To check what version of flask you are running, you should open Python in terminal and type the following accordingly:
import flask
flask --version
Well you have to setup the click event first then you can trigger it and see what happens:
//good habits first let's cache our selector
var $myLink = $('#titleee').find('a');
$myLink.click(function (evt) {
evt.preventDefault();
alert($(this).attr('href'));
});
// now the manual trigger
$myLink.trigger('click');
HTML: text/html
, full-stop.
XHTML: application/xhtml+xml
, or only if following HTML compatbility guidelines, text/html
. See the W3 Media Types Note.
XML: text/xml
, application/xml
(RFC 2376).
There are also many other media types based around XML, for example application/rss+xml
or image/svg+xml
. It's a safe bet that any unrecognised but registered ending in +xml
is XML-based. See the IANA list for registered media types ending in +xml
.
(For unregistered x-
types, all bets are off, but you'd hope +xml
would be respected.)
Ok, instead of identifying players by name track with sockets through which they have connected. You can have a implementation like
var allClients = [];
io.sockets.on('connection', function(socket) {
allClients.push(socket);
socket.on('disconnect', function() {
console.log('Got disconnect!');
var i = allClients.indexOf(socket);
allClients.splice(i, 1);
});
});
Hope this will help you to think in another way
You can also:
public static int unsignedToBytes(byte a)
{
return (int) ( ( a << 24) >>> 24);
}
Explanation:
let's say a = (byte) 133;
In memory it's stored as: "1000 0101" (0x85 in hex)
So its representation translates unsigned=133, signed=-123 (as 2's complement)
a << 24
When left shift is performed 24 bits to the left, the result is now a 4 byte integer which is represented as:
"10000101 00000000 00000000 00000000" (or "0x85000000" in hex)
then we have
( a << 24) >>> 24
and it shifts again on the right 24 bits but fills with leading zeros. So it results to:
"00000000 00000000 00000000 10000101" (or "0x00000085" in hex)
and that is the unsigned representation which equals to 133.
If you tried to cast a = (int) a;
then what would happen is it keeps the 2's complement representation of byte and stores it as int also as 2's complement:
(int) "10000101" ---> "11111111 11111111 11111111 10000101"
And that translates as: -123
Since there's no Request context in the pipeline during app start anymore, I can't imagine there's any way to guess what server/port the next actual request might come in on. You have to so it on Begin_Session.
Here's what I'm using when not in Classic Mode. The overhead is negligible.
/// <summary>
/// Class is called only on the first request
/// </summary>
private class AppStart
{
static bool _init = false;
private static Object _lock = new Object();
/// <summary>
/// Does nothing after first request
/// </summary>
/// <param name="context"></param>
public static void Start(HttpContext context)
{
if (_init)
{
return;
}
//create class level lock in case multiple sessions start simultaneously
lock (_lock)
{
if (!_init)
{
string server = context.Request.ServerVariables["SERVER_NAME"];
string port = context.Request.ServerVariables["SERVER_PORT"];
HttpRuntime.Cache.Insert("basePath", "http://" + server + ":" + port + "/");
_init = true;
}
}
}
}
protected void Session_Start(object sender, EventArgs e)
{
//initializes Cache on first request
AppStart.Start(HttpContext.Current);
}
This worked for me:
Do
$ git status
And check if you have Unmerged paths
# Unmerged paths:
# (use "git reset HEAD <file>..." to unstage)
# (use "git add <file>..." to mark resolution)
#
# both modified: app/assets/images/logo.png
# both modified: app/models/laundry.rb
Fix them with git add
to each of them and try git stash
again.
git add app/assets/images/logo.png
What I did to solve this was to make the changes in the customized cell. You have a custom cell called DataSetCell in its class you could do the following (the code is in swift)
override var isSelected: Bool {
didSet {
if isSelected {
changeStuff
} else {
changeOtherStuff
}
}
}
What this does is that every time the cell is selected, deselected, initialized or get called from the reusable queue, that code will run and the changes will be made. Hope this helps you.
I'm not aware of a tool that does this well but I've seen a variety of homegrown solutions. The common thread of these is to minimise the binary data under version control and maximise textual data to leverage the power of conventional scc systems. To do this:
If you try using:
df[DATE_FIELD]=(pd.to_datetime(df[DATE_FIELD],***unit='s'***))
and receive an error :
"pandas.tslib.OutOfBoundsDatetime: cannot convert input with unit 's'"
This means the DATE_FIELD
is not specified in seconds.
In my case, it was milli seconds - EPOCH time
.
The conversion worked using below:
df[DATE_FIELD]=(pd.to_datetime(df[DATE_FIELD],unit='ms'))
I would suggest you to use a simple and easy plugin called as Quokka which is very popular these days and helps you debug your code on the go. Quokka.js. One biggest advantage in using this plugin is that you save a lot of time to go on web browser and evaluate your code, with help of this you can see everything happening in VS code, which saves a lot of time.
You can use the String split
method to get the single numbers as an array of strings. Then convert them to numbers with the unary plus operator, the Number
function or parseInt
, and add them to your array:
var arr = [1,2,3],
strVale = "130,235,342,124 ";
var strings = strVale.split(",");
for (var i=0; i<strVale.length; i++)
arr.push( + strings[i] );
Or, in one step, using Array map
to convert them and applying them to one single push
:
arr.push.apply(arr, strVale.split(",").map(Number));
for(int i = 0; i < n; i++) {
existing_string += 'c';
}
but you should use StringBuilder instead, and save memory
int n = 3;
String existing_string = "string";
StringBuilder builder = new StringBuilder(existing_string);
for (int i = 0; i < n; i++) {
builder.append(" append ");
}
System.out.println(builder.toString());
The solution (at least on OSX) is:
If you need in a variable the validity of all the files in a directory (git pre-commit hook, build lint script), you can catch the stderr output of the "sh -n" or "bash -n" commands (see other answers) in a variable, and have a "if/else" based on that
bashErrLines=$(find bin/ -type f -name '*.sh' -exec sh -n {} \; 2>&1 > /dev/null)
if [ "$bashErrLines" != "" ]; then
# at least one sh file in the bin dir has a syntax error
echo $bashErrLines;
exit;
fi
Change "sh" with "bash" depending on your needs
Try this:
<style>
#wrapper { position: relative; }
#over_map { position: absolute; top: 10px; left: 10px; z-index: 99; }
</style>
<div id="wrapper">
<div id="google_map">
</div>
<div id="over_map">
</div>
</div>
Your module and your class AthleteList
have the same name. The line
import AthleteList
imports the module and creates a name AthleteList
in your current scope that points to the module object. If you want to access the actual class, use
AthleteList.AthleteList
In particular, in the line
return(AthleteList(templ.pop(0), templ.pop(0), templ))
you are actually accessing the module object and not the class. Try
return(AthleteList.AthleteList(templ.pop(0), templ.pop(0), templ))
A bracket - [
or ]
- means that end of the range is inclusive -- it includes the element listed. A parenthesis - (
or )
- means that end is exclusive and doesn't contain the listed element. So for [first1, last1)
, the range starts with first1
(and includes it), but ends just before last1
.
Assuming integers:
Put that file in assets.
For project created in Android Studio project you need to create assets folder under the main folder.
Read that file as:
public String loadJSONFromAsset(Context context) {
String json = null;
try {
InputStream is = context.getAssets().open("file_name.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
and then you can simply read this string
return by this function as
JSONObject obj = new JSONObject(json_return_by_the_function);
For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html
Hope you will get what you want.
If you ARE using SQL Server, you can just simply wrap the square brackets around the column or table name.
select [select]
from [table]
For PLSQL version 9.0.0.1601
To avoid annoying non-checksum lines : CertUtil -v -hashfile "your_file" SHA1 | FIND /V "CertUtil" This will display only line(s) NOT contaning CertUtil
Shift-Alt-J
is a useful keyboard shortcut in Eclipse for creating Javadoc comment templates.
Invoking the shortcut on a class, method or field declaration will create a Javadoc template:
public int doAction(int i) {
return i;
}
Pressing Shift-Alt-J
on the method declaration gives:
/**
* @param i
* @return
*/
public int doAction(int i) {
return i;
}
The way I use these operators:
||, &&
are for boolean logic. or, and
are for control flow. E.g.
do_smth if may_be || may_be
-- we evaluate the condition here
do_smth or do_smth_else
-- we define the workflow, which is equivalent to
do_smth_else unless do_smth
to give a simple example:
> puts "a" && "b"
b
> puts 'a' and 'b'
a
A well-known idiom in Rails is render and return
. It's a shortcut for saying return if render
, while render && return
won't work. See "Avoiding Double Render Errors" in the Rails documentation for more information.
My approach was similar to @SoftwareFactor, but different, perhaps because I'm running a different OS, Windows Server 2012. These steps worked for me.
Control Panel
> System and Security
> Administrative Tools
> Services
,
right-click SQL Server Browser
> Properties
> General tab
,
change Startup
type to Automatic
,
click Apply
button,
then click Start
button in Service Status
area.
I encountered the same issues: In a relative layout parentView, I have 2 children childView1 and childView2. At first, I put childView1 above childView2 and I want childView1 to be on top of childView2. Changing the order of children views did not solve the problem for me. What worked for me is to set android:clipChildren="false" on parentView and in the code I set:
childView1.bringToFront();
parentView.invalidate();
To anyone still having this issue (Error: Working copy '{DIR}' locked.), I have your solution:
I found that when one of TortoiseSVN windows crash, it leaves a TSVNCache.exe that still has a few handles to your working copy and that is causing the Lock issues you are seeing (and also prevents Clean Up from doing it's job).
So to resolve this:
Either
1a) Use Process Explorer or similar to delete the handles owned by TSVNCache.exe
1b) ..Or even easier, just use Task Manager to kill TSVNCache.exe
Then
2) Right click -> TortoiseSVN -> Clean up. Only "Clean up working copy status" needs to be checked.
From there, happy updating/committing. You can reproduce Lock behavior by doing SVN Update and then quickly killing it's TortoiseProc.exe process before Update finishes.
I use the header(name, value) method and give the return to webResource var:
Client client = Client.create();
WebResource webResource = client.resource("uri");
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
queryParams.add("json", js); //set parametes for request
appKey = "Bearer " + appKey; // appKey is unique number
//Get response from RESTful Server get(ClientResponse.class);
ClientResponse response = webResource.queryParams(queryParams)
.header("Content-Type", "application/json;charset=UTF-8")
.header("Authorization", appKey)
.get(ClientResponse.class);
String jsonStr = response.getEntity(String.class);
According to https://git-scm.com/docs/git-log, for more pretty output in console you can use --decorate argument of git-log command:
git log --pretty=oneline --decorate
will print:
2a5ccd714972552064746e0fb9a7aed747e483c7 (HEAD -> master) New commit
fe00287269b07e2e44f25095748b86c5fc50a3ef (tag: v1.1-01) Commit 3
08ed8cceb27f4f5e5a168831d20a9d2fa5c91d8b (tag: v1.1, tag: v1.0-0.1) commit 1
116340f24354497af488fd63f4f5ad6286e176fc (tag: v1.0) second
52c1cdcb1988d638ec9e05a291e137912b56b3af test
docs explicitly state that destination directory should not exist:
The destination directory, named by
dst
, must not already exist; it will be created as well as missing parent directories.
I think your best bet is to os.walk
the second and all consequent directories, copy2
directory and files and do additional copystat
for directories. After all that's precisely what copytree
does as explained in the docs. Or you could copy
and copystat
each directory/file and os.listdir
instead of os.walk
.
The following example shows benchmarks for a few alternatives.
library(rbenchmark) # Note spelling: "rbenchmark", not "benchmark"
benchmark(seq(0,1e6,by=2),(0:5e5)*2,seq.int(0L,1e6L,by=2L))
## test replications elapsed relative user.self sys.self
## 2 (0:5e+05) * 2 100 0.587 3.536145 0.344 0.244
## 1 seq(0, 1e6, by = 2) 100 2.760 16.626506 1.832 0.900
## 3 seq.int(0, 1e6, by = 2) 100 0.166 1.000000 0.056 0.096
In this case, seq.int
is the fastest method and seq
the slowest. If performance of this step isn't that important (it still takes < 3 seconds to generate a sequence of 500,000 values), I might still use seq
as the most readable solution.
Solved it. Turns out the column had a limited set of characters it would accept, changed it, and now the query works fine.
You can also directly get selected value using following code
<select ng-options='t.name for t in templates'
ng-change='selectedTemplate(t.url)'></select>
script.js
$scope.selectedTemplate = function(pTemplate) {
//Your logic
alert('Template Url is : '+pTemplate);
}
Here are the steps:
cd C:\M1\M2\M3
C:\E1\E2\E3\matlab.exe -r mfile
Windows systems will use your current folder as the location for MATLAB to search for .m files, and the -r
option tries to start the given .m file as soon as startup occurs.
I ran into a similar situation with code that WAS working , then was not.
Turned while dragging / dropping code within a file, I moved an object into another set of braces. Took longer to figure out than I care to admit.
Bit once I move the code back into its proper place, the error resolved.
By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.
In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.
The client code must set the withCredentials
property on the XMLHttpRequest
to true
in order to give permission.
However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials
header. Responding with this header to true
means that the server allows cookies (or other user credentials) to be included on cross-origin requests.
You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.
Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).
forget eval() (is the most misused feature of JS and makes the code slow) and slice(0) (works for simple data types only)
This is the best solution for me:
Object.prototype.clone = function() {
var myObj = (this instanceof Array) ? [] : {};
for (i in this) {
if (i != 'clone') {
if (this[i] && typeof this[i] == "object") {
myObj[i] = this[i].clone();
} else
myObj[i] = this[i];
}
}
return myObj;
};
I have used Dropbox as my Prive or protected svn. Try the link below. http://foyzulkarim.blogspot.com/2012/12/dropbox-as-svn-repository.html
This regularly occurs when you change the extension on the JAR for ZIP, extract the zip content and make some modifications on files such as changing the MANIFEST.MF file which is a very common case, many times Eclipse doesn't generate the MANIFEST file as we want, or maybe we would like to modify the CLASS-PATH or the MAIN-CLASS values of it.
The problem occurs when you zip back the folder.
A valid Runnable/Executable JAR has the next structure:
myJAR (Main-Directory)
|-META-INF (Mandatory)
|-MANIFEST.MF (Mandatory Main-class: com.MainClass)
|-com
|-MainClass.class (must to implement the main method, mandatory)
|-properties files (optional)
|-etc (optional)
If your JAR complies with these rules it will work doesn't matter if you build it manually by using a ZIP tool and then you changed the extension back to .jar
Once you're done try execute it on the command line using:
java -jar myJAR.jar
When you use a zip tool to unpack, change files and zip again, normally the JAR structure changes to this structure which is incorrect, since another directory level is added on the top of the file system making it a corrupted file as is shown below:
**myJAR (Main-Directory)
|-myJAR (creates another directory making the file corrupted)**
|-META-INF (Mandatory)
|-MANIFEST.MF (Mandatory Main-class: com.MainClass)
|-com
|-MainClass.class (must to implement the main method, mandatory)
|-properties files (optional)
|-etc (optional)
:)
After doing a git fetch, you can run git status to show how many commits the local branch is ahead or behind of the remote version of the branch.
This won't show you how many commits it is ahead or behind of a different branch though. Your options are the full diff, looking at github, or using a solution like Vimhsa linked above: Git status over all repo's
To access the mysql
command in Windows without manually changing directories, do this:
Append the path to your MySQL installation to the end of the exisiting 'Variable value'. Example:
%systemDrive%\xampp\mysql\bin\
or, if you prefer
c:\xampp\mysql\bin\
Finally, open a new command prompt to make this change take effect.
Note that MySQL's documentation on Setting Environment Variables has little to say about handling this in Windows.
I would try:
self.wordList = list(wordList)
to force it to make a copy instead of referencing the same object.
in my case the problem was due to watchkit extension being set to swift 3 while the main project's target was set to swift 4.2
why not to take advantage of modern browsers css transition and make things simpler and fast using more css and less jquery
Here is the code for sliding up and down
Here is the code for sliding left to right
Similarly we can change the sliding from top to bottom or right to left by changing transform-origin and transform: scaleX(0) or transform: scaleY(0) appropriately.
If you're in charge (or have any control over the web service), get them to add a unique root element!
If you can't change that at all, then you can do a bit of regex or string-splitting to parse each and pass each element to your XML Reader.
Alternatively, you could manually add a junk root element, by prefixing an opening tag and suffixing a closing tag.
There is also a good PHP 4 json encode / decode library (that is even PHP 5 reverse compatible) written about in this blog post: Using json_encode() and json_decode() in PHP4 (Jun 2009).
The concrete code is by Michal Migurski and by Matt Knapp:
=A1/(24*60*60) + DATE(1970;1;1)
should work with seconds.
=(A1/86400/1000)+25569
if your time is in milliseconds, so dividing by 1000 gives use the correct date
Don't forget to set the type to Date
on your output cell. I tried it with this date: 1504865618099
which is equal to 8-09-17 10:13
.
The simplest way to do this is to add the .config
file in the deployment section on your unit test.
To do so, open the .testrunconfig
file from your Solution Items. In the Deployment section, add the output .config
files from your project's build directory (presumably bin\Debug
).
Anything listed in the deployment section will be copied into the test project's working folder before the tests are run, so your config-dependent code will run fine.
Edit: I forgot to add, this will not work in all situations, so you may need to include a startup script that renames the output .config
to match the unit test's name.
To Save your bitmap in sdcard use the following code
Store Image
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
To Get the Path for Image Storage
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
EDIT From Your comments i have edited the onclick view in this the button1 and button2 functions will be executed separately.
public onClick(View v){
switch(v.getId()){
case R.id.button1:
//Your button 1 function
break;
case R.id. button2:
//Your button 2 function
break;
}
}
install JDK it will work ,
here is the jdk link to download .
link: https://www.oracle.com/technetwork/java/javase/downloads/jdk13-downloads- 5672538.html
s = 'sdsd'
print (s.upper())
upper = raw_input('type in something lowercase.')
lower = raw_input('type in the same thing caps lock.')
print upper.upper()
print lower.lower()
SELECT STUFF((SELECT ', ' + name FROM [table] FOR XML PATH('')), 1, 2, '')
Here's a sample:
DECLARE @t TABLE (name VARCHAR(10))
INSERT INTO @t VALUES ('Peter'), ('Paul'), ('Mary')
SELECT STUFF((SELECT ', ' + name FROM @t FOR XML PATH('')), 1, 2, '')
--Peter, Paul, Mary
As josh527
said, handler.removeCallbacksAndMessages(null);
can work.
But why?
If you have a look at the source code, you can understand it more clearly.
There are 3 type of method to remove callbacks/messages from handler(the MessageQueue):
Handler.java (leave some overload method)
/**
* Remove any pending posts of Runnable <var>r</var> with Object
* <var>token</var> that are in the message queue. If <var>token</var> is null,
* all callbacks will be removed.
*/
public final void removeCallbacks(Runnable r, Object token)
{
mQueue.removeMessages(this, r, token);
}
/**
* Remove any pending posts of messages with code 'what' and whose obj is
* 'object' that are in the message queue. If <var>object</var> is null,
* all messages will be removed.
*/
public final void removeMessages(int what, Object object) {
mQueue.removeMessages(this, what, object);
}
/**
* Remove any pending posts of callbacks and sent messages whose
* <var>obj</var> is <var>token</var>. If <var>token</var> is null,
* all callbacks and messages will be removed.
*/
public final void removeCallbacksAndMessages(Object token) {
mQueue.removeCallbacksAndMessages(this, token);
}
MessageQueue.java do the real work:
void removeMessages(Handler h, int what, Object object) {
if (h == null) {
return;
}
synchronized (this) {
Message p = mMessages;
// Remove all messages at front.
while (p != null && p.target == h && p.what == what
&& (object == null || p.obj == object)) {
Message n = p.next;
mMessages = n;
p.recycleUnchecked();
p = n;
}
// Remove all messages after front.
while (p != null) {
Message n = p.next;
if (n != null) {
if (n.target == h && n.what == what
&& (object == null || n.obj == object)) {
Message nn = n.next;
n.recycleUnchecked();
p.next = nn;
continue;
}
}
p = n;
}
}
}
void removeMessages(Handler h, Runnable r, Object object) {
if (h == null || r == null) {
return;
}
synchronized (this) {
Message p = mMessages;
// Remove all messages at front.
while (p != null && p.target == h && p.callback == r
&& (object == null || p.obj == object)) {
Message n = p.next;
mMessages = n;
p.recycleUnchecked();
p = n;
}
// Remove all messages after front.
while (p != null) {
Message n = p.next;
if (n != null) {
if (n.target == h && n.callback == r
&& (object == null || n.obj == object)) {
Message nn = n.next;
n.recycleUnchecked();
p.next = nn;
continue;
}
}
p = n;
}
}
}
void removeCallbacksAndMessages(Handler h, Object object) {
if (h == null) {
return;
}
synchronized (this) {
Message p = mMessages;
// Remove all messages at front.
while (p != null && p.target == h
&& (object == null || p.obj == object)) {
Message n = p.next;
mMessages = n;
p.recycleUnchecked();
p = n;
}
// Remove all messages after front.
while (p != null) {
Message n = p.next;
if (n != null) {
if (n.target == h && (object == null || n.obj == object)) {
Message nn = n.next;
n.recycleUnchecked();
p.next = nn;
continue;
}
}
p = n;
}
}
}
Anything wrong with a one-liner?
$ perl -pi.bak -e 's/blue/red/g' *_classification.dat
Explanation
-p
processes, then prints <>
line by line-i
activates in-place editing. Files are backed up using the .bak
extensionUsing bit shift is a little quicker...
public static String convertDecimalToBinary(int N) {
StringBuilder binary = new StringBuilder(32);
while (N > 0 ) {
binary.append( N % 2 );
N >>= 1;
}
return binary.reverse().toString();
}
This question is 5 years old. I wonder why still nobody has found the /d
switch to set the working folder:
start /d "c:\activiti-5.9\setup" cmd /k ant demo.start
Try this statement:
exit 1
Replace 1
with appropriate error codes. See also Exit Codes With Special Meanings.
To make it read only
@Html.TextBoxFor(m=> m.Total, new {@class ="form-control", @readonly="true"})
To diable
@Html.TextBoxFor(m=> m.Total, new {@class ="form-control", @disabled="true"})
Three ways to pass model data to partial view (there may be more)
This is view page
Method One Populate at view
@{
PartialViewTestSOl.Models.CountryModel ctry1 = new PartialViewTestSOl.Models.CountryModel();
ctry1.CountryName="India";
ctry1.ID=1;
PartialViewTestSOl.Models.CountryModel ctry2 = new PartialViewTestSOl.Models.CountryModel();
ctry2.CountryName="Africa";
ctry2.ID=2;
List<PartialViewTestSOl.Models.CountryModel> CountryList = new List<PartialViewTestSOl.Models.CountryModel>();
CountryList.Add(ctry1);
CountryList.Add(ctry2);
}
@{
Html.RenderPartial("~/Views/PartialViewTest.cshtml",CountryList );
}
Method Two Pass Through ViewBag
@{
var country = (List<PartialViewTestSOl.Models.CountryModel>)ViewBag.CountryList;
Html.RenderPartial("~/Views/PartialViewTest.cshtml",country );
}
Method Three pass through model
@{
Html.RenderPartial("~/Views/PartialViewTest.cshtml",Model.country );
}
Have you tried the match()
or charmatch()
functions?
Example use:
match(c("A1", "A9", "A6"), myfile$Letter)
Okey so thanks to @bploat and the link to http://www.codingexplorer.com/nsuserdefaults-a-swift-introduction/
I've found that the answer is quite simple for some basic string storage.
let defaults = NSUserDefaults.standardUserDefaults()
// Store
defaults.setObject("theGreatestName", forKey: "username")
// Receive
if let name = defaults.stringForKey("username")
{
print(name)
// Will output "theGreatestName"
}
I've summarized it here http://ridewing.se/blog/save-local-data-in-swift/
At the risk of being accused of shameless self promotion I would like to point out that in my quest for a free load testing tool I went to this article: http://www.devcurry.com/2010/07/10-free-tools-to-loadstress-test-your.html
Either I couldn't get the throughput I wanted, or I couldn't get the flexibility I wanted. AND I wanted to easily aggregate the results of multiple load test generation hosts in post test analysis.
I tried out every tool on the list and to my frustration found that none of them quite did what I wanted to be able to do. So I built one and am sharing it.
Here it is: http://sourceforge.net/projects/loadmonger
PS: No snide comments on the name from folks who are familiar with urban slang. I wasn't but am slightly more worldly now.
I recommend you to use JSON.NET
. it is an open source library to serialize and deserialize your c# objects into json and Json objects into .net objects ...
Serialization Example:
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string json = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "Expiry": new Date(1230422400000),
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
Performance Comparison To Other JSON serializiation Techniques
The regular expression you are looking for is simply this:
[0-9]
You do not mention what language you are using. If your regular expression evaluator forces REs to be anchored, you need this:
.*[0-9].*
Some RE engines (modern ones!) also allow you to write the first as \d
(mnemonically: digit) and the second would then become .*\d.*
.
I think the even shorter answer that you'll like is: StringUtils.isBlank(acct);
From the documentation: http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#isBlank%28java.lang.String%29
isBlank
public static boolean isBlank(String str)
Checks if a String is whitespace, empty ("") or null.
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false
Parameters:
str - the String to check, may be null
Returns:
true if the String is null, empty or whitespace
I came here looking for a solution for extended ascii characters, but couldnt find it. The closest I found is bzlm's solution. But that works only for ASCII Code upto 127(obviously you can replace the encoding type in his code, but i think it was a bit complex to understand. Hence, sharing this version). Here's a solution that works for extended ASCII codes i.e. upto 255 which is the ISO 8859-1
It finds and strips out non-ascii characters(greater than 255)
Dim str1 as String= "â, ??î or ôu? n?i?++$-?!??4?od;/?'®;?:?)///1!@#"
Dim extendedAscii As Encoding = Encoding.GetEncoding("ISO-8859-1",
New EncoderReplacementFallback(String.empty),
New DecoderReplacementFallback())
Dim extendedAsciiBytes() As Byte = extendedAscii.GetBytes(str1)
Dim str2 As String = extendedAscii.GetString(extendedAsciiBytes)
console.WriteLine(str2)
'Output : â, ??î or ôu ni++$-!??4od;/';:)///1!@#$%^yz:
Here's a working fiddle for the code
Replace the encoding as per the requirement, rest should remain the same.
If you don't want to use sessions, the only thing you can do is POST to the same page. Which IMO is the best solution anyway.
// form.php
<?php
if (!empty($_POST['submit'])) {
// validate
if ($allGood) {
// put data into database or whatever needs to be done
header('Location: nextpage.php');
exit;
}
}
?>
<form action="form.php">
<input name="foo" value="<?php if (!empty($_POST['foo'])) echo htmlentities($_POST['foo']); ?>">
...
</form>
This can be made more elegant, but you get the idea...
I've found that using this null comparison works well:
if (Combobox.SelectedItem != null){
//Do something
}
else{
MessageBox.show("Please select a item");
}
This will only accept the selected item and no other value which may have been entered manually by the user which could cause validation issues.
Just came across this problem myself, and the only solution I could find that worked in all my test browsers (IE6, IE7, Firefox) was the following:
The code:
<div style="width: 100%">
<div style="padding-right: 6px;">
<input type="text" style="width: 100%; padding: 2px; margin: 0;
border : solid 1px #999" />
</div>
</div>
Here, the total horizontal overflow for the input element is 6px - 2x(padding + border) - so we set a padding-right for the inner DIV of 6px.
adb reboot
should not reboot your linux box.
But in any case, you can redirect the command to a specific adb device using adb -s <device_id> command
, where
Device ID can be obtained from the command adb devices
command in this case is reboot
Note: I am not sure this will be of any help to you, but you never know.
I found this link:http://www.ubuntugeek.com/howto-convert-vmware-image-to-virtualbox-image.html
ENJOY :-)
I had the same program, I hope this could help.
I your using Windows 7, open Command Prompt-> run as Administrator. register your <...>.dll.
Why run as Administrator, you can register your <...>.dll using the run at the Windows Start, but still your dll only run as user even your account is administrator.
Now you can add your <...>.dll at the Project->Add Reference->Browse
Thanks
For me this one worked
success: function(data){
alert("SUCCCESS");
$.each(data,function(index,itemData){
console.log(JSON.stringify(itemData));
$("#fromDay").append( new Option(itemData.lookupLabel,itemData.id) )
});
}
You can use boost::math::sign()
method from boost/math/special_functions/sign.hpp
if boost is available.
I used this command to find last 5 minutes logs for particular event "DHCPACK
", try below:
$ grep "DHCPACK" /var/log/messages | grep "$(date +%h\ %d) [$(date --date='5 min ago' %H)-$(date +%H)]:*:*"
Using the fileProvider is the way to go. But you can use this simple workaround:
WARNING: It will be fixed in next Android release - https://issuetracker.google.com/issues/37122890#comment4
replace:
startActivity(intent);
by
startActivity(Intent.createChooser(intent, "Your title"));
Exercise 16 from Zed Shaw's book? You can use escape characters as follows:
paragraph1 = "%s \n %s \n %s \n" % (line1, line2, line3)
target.write(paragraph1)
target.close()
This week in milliseconds:
// get today and clear time of day
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0); // ! clear would not reset the hour of day !
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
// get start of this week in milliseconds
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
System.out.println("Start of this week: " + cal.getTime());
System.out.println("... in milliseconds: " + cal.getTimeInMillis());
// start of the next week
cal.add(Calendar.WEEK_OF_YEAR, 1);
System.out.println("Start of the next week: " + cal.getTime());
System.out.println("... in milliseconds: " + cal.getTimeInMillis());
This month in milliseconds:
// get today and clear time of day
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0); // ! clear would not reset the hour of day !
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
// get start of the month
cal.set(Calendar.DAY_OF_MONTH, 1);
System.out.println("Start of the month: " + cal.getTime());
System.out.println("... in milliseconds: " + cal.getTimeInMillis());
// get start of the next month
cal.add(Calendar.MONTH, 1);
System.out.println("Start of the next month: " + cal.getTime());
System.out.println("... in milliseconds: " + cal.getTimeInMillis());
Check if have not set a open_basedir in php.ini or .htaccess of domain what you use. That will jail you in directory of your domain and php will get only access to execute inside this directory.
C:\test>find /c "string" file | find ": 0" 1>nul && echo "execute command here"
use jquery event filter
you can use it like this
$("a:Event(click)")
say you have a dict
with tuples as keys, e.g: labels = {(1,2,0): 'label_1'}
you can modify the elements of the tuple keys as follows:
formatted_labels = {(elem[0],elem[1]):labels[elem] for elem in labels}
Here, we ignore the last elements.
Let's go straight to your question.
Finding the source code for built-in Python functions?
The source code is located at Python/bltinmodule.c
To find the source code in the GitHub repository go here. You can see that all in-built functions start with builtin_<name_of_function>
, for instance, sorted()
is implemented in builtin_sorted
.
For your pleasure I'll post the implementation of sorted()
:
builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *newlist, *v, *seq, *callable;
/* Keyword arguments are passed through list.sort() which will check
them. */
if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
return NULL;
newlist = PySequence_List(seq);
if (newlist == NULL)
return NULL;
callable = _PyObject_GetAttrId(newlist, &PyId_sort);
if (callable == NULL) {
Py_DECREF(newlist);
return NULL;
}
assert(nargs >= 1);
v = _PyObject_FastCallKeywords(callable, args + 1, nargs - 1, kwnames);
Py_DECREF(callable);
if (v == NULL) {
Py_DECREF(newlist);
return NULL;
}
Py_DECREF(v);
return newlist;
}
As you may have noticed, that's not Python code, but C code.
The whole reason for having kubernetes is so it manages the containers for you so you don't have to care so much about the lifecyle of the containers in the pod.
Since you have a deployment
setup that uses replica set
. You can delete the pod using kubectl delete pod test-1495806908-xn5jn
and kubernetes will manage the creation of a new pod with the 2 containers without any downtime. Trying to manually restart single containers in pods negates the whole benefits of kubernetes.
I used @ControllerAdvice
, please check is available in Spring 3.X; I am using it in Spring 4.0.
@ControllerAdvice
public class CommonController extends ControllerBase{
@Autowired
MyService myServiceInstance;
@ModelAttribute("userList")
public List<User> getUsersList()
{
//some code
return ...
}
}
Android brute force will not work if your both the passwords are different so the best option might be like that try to find the file named as
log.idea
in your C:/users/your named account then you might found that in there in android folder open that file lpg.idea in notepad and then search for
alias
using find option in notepad you will find it that the password and alias and alias passwors has been shown there
you are looking for http://api.jquery.com/hasClass/
<div id="mydiv" class="foo bar"></div>
$('#mydiv').hasClass('foo') //returns ture
You can somewhat think about it as array of object vs. array of references.
[SKSpriteNode]
must contain actual objects[SKSpriteNode?]
can contain either references to objects, or nil
Examples
Creating an array with 64 default SKSpriteNode
:
var sprites = [SKSpriteNode](repeatElement(SKSpriteNode(texture: nil),
count: 64))
Creating an array with 64 empty slots (a.k.a optionals):
var optionalSprites = [SKSpriteNode?](repeatElement(nil,
count: 64))
Converting an array of optionals into an array of objects (collapsing [SKSpriteNode?]
into [SKSpriteNode]
):
let flatSprites = optionalSprites.flatMap { $0 }
The count
of the resulting flatSprites
depends on the count of objects in optionalSprites
: empty optionals will be ignored, i.e. skipped.
In our case we were getting UnmarshalException because a wrong Java package was specified in the following. The issue was resolved once the right package was in place:
@Bean
public Unmarshaller tmsUnmarshaller() {
final Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
jaxb2Marshaller
.setPackagesToScan("java.package.to.generated.java.classes.for.xsd");
return jaxb2Marshaller;
}
As per my suggestion if you are doing filter or searching
then you should go with :
$results = User::query();
$results->when($request->that, function ($q) use ($request) {
$q->where('that', $request->that);
});
$results->when($request->this, function ($q) use ($request) {
$q->where('this', $request->that);
});
$results->when($request->this_too, function ($q) use ($request) {
$q->where('this_too', $request->that);
});
$results->get();
yet another solution which uses the fact that np.nan != np.nan
:
In [149]: df.query("EPS == EPS")
Out[149]:
STK_ID EPS cash
STK_ID RPT_Date
600016 20111231 600016 4.3 NaN
601939 20111231 601939 2.5 NaN
Actually you can do it.
Although, someone should note that repeating the CASE
statements are not bad as it seems. SQL Server's query optimizer is smart enough to not execute the CASE
twice so that you won't get any performance hit because of that.
Additionally, someone might use the following logic to not repeat the CASE (if it suits you..)
INSERT INTO dbo.T1
(
Col1,
Col2,
Col3
)
SELECT
1,
SUBSTRING(MyCase.MergedColumns, 0, CHARINDEX('%', MyCase.MergedColumns)),
SUBSTRING(MyCase.MergedColumns, CHARINDEX('%', MyCase.MergedColumns) + 1, LEN(MyCase.MergedColumns) - CHARINDEX('%', MyCase.MergedColumns))
FROM
dbo.T1 t
LEFT OUTER JOIN
(
SELECT CASE WHEN 1 = 1 THEN '2%3' END MergedColumns
) AS MyCase ON 1 = 1
This will insert the values (1, 2, 3) for each record in the table T1
. This uses a delimiter '%'
to split the merged columns. You can write your own split function depending on your needs (e.g. for handling null records or using complex delimiter for varchar
fields etc.). But the main logic is that you should join the CASE
statement and select from the result set of the join with using a split logic.
Check this code. It awesome code for hide div using select item.
HTML
<select name="name" id="cboOptions" onchange="showDiv('div',this)" class="form-control" >
<option value="1">YES</option>
<option value="2">NO</option>
</select>
<div id="div1" style="display:block;">
<input type="text" id="customerName" class="form-control" placeholder="Type Customer Name...">
<input type="text" style="margin-top: 3px;" id="customerAddress" class="form-control" placeholder="Type Customer Address...">
<input type="text" style="margin-top: 3px;" id="customerMobile" class="form-control" placeholder="Type Customer Mobile...">
</div>
<div id="div2" style="display:none;">
<input type="text" list="cars" id="customerID" class="form-control" placeholder="Type Customer Name...">
<datalist id="cars">
<option>Value 1</option>
<option>Value 2</option>
<option>Value 3</option>
<option>Value 4</option>
</datalist>
</div>
JS
<script>
function showDiv(prefix,chooser)
{
for(var i=0;i<chooser.options.length;i++)
{
var div = document.getElementById(prefix+chooser.options[i].value);
div.style.display = 'none';
}
var selectedOption = (chooser.options[chooser.selectedIndex].value);
if(selectedOption == "1")
{
displayDiv(prefix,"1");
}
if(selectedOption == "2")
{
displayDiv(prefix,"2");
}
}
function displayDiv(prefix,suffix)
{
var div = document.getElementById(prefix+suffix);
div.style.display = 'block';
}
</script>
I got the same error when I added a pod repository
pod 'SWRevealViewController'
for an already added source code (SWRevealViewController) from gitHub. So, the error will be fixed by either removing the source code or pod repository.
Case # 2:
The 2nd time, this error appeared when I declare a constant in .h file.
NSString * const SomeConstant = @"SomeValue";
@interface AppDelegate : UIResponder <UIApplicationDelegate> {
...
...
Try running this code, it "just works":
from sklearn import cross_validation, datasets
iris = datasets.load_iris()
X = iris.data[:,:2]
y = iris.target
x_train, x_test, y_train, y_test = cross_validation.train_test_split(X,y,train_size=.8, stratify=y)
y_test
array([0, 0, 0, 0, 2, 2, 1, 0, 1, 2, 2, 0, 0, 1, 0, 1, 1, 2, 1, 2, 0, 2, 2,
1, 2, 1, 1, 0, 2, 1])
You can also use a proxy tool like Charles to capture the outgoing request headers, data, etc. by passing the proxy details through CURLOPT_PROXY
to your curl_setopt_array
method.
For example:
$proxy = '127.0.0.1:8888';
$opt = array (
CURLOPT_URL => "http://www.example.com",
CURLOPT_PROXY => $proxy,
CURLOPT_POST => true,
CURLOPT_VERBOSE => true,
);
$ch = curl_init();
curl_setopt_array($ch, $opt);
curl_exec($ch);
curl_close($ch);
just add your .jar file in applet tag as an attribute as shown below:
<applet
code="file.class"
archive="file.jar"
height=550
width=1100>
</applet>
They are simply showed like this:
_______________________
| <<enumeration>> |
| DaysOfTheWeek |
|_____________________|
| Sunday |
| Monday |
| Tuesday |
| ... |
|_____________________|
And then just have an association between that and your class.
struct x myX;
...
memset(&x, 0, sizeof(myX));
Another option:
$("#<%=dropDownId.ClientID%>").children("option:selected").val();
You can find the info here: http://www.php.net/manual/en/language.operators.comparison.php
It's scarce because it wasn't added until PHP4. What you have is fine though, if you know there may be a type difference then it's a much better comparison, since it's testing value and type in the comparison, not just value.
I had exactly this issue in a recent project which really is a pain in the rear. I finally found it's because the Python we used in Docker has encoding "ansi_x3.4-1968" instead of "utf-8". So if anyone out there using Docker and got this error, following these steps may thoroughly solve your problem.
create a file and name it default_locale in the same directory of your Dockerfile, put this line in it,
environment=LANG="es_ES.utf8", LC_ALL="es_ES.UTF-8", LC_LANG="es_ES.UTF-8"
add these to your Dockerfile,
RUN apt-get clean && apt-get update && apt-get install -y locales
RUN locale-gen en_CA.UTF-8
COPY ./default_locale /etc/default/locale
RUN chmod 0755 /etc/default/locale
ENV LC_ALL=en_CA.UTF-8
ENV LANG=en_CA.UTF-8
ENV LANGUAGE=en_CA.UTF-8
This thoroughly solved my issue when I built and run my Docker again, hopefully this solve your issue also.
You can set padding to your view by pro grammatically throughout below code -
view.setPadding(0,1,20,3);
And, also there are different type of padding available -
These, links will refer Android Developers site. Hope this helps you lot.
I created a Kotlin version based on converting this answer from Java: https://stackoverflow.com/a/13437997/8023278
There is no built in way to disable swiping between pages of a ViewPager, what's required is an extension of ViewPager that overrides onTouchEvent and onInterceptTouchEvent to prevent the swiping action. To make it more generalised we can add a method setSwipePagingEnabled to enable/disable swiping between pages.
class SwipeLockableViewPager(context: Context, attrs: AttributeSet): ViewPager(context, attrs) {
private var swipeEnabled = false
override fun onTouchEvent(event: MotionEvent): Boolean {
return when (swipeEnabled) {
true -> super.onTouchEvent(event)
false -> false
}
}
override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
return when (swipeEnabled) {
true -> super.onInterceptTouchEvent(event)
false -> false
}
}
fun setSwipePagingEnabled(swipeEnabled: Boolean) {
this.swipeEnabled = swipeEnabled
}
}
Then in our layout xml we use our new SwipeLockableViewPager instead of the standard ViewPager
<mypackage.SwipeLockableViewPager
android:id="@+id/myViewPager"
android:layout_height="match_parent"
android:layout_width="match_parent" />
Now in our activity/fragment we can call myViewPager.setSwipePagingEnabled(false)
and users won't be able to swipe between pages
UPDATE
As of 2020 we now have ViewPager2. If you migrate to ViewPager2 there is a built in method to disable swiping: myViewPager2.isUserInputEnabled = false
\n didn't work for me. the \n appear in the bodytext of the email I was sending.. this is how I resolved it.
str_pad($input, 990); //so that the spaces will pad out to the 990 cut off.
You seem to misuse vim, but that's likely due to not being very familiar with it.
The right way is to press Esc, go where you want to do a small correction, fix it, go back and keep editing. It is effective because Vim has much more movements than usual character forward/backward/up/down. After you learn more of them, this will happen to be more productive.
Here's a couple of use-cases:
But, if you still want to do small text traversals without leaving insert mode, follow rson's advice and use Ctrl+O. Taking the first example that I mentioned above, Ctrl+OFf will move you to a previous "f" character and leave you in insert mode.
In the most general way :
isset
tests if a variable (or an element of an array, or a property of an object) exists (and is not null)empty
tests if a variable (...) contains some non-empty data.
To answer question 1 :
$str = '';
var_dump(isset($str));
gives
boolean true
Because the variable $str
exists.
And question 2 :
You should use isset to determine whether a variable exists ; for instance, if you are getting some data as an array, you might need to check if a key isset in that array.
Think about $_GET
/ $_POST
, for instance.
Now, to work on its value, when you know there is such a value : that is the job of empty
.
The problem is the indexing subplot
is using. Subplots are counted starting with 1!
Your code thus needs to read
fig=plt.figure(figsize=(15, 6),facecolor='w', edgecolor='k')
for i in range(10):
#this part is just arranging the data for contourf
ind2 = py.find(zz==i+1)
sfr_mass_mat = np.reshape(sfr_mass[ind2],(pixmax_x,pixmax_y))
sfr_mass_sub = sfr_mass[ind2]
zi = griddata(massloclist, sfrloclist, sfr_mass_sub,xi,yi,interp='nn')
temp = 251+i # this is to index the position of the subplot
ax=plt.subplot(temp)
ax.contourf(xi,yi,zi,5,cmap=plt.cm.Oranges)
plt.subplots_adjust(hspace = .5,wspace=.001)
#just annotating where each contour plot is being placed
ax.set_title(str(temp))
Note the change in the line where you calculate temp
They're actually really similar. How you call them is exactly the same.The difference lies in how the browser loads them into the execution context.
Function declarations load before any code is executed.
Function expressions load only when the interpreter reaches that line of code.
So if you try to call a function expression before it's loaded, you'll get an error! If you call a function declaration instead, it'll always work, because no code can be called until all declarations are loaded.
Example: Function Expression
alert(foo()); // ERROR! foo wasn't loaded yet
var foo = function() { return 5; }
Example: Function Declaration
alert(foo()); // Alerts 5. Declarations are loaded before any code can run.
function foo() { return 5; }
As for the second part of your question:
var foo = function foo() { return 5; }
is really the same as the other two. It's just that this line of code used to cause an error in safari, though it no longer does.
you could also change from the .get()
method to the .getJSON()
method, jQuery will then parse the string returned as data
to a javascript object and/or array that you can then reference like any other javascript object/array.
using your code above, if you changed .get
to .getJSON
, you should get an alert of [object Object]
for each element in the array. If you changed the alert to alert(item.name)
you will get the names.
Try this:
$query = mysql_query("SELECT username FROM Users WHERE username='$username' ")
Don't add $con
to mysql_query()
function.
Disclaimer: using the username
variable in the string passed to mysql_query
, as shown above, is a trivial SQL injection attack vector in so far the username
depends on parameters of the Web request (query string, headers, request body, etc), or otherwise parameters a malicious entity may control.
There is no feature in scp to filter files. For "advanced" stuff like this, I recommend using rsync:
rsync -av --exclude '*.svn' user@server:/my/dir .
(this line copy rsync from distant folder to current one)
Recent versions of rsync tunnel over an ssh connection automatically by default.
As long as the macros in question are in the same workbook and you verify the names exist, you can call those macros from any other module by name, not by module.
So if in Module1 you had two macros Macro1 and Macro2 and in Module2 you had Macro3 and Macro 4, then in another macro you could call them all:
Sub MasterMacro()
Call Macro1
Call Macro2
Call Macro3
Call Macro4
End Sub
You can easily add a drop-shadow effect to an svg-element using the drop-shadow() CSS function and rgba color values. By using rgba color values you can change the opacity of your shadow.
img.light-shadow{_x000D_
filter: drop-shadow(0px 3px 3px rgba(0, 0, 0, 0.4));_x000D_
}_x000D_
_x000D_
img.dark-shadow{_x000D_
filter: drop-shadow(0px 3px 3px rgba(0, 0, 0, 1));_x000D_
}
_x000D_
<img class="light-shadow" src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.svg" />_x000D_
<img class="dark-shadow" src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.svg" />
_x000D_
MSDN details it here very nicely on how to check it from registry:
To find .NET Framework versions by viewing the registry (.NET Framework 1-4)
- On the Start menu, choose Run.
- In the Open box, enter regedit.exe.You must have administrative credentials to run regedit.exe.
In the Registry Editor, open the following subkey:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP
The installed versions are listed under the NDP subkey. The version number is stored in the Version entry. For the .NET Framework 4 the Version entry is under the Client or Full subkey (under NDP), or under both subkeys.
To find .NET Framework versions by viewing the registry (.NET Framework 4.5 and later)
- On the Start menu, choose Run.
- In the Open box, enter regedit.exe. You must have administrative credentials to run regedit.exe.
In the Registry Editor, open the following subkey:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full
Note that the path to the Full subkey includes the subkey Net Framework rather than .NET Framework
Check for a DWORD value named
Release
. The existence of the Release DWORD indicates that the .NET Framework 4.5 or newer has been installed on that computer.
Note: The last row in the above snapshot which got clipped reads On all other OS versions: 461310
. I tried my level best to avoid the information getting clipped while taking the screenshot but the table was way too big.
Using the TreeMap you can sort the Map.
Map<String, String> map = new HashMap<String, String>();
Map<String, String> treeMap = new TreeMap<String, String>(map);
//show hashmap after the sort
for (String str : treeMap.keySet()) {
System.out.println(str);
}
You should add fstream::out to open method like this:
file.open("test.txt",fstream::out);
More information about fstream flags, check out this link: http://www.cplusplus.com/reference/fstream/fstream/open/
You might find your code is more maintainable if you keep all your styles, etc. in CSS and just set / unset class names in JavaScript.
Your CSS would obviously be something like:
.highlight {
background:#ff00aa;
}
Then in JavaScript:
element.className = element.className === 'highlight' ? '' : 'highlight';
The currently accepted answer does not actually address the question, which asks how to save lists that contain both strings and float numbers. For completeness I provide a fully working example, which is based, with some modifications, on the link given in @joris comment.
import numpy as np
names = np.array(['NAME_1', 'NAME_2', 'NAME_3'])
floats = np.array([ 0.1234 , 0.5678 , 0.9123 ])
ab = np.zeros(names.size, dtype=[('var1', 'U6'), ('var2', float)])
ab['var1'] = names
ab['var2'] = floats
np.savetxt('test.txt', ab, fmt="%10s %10.3f")
Update: This example also works properly in Python 3 by using the 'U6'
Unicode string dtype, when creating the ab
structured array, instead of the 'S6'
byte string. The latter dtype would work in Python 2.7, but would write strings like b'NAME_1'
in Python 3.
The document.location
is an object that contains properties for the current location.
The href
property is one of these properties, containing the complete URL, i.e. all the other properties put together.
Some browsers allow you to assign an URL to the location
object and acts as if you assigned it to the href
property. Some other browsers are more picky, and requires you to use the href
property. Thus, to make the code work in all browsers, you have to use the href
property.
Both the window
and document
objects has a location
object. You can set the URL using either window.location.href
or document.location.href
. However, logically the document.location
object should be read-only (as you can't change the URL of a document; changing the URL loads a new document), so to be on the safe side you should rather use window.location.href
when you want to set the URL.
I had this problem when I accidentally redeclared myApp
:
var myApp = angular.module('myApp',[...]);
myApp.controller('Controller1', ...);
var myApp = angular.module('myApp',[...]);
myApp.controller('Controller2', ...);
After the redeclare, Controller1
stops working and raises the OP error.
The ASIDE has since been modified to include secondary content as well.
HTML5 Doctor has a great writeup on it here: http://html5doctor.com/aside-revisited/
Excerpt:
With the new definition of aside, it’s crucial to remain aware of its context. >When used within an article element, the contents should be specifically related >to that article (e.g., a glossary). When used outside of an article element, the >contents should be related to the site (e.g., a blogroll, groups of additional >navigation, and even advertising if that content is related to the page).
I had the same problem. None of the solutions here worked. I had to completely reinstall eclipse and make a new workspace. Then it worked!
using commands module
import commands
"""
Get high load process details
"""
result = commands.getoutput("ps aux | sort -nrk 3,3 | head -n 1")
print result -- python 2x
print (result) -- python 3x
I know there were lots of answers here, but the TL;DR version is this (If you're using Xamarin Studio):
Options
Android Build
Advanced
tabx86
/ armeabi-v7a
/ armeabi
)A similar question was asked, but it didn't ask about statics.
A static variable is basically a global variable, even if you cannot access it globally. Usually there is an address for it that is in the executable itself. There is only one copy for the entire program. No matter how many times you go into a function call (or class) (and in how many threads!) the variable is referring to the same memory location.
The heap is a bunch of memory that can be used dynamically. If you want 4kb for an object then the dynamic allocator will look through its list of free space in the heap, pick out a 4kb chunk, and give it to you. Generally, the dynamic memory allocator (malloc, new, et c.) starts at the end of memory and works backwards.
Explaining how a stack grows and shrinks is a bit outside the scope of this answer, but suffice to say you always add and remove from the end only. Stacks usually start high and grow down to lower addresses. You run out of memory when the stack meets the dynamic allocator somewhere in the middle (but refer to physical versus virtual memory and fragmentation). Multiple threads will require multiple stacks (the process generally reserves a minimum size for the stack).
Statics/globals are useful for memory that you know you will always need and you know that you don't ever want to deallocate. (By the way, embedded environments may be thought of as having only static memory... the stack and heap are part of a known address space shared by a third memory type: the program code. Programs will often do dynamic allocation out of their static memory when they need things like linked lists. But regardless, the static memory itself (the buffer) is not itself "allocated", but rather other objects are allocated out of the memory held by the buffer for this purpose. You can do this in non-embedded as well, and console games will frequently eschew the built in dynamic memory mechanisms in favor of tightly controlling the allocation process by using buffers of preset sizes for all allocations.)
Stack variables are useful for when you know that as long as the function is in scope (on the stack somewhere), you will want the variables to remain. Stacks are nice for variables that you need for the code where they are located, but which isn't needed outside that code. They are also really nice for when you are accessing a resource, like a file, and want the resource to automatically go away when you leave that code.
Heap allocations (dynamically allocated memory) is useful when you want to be more flexible than the above. Frequently, a function gets called to respond to an event (the user clicks the "create box" button). The proper response may require allocating a new object (a new Box object) that should stick around long after the function is exited, so it can't be on the stack. But you don't know how many boxes you would want at the start of the program, so it can't be a static.
I've heard a lot lately about how great Garbage Collectors are, so maybe a bit of a dissenting voice would be helpful.
Garbage Collection is a wonderful mechanism for when performance is not a huge issue. I hear GCs are getting better and more sophisticated, but the fact is, you may be forced to accept a performance penalty (depending upon use case). And if you're lazy, it still may not work properly. At the best of times, Garbage Collectors realize that your memory goes away when it realizes that there are no more references to it (see reference counting). But, if you have an object that refers to itself (possibly by referring to another object which refers back), then reference counting alone will not indicate that the memory can be deleted. In this case, the GC needs to look at the entire reference soup and figure out if there are any islands that are only referred to by themselves. Offhand, I'd guess that to be an O(n^2) operation, but whatever it is, it can get bad if you are at all concerned with performance. (Edit: Martin B points out that it is O(n) for reasonably efficient algorithms. That is still O(n) too much if you are concerned with performance and can deallocate in constant time without garbage collection.)
Personally, when I hear people say that C++ doesn't have garbage collection, my mind tags that as a feature of C++, but I'm probably in the minority. Probably the hardest thing for people to learn about programming in C and C++ are pointers and how to correctly handle their dynamic memory allocations. Some other languages, like Python, would be horrible without GC, so I think it comes down to what you want out of a language. If you want dependable performance, then C++ without garbage collection is the only thing this side of Fortran that I can think of. If you want ease of use and training wheels (to save you from crashing without requiring that you learn "proper" memory management), pick something with a GC. Even if you know how to manage memory well, it will save you time which you can spend optimizing other code. There really isn't much of a performance penalty anymore, but if you really need dependable performance (and the ability to know exactly what is going on, when, under the covers) then I'd stick with C++. There is a reason that every major game engine that I've ever heard of is in C++ (if not C or assembly). Python, et al are fine for scripting, but not the main game engine.
You can mimic es6 classes behaviour... and use your class variables :)
Look mum... no classes!
// Helper
const $constructor = Symbol();
const $extends = (parent, child) =>
Object.assign(Object.create(parent), child);
const $new = (object, ...args) => {
let instance = Object.create(object);
instance[$constructor].call(instance, ...args);
return instance;
}
const $super = (parent, context, ...args) => {
parent[$constructor].call(context, ...args)
}
// class
var Foo = {
classVariable: true,
// constructor
[$constructor](who){
this.me = who;
this.species = 'fufel';
},
// methods
identify(){
return 'I am ' + this.me;
}
}
// class extends Foo
var Bar = $extends(Foo, {
// constructor
[$constructor](who){
$super(Foo, this, who);
this.subtype = 'barashek';
},
// methods
speak(){
console.log('Hello, ' + this.identify());
},
bark(num){
console.log('Woof');
}
});
var a1 = $new(Foo, 'a1');
var b1 = $new(Bar, 'b1');
console.log(a1, b1);
console.log('b1.classVariable', b1.classVariable);
I put it on GitHub
As an add-on to the answers below, when using INT or non-decimal datatypes in your formulas, remember to multiply the value by 1 and the number of decimals you prefer.
i.e. - TotalPackages
is an INT
and so the denominator TotalContainers
, but I want my result to have up to 6 decimal places.
thus:
((m.TotalPackages * 1.000000) / m.TotalContainers) AS Packages,
SELECT *
FROM Product_sales
WHERE (
From_date >= '2013-08-19'
AND To_date <= '2013-08-23'
)
OR (
To_date >= '2013-08-19'
AND From_date <= '2013-08-23'
)
Putting the call to mysql_insert_id()
inside a transaction, should do it:
mysql_query('BEGIN');
// Whatever code that does the insert here.
$id = mysql_insert_id();
mysql_query('COMMIT');
// Stuff with $id.
Print the Upper and Lower case alphabets in python using a built-in range function
def upperCaseAlphabets():
print("Upper Case Alphabets")
for i in range(65, 91):
print(chr(i), end=" ")
print()
def lowerCaseAlphabets():
print("Lower Case Alphabets")
for i in range(97, 123):
print(chr(i), end=" ")
upperCaseAlphabets();
lowerCaseAlphabets();
ASP.NET 2 and SQL Server reporting services 2005 have a limit of 2028. I found this out the hard way, where my dynamic URL generator would not pass over some parameters to a report beyond that point. This was under Internet Explorer 8.