Here's an example using http://www.geoplugin.net/json.gp
$ip = $_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip={$ip}"));
echo $details;
If the class file you want to look into is open source, you should not decompile it, but instead attach the source files directly into your IDE. that way, you can just view the code of some library class as if it were your own
Try like this, it worked for me
<root>
<!--<level value="ALL" />-->
<level value="ERROR" />
<level value="INFO" />
<level value="WARN" />
</root>
This logs 3 types of errors - error, info, and warning
There is no need for all this mess.
You can make the navbar transparent by not writing
navbar-default
ornavbar-inverse
<nav class="navbar"> //Don't add navbar-default to the class
//
</nav>
Try this (It is for Indian mobile number validation):
if (!phoneNumber.matches("^[6-9]\\d{9}$")) {
return false;
} else {
return true;
}
In Python 2.x, just use the ord
and chr
functions:
>>> ord('c')
99
>>> ord('c') + 1
100
>>> chr(ord('c') + 1)
'd'
>>>
Python 3.x makes this more organized and interesting, due to its clear distinction between bytes and unicode. By default, a "string" is unicode, so the above works (ord
receives Unicode chars and chr
produces them).
But if you're interested in bytes (such as for processing some binary data stream), things are even simpler:
>>> bstr = bytes('abc', 'utf-8')
>>> bstr
b'abc'
>>> bstr[0]
97
>>> bytes([97, 98, 99])
b'abc'
>>> bytes([bstr[0] + 1, 98, 99])
b'bbc'
There were no real associative arrays in Javascript until 2015 (release of ECMAScript 6). Since then you can use the Map object as Robocat states. Look up the details in MDN. Example:
let map = new Map();
map.set('key', {'value1', 'value2'});
let values = map.get('key');
Without support for ES6 you can try using objects:
var x = new Object();
x["Key"] = "Value";
However with objects it is not possible to use typical array properties or methods like array.length. At least it is possible to access the "object-array" in a for-in-loop.
If you need to update user information for a specific user ID "x",
The ViewModel will initialize an instance of dbManager to access the database. The code should look like this:
@Entity
class User{
@PrimaryKey
String userId;
String username;
}
Interface UserDao{
//forUpdate
@Update
void updateUser(User user)
}
Class DbManager{
//AppDatabase gets the static object o roomDatabase.
AppDatabase appDatabase;
UserDao userDao;
public DbManager(Application application ){
appDatabase = AppDatabase.getInstance(application);
//getUserDao is and abstract method of type UserDao declared in AppDatabase //class
userDao = appDatabase.getUserDao();
}
public void updateUser(User user, boolean isUpdate){
new InsertUpdateUserAsyncTask(userDao,isUpdate).execute(user);
}
public static class InsertUpdateUserAsyncTask extends AsyncTask<User, Void, Void> {
private UserDao userDAO;
private boolean isInsert;
public InsertUpdateBrandAsyncTask(BrandDAO userDAO, boolean isInsert) {
this. userDAO = userDAO;
this.isInsert = isInsert;
}
@Override
protected Void doInBackground(User... users) {
if (isInsert)
userDAO.insertBrand(brandEntities[0]);
else
//for update
userDAO.updateBrand(users[0]);
//try {
// Thread.sleep(1000);
//} catch (InterruptedException e) {
// e.printStackTrace();
//}
return null;
}
}
}
Class UserViewModel{
DbManager dbManager;
public UserViewModel(Application application){
dbmanager = new DbMnager(application);
}
public void updateUser(User user, boolean isUpdate){
dbmanager.updateUser(user,isUpdate);
}
}
Now in your activity or fragment initialise your UserViewModel like this:
UserViewModel userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
Then just update your user item this way, suppose your userId is 1122 and userName is "xyz" which has to be changed to "zyx".
Get an userItem of id 1122 User object
User user = new user(); if(user.getUserId() == 1122){ user.setuserName("zyx"); userViewModel.updateUser(user); }
This is a raw code, hope it helps you.
Happy coding
You need to link both a.o
and b.o
:
gcc -o program a.c b.c
If you have a main()
in each file, you cannot link them together.
However, your a.c
file contains a reference to doSomething()
and expects to be linked with a source file that defines doSomething()
and does not define any function that is defined in a.c
(such as main()
).
You cannot call a function in Process B from Process A. You cannot send a signal to a function; you send signals to processes, using the kill()
system call.
The signal()
function specifies which function in your current process (program) is going to handle the signal when your process receives the signal.
You have some serious work to do understanding how this is going to work - how ProgramA is going to know which process ID to send the signal to. The code in b.c
is going to need to call signal()
with dosomething
as the signal handler. The code in a.c
is simply going to send the signal to the other process.
Check the pointer for NULL
and then using strlen
to see if it returns 0
.
NULL
check is important because passing NULL
pointer to strlen
invokes an Undefined Behavior.
If the following conditions are true, then rewrite the URL:
If the requested filename is not a directory,
RewriteCond %{REQUEST_FILENAME} !-d
and if the requested filename is not a regular file that exists,
RewriteCond %{REQUEST_FILENAME} !-f
and if the requested filename is not a symbolic link,
RewriteCond %{REQUEST_FILENAME} !-l
then rewrite the URL in the following way:
Take the whole request filename and provide it as the value of a "url" query parameter to index.php. Append any query string from the original URL as further query parameters (QSA), and stop processing this .htaccess file (L).
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
Another Example:
RewriteRule "/pages/(.+)" "/page.php?page=$1" [QSA]
With the [QSA] flag, a request for
/pages/123?one=two
will be mapped to
/page.php?page=123&one=two
For reading/writing excel files, you can use :
readxl
package for reading and writexl
package for writingopenxlsx
package for reading and writingWith xlsx
and XLConnect
(which use rjava) you will face memory errors if you have large files
<script>_x000D_
_$ = document.querySelector .bind(document) ;_x000D_
_x000D_
var AppendLinkHere = _$("body") // <- put in here some CSS selector that'll be more to your needs_x000D_
var a = document.createElement( 'a' )_x000D_
a.text = "Download example" _x000D_
a.href = "//bit\.do/DeezerDL"_x000D_
_x000D_
AppendLinkHere.appendChild( a )_x000D_
_x000D_
_x000D_
// a.title = 'Well well ... _x000D_
a.setAttribute( 'title', _x000D_
'Well well that\'s a link'_x000D_
);_x000D_
</script>
_x000D_
The 'Anchor Object' has its own*(inherited)* properties for setting the link, its text. So just use them. .setAttribute is more general but you normally don't need it. a.title ="Blah"
will do the same and is more clear!
Well a situation that'll demand .setAttribute is this: var myAttrib = "title"; a.setAttribute( myAttrib , "Blah")
Leave the protocol open. Instead of http://example.com/path consider to just use //example.com/path. Check if example.com can be accessed by http: as well as https: but 95 % of sites will work on both.
OffTopic: That's not really relevant about creating links in JS
but maybe good to know:
Well sometimes like in the chromes dev-console you can use $("body")
instead of document.querySelector("body")
A _$ = document.querySelector
will 'honor' your efforts with an Illegal invocation error the first time you use it. That's because the assignment just 'grabs' .querySelector (a ref to the class method). With .bind(...
you'll also involve the context (here it's document
) and you get an object method that'll work as you might expect it.
Assuming your file is named "myfile.ext"
If the file you're trying to load is not an R-script, for which you would use
source("myfile.ext")
you might try the readRDS
function and assign it to a variable-name:
my.data <- readRDS("myfile.ext")
The universal tool for string formatting, sprintf
:
$stamp = sprintf('%s%02s', $year, $month);
If you want to uncheck the checkbox that you have selected first under the condition of 3 checkboxes allowed. With vanilla javascript; you need to assign onclick = "checking(this)" in your html input checkbox
var queue = [];
function checking(id){
queue.push(id)
if (queue.length===3){
queue[0].checked = false
queue.shift()
}
}
Strip won't work. It only removes leading and trailing instances, not everything in between: http://docs.python.org/2/library/stdtypes.html#str.strip
Having fun with filter:
import string
asking = "hello! what's your name?"
predicate = lambda x:x not in string.punctuation
filter(predicate, asking)
The best solution in C#/all static .NET languages is to use the CodeDOM for such things. (As a note, its other main purpose is for dynamically constructing bits of code, or even whole classes.)
Here's a nice short example take from LukeH's blog, which uses some LINQ too just for fun.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
class Program
{
static void Main(string[] args)
{
var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true);
parameters.GenerateExecutable = true;
CompilerResults results = csc.CompileAssemblyFromSource(parameters,
@"using System.Linq;
class Program {
public static void Main(string[] args) {
var q = from i in Enumerable.Range(1,100)
where i % 2 == 0
select i;
}
}");
results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
}
}
The class of primary importance here is the CSharpCodeProvider
which utilises the compiler to compile code on the fly. If you want to then run the code, you just need to use a bit of reflection to dynamically load the assembly and execute it.
Here is another example in C# that (although slightly less concise) additionally shows you precisely how to run the runtime-compiled code using the System.Reflection
namespace.
What you describe is the default behavior. You have to detect and handle these events yourself by adding:
android:configChanges
to your manifest and then the changes that you want to handle. So for orientation, you would use:
android:configChanges="orientation"
and for the keyboard being opened or closed you would use:
android:configChanges="keyboardHidden"
If you want to handle both you can just separate them with the pipe command like:
android:configChanges="keyboardHidden|orientation"
This will trigger the onConfigurationChanged method in whatever Activity you call. If you override the method you can pass in the new values.
Hope this helps.
The disapproval of tail
here based on speed alone doesn't really seem to emphasize that part of the slower speed comes from the fact that tail is safer to work with, if you don't for sure that the length of x will exceed n
, the number of elements you want to subset out:
x <- 1:10
tail(x, 20)
# [1] 1 2 3 4 5 6 7 8 9 10
x[length(x) - (0:19)]
#Error in x[length(x) - (0:19)] :
# only 0's may be mixed with negative subscripts
Tail will simply return the max number of elements instead of generating an error, so you don't need to do any error checking yourself. A great reason to use it. Safer cleaner code, if extra microseconds/milliseconds don't matter much to you in its use.
I like this example:
<asp:FileUpload ID="fpImages" runat="server" title="maximum file size 1 MB or less" onChange="return validateFileExtension(this)" />
<script language="javascript" type="text/javascript">
function ValidateFileUpload(Source, args) {
var fuData = document.getElementById('<%= fpImages.ClientID %>');
var FileUploadPath = fuData.value;
if (FileUploadPath == '') {
// There is no file selected
args.IsValid = false;
}
else {
var Extension = FileUploadPath.substring(FileUploadPath.lastIndexOf('.') + 1).toLowerCase();
if (Extension == "gif" || Extension == "png" || Extension == "bmp" || Extension == "jpeg") {
args.IsValid = true; // Valid file type
FileUploadPath == '';
}
else {
args.IsValid = false; // Not valid file type
}
}
}
</script>
From @Erik Hunter, I post full code for make horizontal UICollectionView
UICollectionViewFlowLayout *collectionViewFlowLayout = [[UICollectionViewFlowLayout alloc] init];
[collectionViewFlowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
self.myCollectionView.collectionViewLayout = collectionViewFlowLayout;
In Swift
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .Horizontal
self.myCollectionView.collectionViewLayout = layout
In Swift 3.0
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
self.myCollectionView.collectionViewLayout = layout
Hope this help
Gimp can be used to convert SVGs with primitives (e.g. rects, circles, etc.) into a single path which can be used within HTML5.
.svg
file with any tool of choice e.g. Illustrator. Don't worry if the SVG output is messy for now, Gimp will clean it upCheck both the Import Paths and Merge imported paths options
<path d="copy this text here" />
If you want all the bars to get the same color (fill
), you can easily add it inside geom_bar
.
ggplot(data=df, aes(x=c1+c2/2, y=c3)) +
geom_bar(stat="identity", width=c2, fill = "#FF6666")
Add fill = the_name_of_your_var
inside aes
to change the colors depending of the variable :
c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2)
Use scale_fill_manual()
if you want to manually the change of colors.
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2) +
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))
Try this ,
Calendar beginTime = Calendar.getInstance();
beginTime.set(yearInt, monthInt - 1, dayInt, 7, 30);
ContentValues l_event = new ContentValues();
l_event.put("calendar_id", CalIds[0]);
l_event.put("title", "event");
l_event.put("description", "This is test event");
l_event.put("eventLocation", "School");
l_event.put("dtstart", beginTime.getTimeInMillis());
l_event.put("dtend", beginTime.getTimeInMillis());
l_event.put("allDay", 0);
l_event.put("rrule", "FREQ=YEARLY");
// status: 0~ tentative; 1~ confirmed; 2~ canceled
// l_event.put("eventStatus", 1);
l_event.put("eventTimezone", "India");
Uri l_eventUri;
if (Build.VERSION.SDK_INT >= 8) {
l_eventUri = Uri.parse("content://com.android.calendar/events");
} else {
l_eventUri = Uri.parse("content://calendar/events");
}
Uri l_uri = MainActivity.this.getContentResolver()
.insert(l_eventUri, l_event);
Try this script to get your browser language
<script type="text/javascript">_x000D_
var userLang = navigator.language || navigator.userLanguage; _x000D_
alert ("The language is: " + userLang);_x000D_
</script>
_x000D_
Cheers
pygame
is not distributed via pip
. See this link which provides windows binaries ready for installation.
Finally, use these commands to install pygame wheel with pip
Python 2 (usually called pip)
pip install file.whl
Python 3 (usually called pip3)
pip3 install file.whl
Another tutorial for installing pygame for windows can be found here. Although the instructions are for 64bit windows, it can still be applied to 32bit
Try XmlSerialization
try this
[Serializable]
public class Task
{
public string Name{get; set;}
public string Location {get; set;}
public string Arguments {get; set;}
public DateTime RunWhen {get; set;}
}
public void WriteXMl(Task task)
{
XmlSerializer serializer;
serializer = new XmlSerializer(typeof(Task));
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream, Encoding.Unicode);
serializer.Serialize(writer, task);
int count = (int)stream.Length;
byte[] arr = new byte[count];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(arr, 0, count);
using (BinaryWriter binWriter=new BinaryWriter(File.Open(@"C:\Temp\Task.xml", FileMode.Create)))
{
binWriter.Write(arr);
}
}
public Task GetTask()
{
StreamReader stream = new StreamReader(@"C:\Temp\Task.xml", Encoding.Unicode);
return (Task)serializer.Deserialize(stream);
}
public static void notifyUser(Activity activity, String header,
String message) {
NotificationManager notificationManager = (NotificationManager) activity
.getSystemService(Activity.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(
activity.getApplicationContext(), YourActivityToLaunch.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(activity);
stackBuilder.addParentStack(YourActivityToLaunch.class);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent pIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(activity)
.setContentTitle(header)
.setContentText(message)
.setDefaults(
Notification.DEFAULT_SOUND
| Notification.DEFAULT_VIBRATE)
.setContentIntent(pIntent).setAutoCancel(true)
.setSmallIcon(drawable.notification_icon).build();
notificationManager.notify(2, notification);
}
public bool MojTestPalindrome (string word)
{
bool yes = false;
char[]test1 = word.ToArray();
char[] test2 = test1.Reverse().ToArray();
for (int i=0; i< test2.Length; i++)
{
if (test1[i] != test2[test2.Length - 1 - i])
{
yes = false;
break;
}
else {
yes = true;
}
}
if (yes == true)
{
return true;
}
else
return false;
}
When loading the Properties from a Class in the package com.al.common.email.templates
you can use
Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream("foo.properties");
prop.load(in);
in.close();
(Add all the necessary exception handling).
If your class is not in that package, you need to aquire the InputStream slightly differently:
InputStream in =
getClass().getResourceAsStream("/com/al/common/email/templates/foo.properties");
Relative paths (those without a leading '/') in getResource()
/getResourceAsStream()
mean that the resource will be searched relative to the directory which represents the package the class is in.
Using java.lang.String.class.getResource("foo.txt")
would search for the (inexistent) file /java/lang/String/foo.txt
on the classpath.
Using an absolute path (one that starts with '/') means that the current package is ignored.
You Can also set the background color to Clear to achieve the same effect as UITableViewCellSelectionStyleNone
, in case you don't want to/ can't use UITableViewCellSelectionStyleNone
.
You would use code like the following:
UIView *backgroundColorView = [[UIView alloc] init];
backgroundColorView.backgroundColor = [UIColor clearColor];
backgroundColorView.layer.masksToBounds = YES;
[cell setSelectedBackgroundView: backgroundColorView];
This may degrade your performance as your adding an extra colored view to each cell.
You can use the following command:
zip -r nameoffile.zip directory
Hope this helps.
in place
>>> l = [[0, 1, 'f'], [4, 2, 't'], [9, 4, 'afsd']]
>>> l.sort(key=lambda x: x[2])
not in place using sorted:
>>> sorted(l, key=lambda x: x[2])
A simple solution for selecting 5
random files while avoiding to parse ls. It also works with files containing spaces, newlines and other special characters:
shuf -ezn 5 * | xargs -0 -n1 echo
Replace echo
with the command you want to execute for your files.
I tried to resolve with the suggested answer and still ran into some issues...
This was a solution to my problem:
ARG APP_EXE="AppName.exe"
ENV _EXE=${APP_EXE}
# Build a shell script because the ENTRYPOINT command doesn't like using ENV
RUN echo "#!/bin/bash \n mono ${_EXE}" > ./entrypoint.sh
RUN chmod +x ./entrypoint.sh
# Run the generated shell script.
ENTRYPOINT ["./entrypoint.sh"]
Specifically targeting your problem:
RUN echo "#!/bin/bash \n ./greeting --message ${ADDRESSEE}" > ./entrypoint.sh
RUN chmod +x ./entrypoint.sh
ENTRYPOINT ["./entrypoint.sh"]
I faced a similar issue when running SSH or Git Clone in Windows. Following findings helps to solve my problem:
Also, I think there a way to “tell” git to use the default .ssh folder in home folder but still need to figure out how.
As a lighter alternative to the existing answers, you can set the build result with a simple HTTP POST to access the Groovy script console REST API:
curl -X POST \
--silent \
--user "$YOUR_CREDENTIALS" \
--data-urlencode "script=Jenkins.instance.getItemByFullName( '$JOB_NAME' ).getBuildByNumber( $BUILD_NUMBER ).setResult( hudson.model.Result.UNSTABLE )" $JENKINS_URL/scriptText
Advantages:
For this solution, your environment must meet these conditions:
Compiler shows following error :
Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: 'Storyboard (<UIStoryboard: 0x7fedf2d5c9a0>) doesn't contain a
ViewController with identifier 'SBAddEmployeeVC''
Here the object of the storyboard created is not the main storyboard which contains our ViewControllers. As storyboard file on which we work is named as Main.storyboard. So we need to have reference of object of the Main.storyboard.
Use following code for that :
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
Here storyboardWithName
is the name of the storyboard file we are working with and bundle
specifies the bundle in which our storyboard is (i.e. mainBundle
).
Short and sweet, no additional modules needed:
my $toDate = `date +%m/%d/%Y" "%l:%M:%S" "%p`;
Output for example would be: 04/25/2017 9:30:33 AM
Go to terminal and type android avd
. Select your AVD and select "Edit". Make sure you do not see No CPU/ABI system image available for this target
- it will show in red font at the bottom. Change the target
to the one that is available or download the ABI image. Sometimes, if you create an AVD from inside Android Studio, it does not ensure this requirement.
Here is a complete example. Right click on the solution to manage nuget packages and get Newtonsoft and RestSharp:
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
namespace TestAPI
{
class Program
{
static void Main(string[] args)
{
String id = "xxx";
String secret = "xxx";
var client = new RestClient("https://xxx.xxx.com/services/api/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&scope=all&client_id=" + id + "&client_secret=" + secret, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
dynamic resp = JObject.Parse(response.Content);
String token = resp.access_token;
client = new RestClient("https://xxx.xxx.com/services/api/x/users/v1/employees");
request = new RestRequest(Method.GET);
request.AddHeader("authorization", "Bearer " + token);
request.AddHeader("cache-control", "no-cache");
response = client.Execute(request);
}
}
}
I was unable to get @Factor Mystic's answer to work with POSIX regular expressions, so I wrote one that works with POSIX regular expressions and PERL regular expressions.
It should match:
IPv6 Regular Expression:
(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))
For ease of reading, the following is the above regular expression split at major OR points into separate lines:
# IPv6 RegEx
(
([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}| # 1:2:3:4:5:6:7:8
([0-9a-fA-F]{1,4}:){1,7}:| # 1:: 1:2:3:4:5:6:7::
([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}| # 1::8 1:2:3:4:5:6::8 1:2:3:4:5:6::8
([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}| # 1::7:8 1:2:3:4:5::7:8 1:2:3:4:5::8
([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}| # 1::6:7:8 1:2:3:4::6:7:8 1:2:3:4::8
([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}| # 1::5:6:7:8 1:2:3::5:6:7:8 1:2:3::8
([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}| # 1::4:5:6:7:8 1:2::4:5:6:7:8 1:2::8
[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})| # 1::3:4:5:6:7:8 1::3:4:5:6:7:8 1::8
:((:[0-9a-fA-F]{1,4}){1,7}|:)| # ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::
fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}| # fe80::7:8%eth0 fe80::7:8%1 (link-local IPv6 addresses with zone index)
::(ffff(:0{1,4}){0,1}:){0,1}
((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}
(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])| # ::255.255.255.255 ::ffff:255.255.255.255 ::ffff:0:255.255.255.255 (IPv4-mapped IPv6 addresses and IPv4-translated addresses)
([0-9a-fA-F]{1,4}:){1,4}:
((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}
(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]) # 2001:db8:3:4::192.0.2.33 64:ff9b::192.0.2.33 (IPv4-Embedded IPv6 Address)
)
# IPv4 RegEx
((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])
To make the above easier to understand, the following "pseudo" code replicates the above:
IPV4SEG = (25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])
IPV4ADDR = (IPV4SEG\.){3,3}IPV4SEG
IPV6SEG = [0-9a-fA-F]{1,4}
IPV6ADDR = (
(IPV6SEG:){7,7}IPV6SEG| # 1:2:3:4:5:6:7:8
(IPV6SEG:){1,7}:| # 1:: 1:2:3:4:5:6:7::
(IPV6SEG:){1,6}:IPV6SEG| # 1::8 1:2:3:4:5:6::8 1:2:3:4:5:6::8
(IPV6SEG:){1,5}(:IPV6SEG){1,2}| # 1::7:8 1:2:3:4:5::7:8 1:2:3:4:5::8
(IPV6SEG:){1,4}(:IPV6SEG){1,3}| # 1::6:7:8 1:2:3:4::6:7:8 1:2:3:4::8
(IPV6SEG:){1,3}(:IPV6SEG){1,4}| # 1::5:6:7:8 1:2:3::5:6:7:8 1:2:3::8
(IPV6SEG:){1,2}(:IPV6SEG){1,5}| # 1::4:5:6:7:8 1:2::4:5:6:7:8 1:2::8
IPV6SEG:((:IPV6SEG){1,6})| # 1::3:4:5:6:7:8 1::3:4:5:6:7:8 1::8
:((:IPV6SEG){1,7}|:)| # ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::
fe80:(:IPV6SEG){0,4}%[0-9a-zA-Z]{1,}| # fe80::7:8%eth0 fe80::7:8%1 (link-local IPv6 addresses with zone index)
::(ffff(:0{1,4}){0,1}:){0,1}IPV4ADDR| # ::255.255.255.255 ::ffff:255.255.255.255 ::ffff:0:255.255.255.255 (IPv4-mapped IPv6 addresses and IPv4-translated addresses)
(IPV6SEG:){1,4}:IPV4ADDR # 2001:db8:3:4::192.0.2.33 64:ff9b::192.0.2.33 (IPv4-Embedded IPv6 Address)
)
I posted a script on GitHub which tests the regular expression: https://gist.github.com/syzdek/6086792
I've coded up a simple example for you and annotated the source. The example shows how to grab live json and parse into a JSONObject
for detail extraction:
try{
// Create a new HTTP Client
DefaultHttpClient defaultClient = new DefaultHttpClient();
// Setup the get request
HttpGet httpGetRequest = new HttpGet("http://example.json");
// Execute the request in the client
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
// Grab the response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
// Instantiate a JSON object from the request response
JSONObject jsonObject = new JSONObject(json);
} catch(Exception e){
// In your production code handle any errors and catch the individual exceptions
e.printStackTrace();
}
Once you have your JSONObject
refer to the SDK for details on how to extract the data you require.
DISCLAIMER: The below solution does not preserve trailing tabs.
If you know the exact number of lines in the text file, try the following method:
@ECHO OFF
SET origfile=original file
SET tempfile=temporary file
SET insertbefore=4
SET totallines=200
<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
SETLOCAL EnableDelayedExpansion
SET /P L=
IF %%i==%insertbefore% ECHO(
ECHO(!L!
ENDLOCAL
)
) >%tempfile%
COPY /Y %tempfile% %origfile% >NUL
DEL %tempfile%
The loop reads lines from the original file one by one and outputs them. The output is redirected to a temporary file. When a certain line is reached, an empty line is output before it.
After finishing, the original file is deleted and the temporary one gets assigned the original name.
UPDATE
If the number of lines is unknown beforehand, you can use the following method to obtain it:
FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C
(This line simply replaces the SET totallines=200
line in the above script.)
The method has one tiny flaw: if the file ends with an empty line, the result will be the actual number of lines minus one. If you need a workaround (or just want to play safe), you can use the method described in this answer.
no need to uninstall & then re-install sklearn
try this:
from sklearn.model_selection import train_test_split
That’s a typo. You’ve accidently set user.mail
with no e. Fix it by setting user.email
in the global configuration with
git config --global user.email "[email protected]"
Rather than:
first_element = myList[i[0]]
You probably want:
first_element = myList[i][0]
What is Angular CLI Budgets? Budgets is one of the less known features of the Angular CLI. It’s a rather small but a very neat feature!
As applications grow in functionality, they also grow in size. Budgets is a feature in the Angular CLI which allows you to set budget thresholds in your configuration to ensure parts of your application stay within boundaries which you set — Official Documentation
Or in other words, we can describe our Angular application as a set of compiled JavaScript files called bundles which are produced by the build process. Angular budgets allows us to configure expected sizes of these bundles. More so, we can configure thresholds for conditions when we want to receive a warning or even fail build with an error if the bundle size gets too out of control!
How To Define A Budget? Angular budgets are defined in the angular.json file. Budgets are defined per project which makes sense because every app in a workspace has different needs.
Thinking pragmatically, it only makes sense to define budgets for the production builds. Prod build creates bundles with “true size” after applying all optimizations like tree-shaking and code minimization.
Oops, a build error! The maximum bundle size was exceeded. This is a great signal that tells us that something went wrong…
First Approach: Are your files gzipped?
Generally speaking, gzipped file has only about 20% the size of the original file, which can drastically decrease the initial load time of your app. To check if you have gzipped your files, just open the network tab of developer console. In the “Response Headers”, if you should see “Content-Encoding: gzip”, you are good to go.
How to gzip? If you host your Angular app in most of the cloud platforms or CDN, you should not worry about this issue as they probably have handled this for you. However, if you have your own server (such as NodeJS + expressJS) serving your Angular app, definitely check if the files are gzipped. The following is an example to gzip your static assets in a NodeJS + expressJS app. You can hardly imagine this dead simple middleware “compression” would reduce your bundle size from 2.21MB to 495.13KB.
const compression = require('compression')
const express = require('express')
const app = express()
app.use(compression())
Second Approach:: Analyze your Angular bundle
If your bundle size does get too big you may want to analyze your bundle because you may have used an inappropriate large-sized third party package or you forgot to remove some package if you are not using it anymore. Webpack has an amazing feature to give us a visual idea of the composition of a webpack bundle.
It’s super easy to get this graph.
npm install -g webpack-bundle-analyzer
ng build --stats-json
(don’t use flag --prod
). By enabling --stats-json
you will get an additional file stats.jsonwebpack-bundle-analyzer ./dist/stats.json
and your browser will pop up the page at localhost:8888. Have fun with it.ref 1: How Did Angular CLI Budgets Save My Day And How They Can Save Yours
This Add-on will do the trick for you.
http://www.contextures.com/xlPivotPlayPlus01.html
It shows the connection string, and allows it to be changed. Don't forget to change the Query SQL as well, if needed (with the same tool).
You do like this. the function return the old text.
$('button').click(function(){
$(this).text(function(i,old){
return old=='Read More' ? 'Read Less' : 'Read More';
});
});
Use .form-inline = This will left-align labels and inline-block controls for a compact layout
Example: http://jsfiddle.net/hSuy4/292/
<div class="form-inline">
<input type="text">
<input type="button" class="btn" value="submit">
</div>
.form-horizontal = Right align labels and float them to the left to make them appear on the same line as controls which is better for 2 column form layout.
(e.g.
Label 1: [textbox]
Label 2: [textbox]
: [button]
)
Examples: http://twitter.github.io/bootstrap/base-css.html#forms
I found this method worked for me:
$thisproduct = "my_product_id";
$array=array("$product1", "$product2", "$product3", "$product4");
if (in_array($thisproduct,$array)) {
echo "Product found";
}
PHP refresh current page
With PHP code:
<?php
$secondsWait = 1;
header("Refresh:$secondsWait");
echo date('Y-m-d H:i:s');
?>
Note: Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.
if you send any output, you can use javascript:
<?php
echo date('Y-m-d H:i:s');
echo '<script type="text/javascript">location.reload(true);</script>';
?>
When this method receives a true value as argument, it will cause the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.
Or you can explicitly use "meta refresh" (with pure html):
<?php
$secondsWait = 1;
echo date('Y-m-d H:i:s');
echo '<meta http-equiv="refresh" content="'.$secondsWait.'">';
?>
Greetings and good code,
What about constructing the element using jQuery? e.g.
$("<div></div>")
creates a new div element, ready to be added to the page. Can be shortened further to
$("<div>")
then you can chain on commands that you need, set up event handlers and append it to the DOM. For example
$('<div id="myid">Div Content</div>')
.bind('click', function(e) { /* event handler here */ })
.appendTo('#myOtherDiv');
How about
SELECT user()
I use this before.MySQL, H2 is OK, I don't know others.
Without explicitly defining the height
I determined I need to apply the flex
value to the parent and grandparent div
elements...
<div style="display: flex;">
<div style="display: flex;">
<img alt="No, he'll be an engineer." src="theknack.png" style="margin: auto;" />
</div>
</div>
If you're using a single element (e.g. dead-centered text in a single flex
element) use the following:
align-items: center;
display: flex;
justify-content: center;
If you have a flash FLA file that shows the FLV movie you can add a button inside the FLA file. This button can be given an action to load the URL.
on (release) {
getURL("http://someurl/");
}
To make the button transparent you can place a square inside it that is moved to the hit-area frame of the button.
I think it would go too far to explain into depth with pictures how to go about in stackoverflow.
Essentially you have to have admin rights (directly or indirectly) to the repository to do this. You can either configure the repository to allow all users to do this, or you can modify the log message directly on the server.
See this part of the Subversion FAQ (emphasis mine):
Log messages are kept in the repository as properties attached to each revision. By default, the log message property (svn:log) cannot be edited once it is committed. That is because changes to revision properties (of which svn:log is one) cause the property's previous value to be permanently discarded, and Subversion tries to prevent you from doing this accidentally. However, there are a couple of ways to get Subversion to change a revision property.
The first way is for the repository administrator to enable revision property modifications. This is done by creating a hook called "pre-revprop-change" (see this section in the Subversion book for more details about how to do this). The "pre-revprop-change" hook has access to the old log message before it is changed, so it can preserve it in some way (for example, by sending an email). Once revision property modifications are enabled, you can change a revision's log message by passing the --revprop switch to svn propedit or svn propset, like either one of these:
$svn propedit -r N --revprop svn:log URL $svn propset -r N --revprop svn:log "new log message" URL
where N is the revision number whose log message you wish to change, and URL is the location of the repository. If you run this command from within a working copy, you can leave off the URL.
The second way of changing a log message is to use svnadmin setlog. This must be done by referring to the repository's location on the filesystem. You cannot modify a remote repository using this command.
$ svnadmin setlog REPOS_PATH -r N FILE
where REPOS_PATH is the repository location, N is the revision number whose log message you wish to change, and FILE is a file containing the new log message. If the "pre-revprop-change" hook is not in place (or you want to bypass the hook script for some reason), you can also use the --bypass-hooks option. However, if you decide to use this option, be very careful. You may be bypassing such things as email notifications of the change, or backup systems that keep track of revision properties.
To make up for the daylight saving time (starting on March's last sunday until October's last sunday) I had to use the following formula:
=IF(
AND(
A2>=EOMONTH(DATE(YEAR(A2);3;1);0)-MOD(WEEKDAY(EOMONTH(DATE(YEAR(A2);3;1);0);11);7);
A2<=EOMONTH(DATE(YEAR(A2);10;1);0)-MOD(WEEKDAY(EOMONTH(DATE(YEAR(A2);10;1);0);11);7)
);
(A2-DATE(1970;1;1)-TIME(1;0;0))*24*60*60*1000;
(A2-DATE(1970;1;1))*24*60*60*1000
)
Quick explanation:
If the date ["A2"] is between March's last sunday and October's last sunday [third and fourth code lines], then I'll be subtracting one hour [-TIME(1;0;0)] to the date.
`CREATE TRIGGER `category_before_ins_tr` BEFORE INSERT ON `category`
FOR EACH ROW
BEGIN
**SET @tableId= (SELECT id FROM dummy LIMIT 1);**
END;`;
Per zanco's answer, you're not providing a remote command to ssh
, given how the shell parses the command line. To solve this problem, change the syntax of your ssh
command invocation so that the remote command is comprised of a syntactically correct, multi-line string.
There are a variety of syntaxes that can be used. For example, since commands can be piped into bash
and sh
, and probably other shells too, the simplest solution is to just combine ssh
shell invocation with heredocs:
ssh user@server /bin/bash <<'EOT'
echo "These commands will be run on: $( uname -a )"
echo "They are executed by: $( whoami )"
EOT
Note that executing the above without /bin/bash
will result in the warning Pseudo-terminal will not be allocated because stdin is not a terminal
. Also note that EOT
is surrounded by single-quotes, so that bash
recognizes the heredoc as a nowdoc, turning off local variable interpolation so that the command text will be passed as-is to ssh
.
If you are a fan of pipes, you can rewrite the above as follows:
cat <<'EOT' | ssh user@server /bin/bash
echo "These commands will be run on: $( uname -a )"
echo "They are executed by: $( whoami )"
EOT
The same caveat about /bin/bash
applies to the above.
Another valid approach is to pass the multi-line remote command as a single string, using multiple layers of bash
variable interpolation as follows:
ssh user@server "$( cat <<'EOT'
echo "These commands will be run on: $( uname -a )"
echo "They are executed by: $( whoami )"
EOT
)"
The solution above fixes this problem in the following manner:
ssh user@server
is parsed by bash, and is interpreted to be the ssh
command, followed by an argument user@server
to be passed to the ssh
command
"
begins an interpolated string, which when completed, will comprise an argument to be passed to the ssh
command, which in this case will be interpreted by ssh
to be the remote command to execute as user@server
$(
begins a command to be executed, with the output being captured by the surrounding interpolated string
cat
is a command to output the contents of whatever file follows. The output of cat
will be passed back into the capturing interpolated string
<<
begins a bash heredoc
'EOT'
specifies that the name of the heredoc is EOT. The single quotes '
surrounding EOT specifies that the heredoc should be parsed as a nowdoc, which is a special form of heredoc in which the contents do not get interpolated by bash, but rather passed on in literal format
Any content that is encountered between <<'EOT'
and <newline>EOT<newline>
will be appended to the nowdoc output
EOT
terminates the nowdoc, resulting in a nowdoc temporary file being created and passed back to the calling cat
command. cat
outputs the nowdoc and passes the output back to the capturing interpolated string
)
concludes the command to be executed
"
concludes the capturing interpolated string. The contents of the interpolated string will be passed back to ssh
as a single command line argument, which ssh
will interpret as the remote command to execute as user@server
If you need to avoid using external tools like cat
, and don't mind having two statements instead of one, use the read
built-in with a heredoc to generate the SSH command:
IFS='' read -r -d '' SSH_COMMAND <<'EOT'
echo "These commands will be run on: $( uname -a )"
echo "They are executed by: $( whoami )"
EOT
ssh user@server "${SSH_COMMAND}"
To use the hex
encoding in Python 3, use
>>> import codecs
>>> codecs.encode(b"c", "hex")
b'63'
In legacy Python, there are several other ways of doing this:
>>> hex(ord("c"))
'0x63'
>>> format(ord("c"), "x")
'63'
>>> "c".encode("hex")
'63'
Recent versions of the TortoiseSVN package can install a discrete svn.exe in addition to the one linked into the GUI binary. It is located in the same bin directory where the main program is installed. (If you have already installed TortoiseSVN, then rerun the installer, select Modify, and select command line tools for installation.)
using System.IO; //add this namespace also
string[] filePaths = Directory.GetFiles(@"c:\Maps\", "*.txt",
SearchOption.TopDirectoryOnly);
For the sake of others who come on this issue, I had this same problem in Ubuntu (namely that my passwords weren't caching, despite having set the option correctly, and getting the error git: 'credential-cache' is not a git command.
), until I found out that this feature is only available in Git 1.7.9 and above.
Being on an older distribution of Ubuntu (Natty; I'm a stubborn Gnome 2 user) the version in the repo was git version 1.7.4.1. I used the following PPA to upgrade: https://launchpad.net/~git-core/+archive/ppa
ie ---> Tools ----> Internet options -----> Programe ------> Make Defualt
I was able to achieve this by coding my own. I don't like extending into and relying on large library's for something rudimental.
Form and Designer:
public partial class InputBox
: Form
{
public String Input
{
get { return textInput.Text; }
}
public InputBox()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
DialogResult = System.Windows.Forms.DialogResult.OK;
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult = System.Windows.Forms.DialogResult.Cancel;
}
private void InputBox_Load(object sender, EventArgs e)
{
this.ActiveControl = textInput;
}
public static DialogResult Show(String title, String message, String inputTitle, out String inputValue)
{
InputBox inputBox = null;
DialogResult results = DialogResult.None;
using (inputBox = new InputBox() { Text = title })
{
inputBox.labelMessage.Text = message;
inputBox.splitContainer2.SplitterDistance = inputBox.labelMessage.Width;
inputBox.labelInput.Text = inputTitle;
inputBox.splitContainer1.SplitterDistance = inputBox.labelInput.Width;
inputBox.Size = new Size(
inputBox.Width,
8 + inputBox.labelMessage.Height + inputBox.splitContainer2.SplitterWidth + inputBox.splitContainer1.Height + 8 + inputBox.button2.Height + 12 + (50));
results = inputBox.ShowDialog();
inputValue = inputBox.Input;
}
return results;
}
void labelInput_TextChanged(object sender, System.EventArgs e)
{
}
}
partial class InputBox
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.labelMessage = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.labelInput = new System.Windows.Forms.Label();
this.textInput = new System.Windows.Forms.TextBox();
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.splitContainer2 = new System.Windows.Forms.SplitContainer();
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).BeginInit();
this.splitContainer2.Panel1.SuspendLayout();
this.splitContainer2.Panel2.SuspendLayout();
this.splitContainer2.SuspendLayout();
this.SuspendLayout();
//
// labelMessage
//
this.labelMessage.AutoSize = true;
this.labelMessage.Location = new System.Drawing.Point(3, 0);
this.labelMessage.MaximumSize = new System.Drawing.Size(379, 0);
this.labelMessage.Name = "labelMessage";
this.labelMessage.Size = new System.Drawing.Size(50, 13);
this.labelMessage.TabIndex = 99;
this.labelMessage.Text = "Message";
//
// button1
//
this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.button1.Location = new System.Drawing.Point(316, 126);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 3;
this.button1.Text = "Cancel";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.button2.Location = new System.Drawing.Point(235, 126);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 2;
this.button2.Text = "OK";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// labelInput
//
this.labelInput.AutoSize = true;
this.labelInput.Location = new System.Drawing.Point(3, 6);
this.labelInput.Name = "labelInput";
this.labelInput.Size = new System.Drawing.Size(31, 13);
this.labelInput.TabIndex = 99;
this.labelInput.Text = "Input";
this.labelInput.TextChanged += new System.EventHandler(this.labelInput_TextChanged);
//
// textInput
//
this.textInput.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textInput.Location = new System.Drawing.Point(3, 3);
this.textInput.Name = "textInput";
this.textInput.Size = new System.Drawing.Size(243, 20);
this.textInput.TabIndex = 1;
//
// splitContainer1
//
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel2;
this.splitContainer1.IsSplitterFixed = true;
this.splitContainer1.Location = new System.Drawing.Point(0, 0);
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.labelInput);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.textInput);
this.splitContainer1.Size = new System.Drawing.Size(379, 50);
this.splitContainer1.SplitterDistance = 126;
this.splitContainer1.TabIndex = 99;
//
// splitContainer2
//
this.splitContainer2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.splitContainer2.IsSplitterFixed = true;
this.splitContainer2.Location = new System.Drawing.Point(12, 12);
this.splitContainer2.Name = "splitContainer2";
this.splitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitContainer2.Panel1
//
this.splitContainer2.Panel1.Controls.Add(this.labelMessage);
//
// splitContainer2.Panel2
//
this.splitContainer2.Panel2.Controls.Add(this.splitContainer1);
this.splitContainer2.Size = new System.Drawing.Size(379, 108);
this.splitContainer2.SplitterDistance = 54;
this.splitContainer2.TabIndex = 99;
//
// InputBox
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(403, 161);
this.Controls.Add(this.splitContainer2);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "InputBox";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Title";
this.TopMost = true;
this.Load += new System.EventHandler(this.InputBox_Load);
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel1.PerformLayout();
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.Panel2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();
this.splitContainer1.ResumeLayout(false);
this.splitContainer2.Panel1.ResumeLayout(false);
this.splitContainer2.Panel1.PerformLayout();
this.splitContainer2.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).EndInit();
this.splitContainer2.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Label labelMessage;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Label labelInput;
private System.Windows.Forms.TextBox textInput;
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.SplitContainer splitContainer2;
}
Usage:
String output = "";
result = System.Windows.Forms.DialogResult.None;
result = InputBox.Show(
"Input Required",
"Please enter the value (if available) below.",
"Value",
out output);
if (result != System.Windows.Forms.DialogResult.OK)
{
return;
}
Note this exhibits a bit of auto sizing to keep it pretty based on how much text you ask it display. I also know it's lacking the bells and whistles but it's a solid step forward for those facing this same dilemma.
Another approach which seemed to work for me at least in Linux environment is to run your Node.js application like this:
env TZ='Europe/Amsterdam' node server.js
This should at least ensure that the timezone is correctly set already from the beginning.
If it is hibernate and JPA. check your referred table name and columns might be a mismatch
Cleanly Migrate Your Subversion Repository To a Git Repository. First you have to create a file that maps your Subversion commit author names to Git commiters, say ~/authors.txt
:
jmaddox = Jon Maddox <[email protected]>
bigpappa = Brian Biggs <[email protected]>
Then you can download the Subversion data into a Git repository:
mkdir repo && cd repo
git svn init http://subversion/repo --no-metadata
git config svn.authorsfile ~/authors.txt
git svn fetch
If you’re on a Mac, you can get git-svn
from MacPorts by installing git-core +svn
.
If your subversion repository is on the same machine as your desired git repository, then you can use this syntax for the init step, otherwise all the same:
git svn init file:///home/user/repoName --no-metadata
For the sake of completeness, you should have a method which can check all arrays:
public static <E> boolean compareArrays(E[] array1, E[] array2) {
boolean b = true;
for (int i = 0; i < array2.length; i++) {
if (array2[i].equals(array1[i]) ) {// For String Compare
System.out.println("true");
} else {
b = false;
System.out.println("False");
}
}
return b;
}
Print service
import { Injectable } from '@angular/core';
@Injectable()
export class PrintingService {
public print(printEl: HTMLElement) {
let printContainer: HTMLElement = document.querySelector('#print-container');
if (!printContainer) {
printContainer = document.createElement('div');
printContainer.id = 'print-container';
}
printContainer.innerHTML = '';
let elementCopy = printEl.cloneNode(true);
printContainer.appendChild(elementCopy);
document.body.appendChild(printContainer);
window.print();
}
}
?omponent that I want to print
@Component({
selector: 'app-component',
templateUrl: './component.component.html',
styleUrls: ['./component.component.css'],
encapsulation: ViewEncapsulation.None
})
export class MyComponent {
@ViewChild('printEl') printEl: ElementRef;
constructor(private printingService: PrintingService) {}
public print(): void {
this.printingService.print(this.printEl.nativeElement);
}
}
Not the best choice, but works.
Use the following code. It works best.
def one_hot_encode(x):
"""
argument
- x: a list of labels
return
- one hot encoding matrix (number of labels, number of class)
"""
encoded = np.zeros((len(x), 10))
for idx, val in enumerate(x):
encoded[idx][val] = 1
return encoded
Found it here P.S You don't need to go into the link.
You can do something like:
s = np.random.normal(2, 3, 1000)
import matplotlib.pyplot as plt
count, bins, ignored = plt.hist(s, 30, density=True)
plt.plot(bins, 1/(3 * np.sqrt(2 * np.pi)) * np.exp( - (bins - 2)**2 / (2 * 3**2) ),
linewidth=2, color='r')
plt.show()
Use these two commands (for Java 8):
sudo update-java-alternatives --set java-8-oracle
java -XshowSettings 2>&1 | grep -e 'java.home' | awk '{print "JAVA_HOME="$3}' | sed "s/\/jre//g" >> /etc/environment
whiles
In your case, the first value to insert must be NULL, because it's AUTO_INCREMENT.
Here are my personal, super-condensed notes, as far as this subject pertains to me currently, for anyone who's interested:
There's a Windows answer, and a Debian answer, so here's a Mac one:
This assumes you're just here looking for a quick way to make a customisable alert sound, and not specifically the piezeoelectric beep you get on Windows:
os.system( "say beep" )
Disclaimer: You can replace os.system
with a call to the subprocess
module if you're worried about someone hacking on your beep code.
It seems to me you could split the cookie key-value pairs into an array and base your search on that:
var obligations = getCookieData("obligations");
Which runs the following:
function getCookieData( name ) {
var pairs = document.cookie.split("; "),
count = pairs.length, parts;
while ( count-- ) {
parts = pairs[count].split("=");
if ( parts[0] === name )
return parts[1];
}
return false;
}
Fiddle: http://jsfiddle.net/qFmPc/
Or possibly even the following:
function getCookieData( name ) {
var patrn = new RegExp( "^" + name + "=(.*?);" ),
patr2 = new RegExp( " " + name + "=(.*?);" );
if ( match = (document.cookie.match(patrn) || document.cookie.match(patr2)) )
return match[1];
return false;
}
The example bellow explains how to remove bullets using a css style class. You can use , similar to css class, by identifier (#id), by parent tag, etc. The same way you can use to define a css to remove bullets from the page footer.
I've used this site as a starting point.
<html>
<head>
<style type="text/css">
div.ui-menu li {
list-style:none;
background-image:none;
background-repeat:none;
background-position:0;
}
ul
{
list-style-type:none;
padding:0px;
margin:0px;
}
li
{
background-image:url(sqpurple.gif);
background-repeat:no-repeat;
background-position:0px 5px;
padding-left:14px;
}
</style>
</head>
<body>
<div class="ui-menu">
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ul>
</div>
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ul>
</body>
</html>
This worked for me when I got the same error message...
mvn install deploy
With socket.emit you can register custom event like that:
server:
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
client:
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
Socket.send does the same, but you don't register to 'news' but to message:
server:
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.send('hi');
});
client:
var socket = io.connect('http://localhost');
socket.on('message', function (message) {
console.log(message);
});
You can get a list of string from your number, by converting it to a string, and then splitting it with an empty string. The result will be an array of strings, each containing a digit:
const num = 124124124
const strArr = `${num}`.split("")
OR to build on this, map each string digit and convert them to a Number
:
const intArr = `${num}`.split("").map(x => Number(x))
A lot of the answers on here use regexes, this is fine but it doesn't handle new additions to the language too well (like arrow functions and classes). Also of note is that if you use any of these functions on minified code it's going to go . It will use whatever the minified name is. Angular gets around this by allowing you to pass in an ordered array of strings that matches the order of the arguments when registering them with the DI container. So on with the solution:
var esprima = require('esprima');
var _ = require('lodash');
const parseFunctionArguments = (func) => {
// allows us to access properties that may or may not exist without throwing
// TypeError: Cannot set property 'x' of undefined
const maybe = (x) => (x || {});
// handle conversion to string and then to JSON AST
const functionAsString = func.toString();
const tree = esprima.parse(functionAsString);
console.log(JSON.stringify(tree, null, 4))
// We need to figure out where the main params are. Stupid arrow functions
const isArrowExpression = (maybe(_.first(tree.body)).type == 'ExpressionStatement');
const params = isArrowExpression ? maybe(maybe(_.first(tree.body)).expression).params
: maybe(_.first(tree.body)).params;
// extract out the param names from the JSON AST
return _.map(params, 'name');
};
This handles the original parse issue and a few more function types (e.g. arrow functions). Here's an idea of what it can and can't handle as is:
// I usually use mocha as the test runner and chai as the assertion library
describe('Extracts argument names from function signature. ', () => {
const test = (func) => {
const expectation = ['it', 'parses', 'me'];
const result = parseFunctionArguments(toBeParsed);
result.should.equal(expectation);
}
it('Parses a function declaration.', () => {
function toBeParsed(it, parses, me){};
test(toBeParsed);
});
it('Parses a functional expression.', () => {
const toBeParsed = function(it, parses, me){};
test(toBeParsed);
});
it('Parses an arrow function', () => {
const toBeParsed = (it, parses, me) => {};
test(toBeParsed);
});
// ================= cases not currently handled ========================
// It blows up on this type of messing. TBH if you do this it deserves to
// fail On a tech note the params are pulled down in the function similar
// to how destructuring is handled by the ast.
it('Parses complex default params', () => {
function toBeParsed(it=4*(5/3), parses, me) {}
test(toBeParsed);
});
// This passes back ['_ref'] as the params of the function. The _ref is a
// pointer to an VariableDeclarator where the ? happens.
it('Parses object destructuring param definitions.' () => {
function toBeParsed ({it, parses, me}){}
test(toBeParsed);
});
it('Parses object destructuring param definitions.' () => {
function toBeParsed ([it, parses, me]){}
test(toBeParsed);
});
// Classes while similar from an end result point of view to function
// declarations are handled completely differently in the JS AST.
it('Parses a class constructor when passed through', () => {
class ToBeParsed {
constructor(it, parses, me) {}
}
test(ToBeParsed);
});
});
Depending on what you want to use it for ES6 Proxies and destructuring may be your best bet. For example if you wanted to use it for dependency injection (using the names of the params) then you can do it as follows:
class GuiceJs {
constructor() {
this.modules = {}
}
resolve(name) {
return this.getInjector()(this.modules[name]);
}
addModule(name, module) {
this.modules[name] = module;
}
getInjector() {
var container = this;
return (klass) => {
console.log(klass);
var paramParser = new Proxy({}, {
// The `get` handler is invoked whenever a get-call for
// `injector.*` is made. We make a call to an external service
// to actually hand back in the configured service. The proxy
// allows us to bypass parsing the function params using
// taditional regex or even the newer parser.
get: (target, name) => container.resolve(name),
// You shouldn't be able to set values on the injector.
set: (target, name, value) => {
throw new Error(`Don't try to set ${name}! `);
}
})
return new klass(paramParser);
}
}
}
It's not the most advanced resolver out there but it gives an idea of how you can use a Proxy to handle it if you want to use args parser for simple DI. There is however one slight caveat in this approach. We need to use destructuring assignments instead of normal params. When we pass in the injector proxy the destructuring is the same as calling the getter on the object.
class App {
constructor({tweeter, timeline}) {
this.tweeter = tweeter;
this.timeline = timeline;
}
}
class HttpClient {}
class TwitterApi {
constructor({client}) {
this.client = client;
}
}
class Timeline {
constructor({api}) {
this.api = api;
}
}
class Tweeter {
constructor({api}) {
this.api = api;
}
}
// Ok so now for the business end of the injector!
const di = new GuiceJs();
di.addModule('client', HttpClient);
di.addModule('api', TwitterApi);
di.addModule('tweeter', Tweeter);
di.addModule('timeline', Timeline);
di.addModule('app', App);
var app = di.resolve('app');
console.log(JSON.stringify(app, null, 4));
This outputs the following:
{
"tweeter": {
"api": {
"client": {}
}
},
"timeline": {
"api": {
"client": {}
}
}
}
Its wired up the entire application. The best bit is that the app is easy to test (you can just instantiate each class and pass in mocks/stubs/etc). Also if you need to swap out implementations, you can do that from a single place. All this is possible because of JS Proxy objects.
Note: There is a lot of work that would need to be done to this before it would be ready for production use but it does give an idea of what it would look like.
It's a bit late in the answer but it may help others who are thinking of the same thing.
In my case I was developing a Polymer WebComponent, which is included using <link rel="import">
into the main HTML document. Turns out that the WebComponent HTML file was being cached for some reason, even though I had changed it since the cached version.
To solve it I opened the Developer Console (in Chrome), right clicked on the reload arrow next to the URL bar and selected "Empty cache and hard reload" - problem solved.
This should be rather a SuperUser question.
Right I have the exact same error inside MacOSX SourceTree, however, inside a iTerm2 terminal, things work just dandy.
However, the problem seemed to be that I've got two ssh-agent
s running ;(
The first being /usr/bin/ssh-agent
(aka MacOSX's) and then also the HomeBrew installed /usr/local/bin/ssh-agent
running.
Firing up a terminal from SourceTree, allowed me to see the differences in SSH_AUTH_SOCK
, using lsof
I found the two different ssh-agent
s and then I was able to load the keys (using ssh-add
) into the system's default ssh-agent
(ie. /usr/bin/ssh-agent
), SourceTree was working again.
Continuing with JoelAnair's answer:
For more robustness, use as follows:
var el = document.getElementById('targetFrame');
if(el.contentWindow)
{
el.contentWindow.targetFunction();
}
else if(el.contentDocument)
{
el.contentDocument.targetFunction();
}
Workd like charm :)
If you need to do this for a large number of articles, then instead of querying the website directly, consider downloading a Wikipedia database dump and then accessing it through an API such as JWPL.
This is a simple blocking technique:
var waitTill = new Date(new Date().getTime() + seconds * 1000);
while(waitTill > new Date()){}
It's blocking insofar as nothing else will happen in your script (like callbacks). But since this is a console script, maybe it is what you need!
Short answer: no (easy?) way, but you can do something that serves your purpose.
I've done a similar tool (a small command that, given a description of a project, sets environment, paths, directories, etc.). What I do is set-up everything and then spawn a shell with:
spawn('bash', ['-i'], {
cwd: new_cwd,
env: new_env,
stdio: 'inherit'
});
After execution, you'll be on a shell with the new directory (and, in my case, environment). Of course you can change bash for whatever shell you prefer. The main differences with what you originally asked for are:
However, for me, that differences are desirable.
Find more about the FileSystemObject object at http://msdn.microsoft.com/en-us/library/aa242706(v=vs.60).aspx. For good VBScript, I recommend:
Here's some code to read and write text to a text file:
Option Explicit
Const fsoForReading = 1
Const fsoForWriting = 2
Function LoadStringFromFile(filename)
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename, fsoForReading)
LoadStringFromFile = f.ReadAll
f.Close
End Function
Sub SaveStringToFile(filename, text)
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename, fsoForWriting)
f.Write text
f.Close
End Sub
SaveStringToFile "f.txt", "Hello World" & vbCrLf
MsgBox LoadStringFromFile("f.txt")
with O(n log(n))
int[] arr1; // your given array
int[] arr2 = new int[arr1.length];
Arrays.sort(arr1);
for (int i = 0; i < arr1.length; i++) {
arr2[i]++;
if (i+1 < arr1.length)
{
if (arr1[i] == arr1[i + 1]) {
arr2[i]++;
i++;
}
}
}
for (int i = 0; i < arr1.length; i++) {
if(arr2[i]>0)
System.out.println(arr1[i] + ":" + arr2[i]);
}
A note to those using potrace and imagemagick, converting PNG images with transparency to PPM doesn't seem to work very well. Here is an example that uses the -flatten
flag on convert
to handle this:
sudo apt-get install potrace imagemagick
convert -flatten input.png output.ppm
potrace -s output.ppm -o output.svg
rm output.ppm
Another interesting phenomenon is that you can use PPM (256*3 colors, ie. RGB), PGM (256 colors, ie. grayscale) or PBM (2 colors, ie. white or black only) as the input format. From my limited observations, it would appear that on images which are anti-aliased, PPM and PGM (which produce identical SVGs as far as I can see) shrink the colored area and PBM expands the colored area (albeit only a little). Presumably this is the difference between a pixel > (256 / 2)
test and a pixel > 0
test. You can switch between the three by changing the file extension, ie. the following use PBM:
sudo apt-get install potrace imagemagick
convert -flatten input.png output.pbm
potrace -s output.pbm -o output.svg
rm output.pbm
This Might help as reference
I had the same issue, after multiple trial of suggested solution on this site and others, I found a solution for my scenario. The account was locked out How to Check if the account is Locked out... Login to the server using higher privileged account (like SA or admin rights) Expand security ==> select the login name ==>open the property window of the login ==> select the status page on the property window
Make sure This 3 Things 1, permission to connect database is GRANTED 2, Login is ENABLED 3, Status SQL server authentication Login is not locked out (Uncheck the box)
Thanks Tsige
For input number in range 0..100
int n1 = 75; // input value
String res; int n=0;
int[] a ={0,20,35,55,70,85,101};
for(; n1>=a[n]; n++);
switch(6-n+1) {
case 1: res="A"; break;
case 2: res="B"; break;
case 3: res="C"; break;
case 4: res="D"; break;
case 5: res="E"; break;
default:res="F";
}
System.out.println(res);
To enhance Fabian's one-liner; let us say that we want to ignore only exit status 1 but to preserve the exit status if it is anything else:
tar -czf sample.tar.gz dir1 dir2 || ( export ret=$?; [[ $ret -eq 1 ]] || exit "$ret" )
This does everything sandeep's script does, on one line.
There are several other version managers to consider, see for a few examples and one that's not listed there that I'll be giving a try soon is ch-ruby. I tried rbenv but had too many problems with it. RVM is my mainstay, though it sometimes has the odd problem (hence my wish to try ch-ruby when I get a chance). I wouldn't touch the system Ruby, as other things may rely on it.
I should add I've also compiled my own Ruby several times, and using the Hivelogic article (as Dave Everitt has suggested) is a good idea if you take that route.
I can strongly recommend looking into Simple, especially if you don't need Servlet capabilities but simply access to the request/reponse objects. If you need REST you can put Jersey on top of it, if you need to output HTML or similar there's Freemarker. I really love what you can do with this combination, and there is relatively little API to learn.
When you make a call to using namespace <some_namespace>;
all symbols in that namespace will become visible without adding the namespace prefix. A symbol may be for instance a function, class or a variable.
E.g. if you add using namespace std;
you can write just cout
instead of std::cout
when calling the operator cout
defined in the namespace std
.
This is somewhat dangerous because namespaces are meant to be used to avoid name collisions and by writing using namespace
you spare some code, but loose this advantage. A better alternative is to use just specific symbols thus making them visible without the namespace prefix. Eg:
#include <iostream>
using std::cout;
int main() {
cout << "Hello world!";
return 0;
}
To be able to give you specific help, you's have to explain what particular parts specifically "get messed up", or perhaps offer a screenshot. It also helps to know what version of Outlook you encounter the problem in.
Either way, CampaignMonitor.com's CSS guide has often helped me out debugging email client inconsistencies.
From that guide you can see several things just won't work well or at all in Outlook, here are some highlights of the more important ones:
E:first-child
, E:hover
, E > F
(Child combinator), E + F
(Adjacent sibling combinator), E ~ F
(General sibling combinator). This unfortunately means resorting to workarounds like inline styles.white-space
won't work.background-image
property won't work.height
, width
, and the max-
versions are either not usable or have bugs for certain elements.display
, float
s and position
are all out).In short: combining CSS and Outlook can be a pain. Be prepared to use many ugly workarounds.
PS. In your specific case, there are two minor issues in your html that may cause you odd behavior. There's "align=top
" where you probably meant to use vertical-align
. Also: cell-padding
for td
s doesn't exist.
In addition to all the other answers you received, I want to explain the unknown option -- o
error: Your command was
$ adb shell 'su -c mount -o rw,remount /system'
which calls su through adb. You properly quoted the whole su command in order to pass it as one argument to adb shell
. However, su -c <cmd>
also needs you to quote the command with arguments it shall pass to the shell's -c
option. (YMMV depending on su
variants.) Therefore, you might want to try
$ adb shell 'su -c "mount -o rw,remount /system"'
(and potentially add the actual device listed in the output of mount | grep system
before the /system
arg – see the other answers.)
Use the following instead:
boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );
This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.
Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.
First off, you have to specify you wish to use Document Literal style:
$client = new SoapClient(NULL, array(
'location' => 'https://example.com/path/to/service',
'uri' => 'http://example.com/wsdl',
'trace' => 1,
'use' => SOAP_LITERAL)
);
Then, you need to transform your data into a SoapVar; I've written a simple transform function:
function soapify(array $data)
{
foreach ($data as &$value) {
if (is_array($value)) {
$value = soapify($value);
}
}
return new SoapVar($data, SOAP_ENC_OBJECT);
}
Then, you apply this transform function onto your data:
$data = soapify(array(
'Acquirer' => array(
'Id' => 'MyId',
'UserId' => 'MyUserId',
'Password' => 'MyPassword',
),
));
Finally, you call the service passing the Data parameter:
$method = 'Echo';
$result = $client->$method(new SoapParam($data, 'Data'));
static string NullToString( object Value )
{
// Value.ToString() allows for Value being DBNull, but will also convert int, double, etc.
return Value == null ? "" : Value.ToString();
// If this is not what you want then this form may suit you better, handles 'Null' and DBNull otherwise tries a straight cast
// which will throw if Value isn't actually a string object.
//return Value == null || Value == DBNull.Value ? "" : (string)Value;
}
I know it's a bit late for this answer, but I've not seen anyone else put this.
Like Greg said, you want to use the Random class
Random rand = new Random();
but the difference I'm going to say is simple do this:
Color color = new Color(rand.nextInt(0xFFFFFF));
And it's as simple as that! no need to generate lots of different floats.
You cannot access var
with the generic.
Try something like
Console.WriteLine("Generic : {0}", test);
And override ToString
method [1]
[1] http://msdn.microsoft.com/en-us/library/system.object.tostring.aspx
Short solution:
const query = {}
const projection = {}
const options = { sort: { id: 1 }, limit: 2, skip: 10 }
Room.find(query, projection, options).exec(function(err, docs) { ... });
another option is rlang::is_empty
(useful if you're working in the tidyverse)
The rlang namespace does not seem to be attached when attaching the tidyverse via library(tidyverse)
- in this case you use purrr::is_empty
, which is just imported from the rlang
package.
By the way, rlang::is_empty
uses user Gavin's approach.
rlang::is_empty(which(1:3 == 5))
#> [1] TRUE
Add this in your HTML or PHP code:
<?php if (!isset($_SERVER['HTTP_USER_AGENT']) || stripos($_SERVER['HTTP_USER_AGENT'], 'Speed Insights') === false): ?>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-PUT YOUR GOOGLE ANALYTICS ID HERE', 'auto');
ga('send', 'pageview');
</script>
<?php endif; ?>
This works fine with JavaScript:
<script>
if(navigator.userAgent.indexOf("Speed Insights") == -1) {
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-<PUT YOUR GOOGLE ANALYTICS ID HERE>', 'auto');
ga('send', 'pageview');
}
</script>
NiloVelez already said: Obviously, it won't make any real improvement, but if your only concern is getting a 100/100 score this will do it.
I had a similar error with Tomcat 8.0 / MySQL . Changing the jdbc url value from localhost to 127.0.0.1 resolved the issue.
<object Margin="left,top,right,bottom"/>
- or -
<object Margin="left,top"/>
- or -
<object Margin="thicknessReference"/>
See here: http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.margin.aspx
This is very nice:
http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/RandomStringUtils.html - something like RandomStringUtils.randomNumeric(7)
.
There are 10^7 equiprobable (if java.util.Random
is not broken) distinct values so uniqueness may be a concern.
There have been many valid answers, however, none of them has the same syntax as tail in linux. The following function can be stored in your $Home\Documents\PowerShell\Microsoft.PowerShell_profile.ps1
for persistency (see powershell profiles documentation for more details).
This allows you to call...
tail server.log
tail -n 5 server.log
tail -f server.log
tail -Follow -Lines 5 -Path server.log
which comes quite close to the linux syntax.
function tail {
<#
.SYNOPSIS
Get the last n lines of a text file.
.PARAMETER Follow
output appended data as the file grows
.PARAMETER Lines
output the last N lines (default: 10)
.PARAMETER Path
path to the text file
.INPUTS
System.Int
IO.FileInfo
.OUTPUTS
System.String
.EXAMPLE
PS> tail c:\server.log
.EXAMPLE
PS> tail -f -n 20 c:\server.log
#>
[CmdletBinding()]
[OutputType('System.String')]
Param(
[Alias("f")]
[parameter(Mandatory=$false)]
[switch]$Follow,
[Alias("n")]
[parameter(Mandatory=$false)]
[Int]$Lines = 10,
[parameter(Mandatory=$true, Position=5)]
[ValidateNotNullOrEmpty()]
[IO.FileInfo]$Path
)
if ($Follow)
{
Get-Content -Path $Path -Tail $Lines -Wait
}
else
{
Get-Content -Path $Path -Tail $Lines
}
}
To conditionally check the length of the string, use CASE
.
SELECT CASE WHEN LEN(comments) <= 60
THEN comments
ELSE LEFT(comments, 60) + '...'
END As Comments
FROM myView
Usually, activating a virtualenv gives you a shell function named:
$ deactivate
which puts things back to normal.
I have just looked specifically again at the code for virtualenvwrapper
, and, yes, it too supports deactivate
as the way to escape from all virtualenvs.
If you are trying to leave an Anaconda environment, the command depends upon your version of conda
. Recent versions (like 4.6) install a conda
function directly in your shell, in which case you run:
conda deactivate
Older conda versions instead implement deactivation using a stand-alone script:
source deactivate
As simple as joining lists in python itself.
ansible -m debug -a msg="{{ '-'.join(('list', 'joined', 'together')) }}" localhost
localhost | SUCCESS => {
"msg": "list-joined-together" }
Works the same way using variables:
ansible -m debug -a msg="{{ '-'.join((var1, var2, var3)) }}" localhost
var intvalue = Math.floor( floatvalue );
var intvalue = Math.ceil( floatvalue );
var intvalue = Math.round( floatvalue );
// `Math.trunc` was added in ECMAScript 6
var intvalue = Math.trunc( floatvalue );
// value=x // x=5 5<x<5.5 5.5<=x<6
Math.floor(value) // 5 5 5
Math.ceil(value) // 5 6 6
Math.round(value) // 5 5 6
Math.trunc(value) // 5 5 5
parseInt(value) // 5 5 5
~~value // 5 5 5
value | 0 // 5 5 5
value >> 0 // 5 5 5
value >>> 0 // 5 5 5
value - value % 1 // 5 5 5
Negative
// value=x // x=-5 -5>x>=-5.5 -5.5>x>-6
Math.floor(value) // -5 -6 -6
Math.ceil(value) // -5 -5 -5
Math.round(value) // -5 -5 -6
Math.trunc(value) // -5 -5 -5
parseInt(value) // -5 -5 -5
value | 0 // -5 -5 -5
~~value // -5 -5 -5
value >> 0 // -5 -5 -5
value >>> 0 // 4294967291 4294967291 4294967291
value - value % 1 // -5 -5 -5
Positive - Larger numbers
// x = Number.MAX_SAFE_INTEGER/10 // =900719925474099.1
// value=x x=900719925474099 x=900719925474099.4 x=900719925474099.5
Math.floor(value) // 900719925474099 900719925474099 900719925474099
Math.ceil(value) // 900719925474099 900719925474100 900719925474100
Math.round(value) // 900719925474099 900719925474099 900719925474100
Math.trunc(value) // 900719925474099 900719925474099 900719925474099
parseInt(value) // 900719925474099 900719925474099 900719925474099
value | 0 // 858993459 858993459 858993459
~~value // 858993459 858993459 858993459
value >> 0 // 858993459 858993459 858993459
value >>> 0 // 858993459 858993459 858993459
value - value % 1 // 900719925474099 900719925474099 900719925474099
Negative - Larger numbers
// x = Number.MAX_SAFE_INTEGER/10 * -1 // -900719925474099.1
// value = x // x=-900719925474099 x=-900719925474099.5 x=-900719925474099.6
Math.floor(value) // -900719925474099 -900719925474100 -900719925474100
Math.ceil(value) // -900719925474099 -900719925474099 -900719925474099
Math.round(value) // -900719925474099 -900719925474099 -900719925474100
Math.trunc(value) // -900719925474099 -900719925474099 -900719925474099
parseInt(value) // -900719925474099 -900719925474099 -900719925474099
value | 0 // -858993459 -858993459 -858993459
~~value // -858993459 -858993459 -858993459
value >> 0 // -858993459 -858993459 -858993459
value >>> 0 // 3435973837 3435973837 3435973837
value - value % 1 // -900719925474099 -900719925474099 -900719925474099
What you're checking
if(isset($_POST['submit']))
but there's no variable name called "submit".
well i want you to understand why it doesn't works.
lets imagine if you give your submit button name delete
<input type="submit" value="Submit" name="delete" />
and check if(isset($_POST['delete']))
then it works in this code you didn't give any name to submit button and checking its exist or not with isset();
function so php didn't find any variable like "submit" so its not working now try this :
<input type="submit" name="submit" value="Submit" />
I had the same question and more, and though this thread is old, it is still a good one, so in summary for SSRS 2008R2 I found...
Situations
Actions
If applicable, be sure to replace Reports/Pages/Report.aspx?ItemPath= with ReportServer?. In other words: Instead of this:
http://server/Reports/Pages/Report.aspx?ItemPath=/ReportFolder/ReportSubfolder/ReportName
Use this syntax:
http://server/ReportServer?/ReportFolder/ReportSubfolder/ReportName
Add parameter(s) to the report and set as hidden (or visible if user action allowed, though keep in mind that while the report parameter will change, the URL will not change based on an updated entry).
Attach parameters to URL with &ParameterName=Value
Parameters can be referenced or displayed in report using @ParameterName, whether they're set in the report or in the URL
To hide the toolbar where parameters are displayed, add &rc:Toolbar=false to the URL (reference)
Putting that all together, you can run a URL with embedded values, or call this as an action from one report and read by another report:
http://server.domain.com/ReportServer?/ReportFolder1/ReportSubfolder1/ReportName&UserID=ABC123&rc:Toolbar=false
In report dataset properties query: SELECT stuff FROM view WHERE User = @UserID
In report, set expression value to [UserID] (or =Fields!UserID.Value)
Keep in mind that if a report has multiple parameters, you might need to include all parameters in the URL, even if blank, depending on how your dataset query is written.
To pass a parameter using Action = Go to URL, set expression to:
="http://server.domain.com/ReportServer?/ReportFolder1/ReportSubfolder1/ReportName&UserID="
&Fields!UserID.Value
&"&rc:Toolbar=false"
&"&rs:ClearSession=True"
Be sure to have a space after an expression if followed by & (a line break is isn't enough). No space is required before an expression. This method can pass a parameter but does not hide it as it is visible in the URL.
If you don't include &rs:ClearSession=True then the report won't refresh until browser session cache is cleared.
To pass a parameter using Action = Go to report:
For reference, / = %2f
In your case, "EOF" is known as a "Here Tag". Basically <<Here
tells the shell that you are going to enter a multiline string until the "tag" Here
. You can name this tag as you want, it's often EOF
or STOP
.
Some rules about the Here tags:
example:
$ cat >> test <<HERE
> Hello world HERE <-- Not by itself on a separate line -> not considered end of string
> This is a test
> HERE <-- Leading space, so not considered end of string
> and a new line
> HERE <-- Now we have the end of the string
Instead of correcting you on the semantics of an 'associative array', I think this is what you want:
function getSortedKeys(obj) {
var keys = keys = Object.keys(obj);
return keys.sort(function(a,b){return obj[b]-obj[a]});
}
for really old browsers, use this instead:
function getSortedKeys(obj) {
var keys = []; for(var key in obj) keys.push(key);
return keys.sort(function(a,b){return obj[b]-obj[a]});
}
You dump in an object (like yours) and get an array of the keys - eh properties - back, sorted descending by the (numerical) value of the, eh, values of the, eh, object.
This only works if your values are numerical. Tweek the little function(a,b)
in there to change the sorting mechanism to work ascending, or work for string
values (for example). Left as an exercise for the reader.
$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https'?'https':'http';
$protocol = isset($_SERVER["HTTPS"]) ? 'https' : 'http';
These should both work
delete acts like a non real world situation, it just removes the item, but the array length stays the same:
example from node terminal:
> var arr = ["a","b","c","d"];
> delete arr[2]
true
> arr
[ 'a', 'b', , 'd', 'e' ]
Here is a function to remove an item of an array by index, using slice(), it takes the arr as the first arg, and the index of the member you want to delete as the second argument. As you can see, it actually deletes the member of the array, and will reduce the array length by 1
function(arr,arrIndex){
return arr.slice(0,arrIndex).concat(arr.slice(arrIndex + 1));
}
What the function above does is take all the members up to the index, and all the members after the index , and concatenates them together, and returns the result.
Here is an example using the function above as a node module, seeing the terminal will be useful:
> var arr = ["a","b","c","d"]
> arr
[ 'a', 'b', 'c', 'd' ]
> arr.length
4
> var arrayRemoveIndex = require("./lib/array_remove_index");
> var newArray = arrayRemoveIndex(arr,arr.indexOf('c'))
> newArray
[ 'a', 'b', 'd' ] // c ya later
> newArray.length
3
please note that this will not work one array with dupes in it, because indexOf("c") will just get the first occurance, and only splice out and remove the first "c" it finds.
A bit late to the party but might be valuable to someone with this error..
I just straight copied a bunch of files into an Xcode project, if you forget to add them to your projects Build Phases you will get the error "Undefined symbols for architecture i386". So add your implementation files to Compile Sources, and Xib files to Copy Bundle Resources.
The error was telling me that there was no link to my classes simply because they weren't included in the Compile Sources, quite obvious really but may save someone a headache.
You could use SQL.js which is the SQLlite lib compiled to JavaScript and store the database in the local storage introduced in HTML5.
$.each(JSON.parse(result), function(i, item) {
alert(item.number);
});
Label's aren't form elements. They don't have a value
. They have innerHTML
and textContent
.
Thus,
$('#telefon').html()
// or
$('#telefon').text()
or
var telefon = document.getElementById('telefon');
telefon.innerHTML;
If you are starting with your form element, check out the labels
list of it. That is,
var el = $('#myformelement');
var label = $( el.prop('labels') );
// label.html();
// el.val();
// blah blah blah you get the idea
To add to the above correct answer :-
For my case in shell, this code worked (working on sqoop
)
ROOT_PATH="path/to/the/folder"
--options-file $ROOT_PATH/query.txt
For oracle you can
group by trunc(created);
as this truncates the created datetime to the previous midnight.
Another option is to
group by to_char(created, 'DD.MM.YYYY');
which achieves the same result, but may be slower as it requires a type conversion.
I tried the following solutions from the other answers and they didn't work:
If your repository is hosted remotely (GitHub, GitLab, BitBucket), you can rename the file on origin (GitHub.com) and force the file rename in a top-down manner.
The instructions below pertain to GitHub, however the general idea behind them should apply to any remote repository-hosting platform. Keep in mind the type of file you're attempting to rename matters, that is, whether it's a file type that GitHub deems as editable (code, text, etc) or uneditable (image, binary, etc) within the browser.
branchname
branch" radio button is selected and click the "Commit changes" buttonbranchname
branch" radio button is selected and click the "Commit changes" buttonI checked off Google API as project build target.
That is irrelevant, as that is for Maps V1, and you are trying to use Maps V2.
I included .jar file for maps by right-clicking on my project, went to build path and added external archive locating it in my SDK: android-sdk-windows\add-ons\addon_google_apis_google_inc_8\libs\maps
This is doubly wrong.
First, never manually modify the build path in an Android project. If you are doing that, at best, you will crash at runtime, because the JAR you think you put in your project (via the manual build path change) is not in your APK. For an ordinary third-party JAR, put it in the libs/
directory of your project, which will add it to your build path automatically and add its contents to your APK file.
However, Maps V2 is not a JAR. It is an Android library project that contains a JAR. You need the whole library project.
You need to import the android-sdk-windows\add-ons\addon_google_apis_google_inc_8
project into Eclipse, then add it to your app as a reference to an Android library project.
Just in case someone only wishes to check if port 22 is open on a remote machine, this simple netcat command is useful. I used it because nmap and telnet were not available for me. Moreover, my ssh configuration uses keyboard password auth.
It is a variant of the solution proposed by GUESSWHOz.
nc -q 0 -w 1 "${remote_ip}" 22 < /dev/null &> /dev/null && echo "Port is reachable" || echo "Port is unreachable"
lst *= 0
has the same effect as
lst[:] = []
It's a little simpler and maybe easier to remember. Other than that there's not much to say
The efficiency seems to be about the same
simple with generated links :) html:
<span class='preview' data-image-url="imageUrl.png" data-container="body" data-toggle="popover" data-placement="top" >preview</span>
js:
$('.preview').popover({
'trigger':'hover',
'html':true,
'content':function(){
return "<img src='"+$(this).data('imageUrl')+"'>";
}
});
This solution worked for me:
tabBarOptions: {
showIcon: true,
showLabel: false,
style: {
backgroundColor: '#000',
borderTopLeftRadius: 40,
borderTopRightRadius: 40,
position: 'relative',
zIndex: 2,
marginTop: -48
}
}
Fixed it...
Get-ChildItem C:\Windows\ -recurse -include @("*.txt*","*.pdf") |
Where-Object {$_.CreationTime -gt "01/01/2013" -and $_.CreationTime -lt "12/02/2014"} |
Select-Object FullName, CreationTime, @{Name="Mbytes";Expression={$_.Length/1Kb}}, @{Name="Age";Expression={(((Get-Date) - $_.CreationTime).Days)}} |
Export-Csv C:\search_TXT-and-PDF_files_01012013-to-12022014_sort.txt
Edit: As Atspulgs comment suggest, you can achieve the same without jQuery using the querySelector:
document.querySelector('head').innerHTML += '<link rel="stylesheet" href="styles.css" type="text/css"/>';
Older answer below.
You could use the jQuery library to select your head element and append HTML to it, in a manner like:
$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');
You can find a complete tutorial for this problem here
The data.table
package has a function 'as.ITime
', which can do this efficiently use below:
library(data.table)
x <- "2012-03-07 03:06:49 CET"
as.IDate(x) # Output is "2012-03-07"
as.ITime(x) # Output is "03:06:49"
I would like to extend the answer of @dzintars about the Cygwin version of pkg-config in that focus how should one use it properly with CMake, because I see various comments about CMake in this topic.
I have experienced many troubles with CMake + Cygwin's pkg-config and I want to share my experience how to avoid them.
1. The symlink C:/Cygwin64/bin/pkg-config -> pkgconf.exe does not work in Windows console.
It is not a native Windows .lnk symlink and it won't be callable in Windows console cmd.exe even if you add ".;" to your %PATHEXT% (see https://www.mail-archive.com/[email protected]/msg104088.html).
It won't work from CMake, because CMake calls pkg-config with the method execute_process() (FindPkgConfig.cmake) which opens a new cmd.exe.
Solution: Add -DPKG_CONFIG_EXECUTABLE=C:/Cygwin64/bin/pkgconf.exe to the CMake command line (or set it in CMakeLists.txt).
2. Cygwin's pkg-config recognizes only Cygwin paths in PKG_CONFIG_PATH (no Windows paths).
For example, on my system the .pc files are located in C:\Cygwin64\usr\x86_64-w64-mingw32\sys-root\mingw\lib\pkgconfig. The following three paths are valid, but only path C works in PKG_CONFIG_PATH:
Solution: add .pc files location always as a Cygwin path into PKG_CONFIG_PATH.
3) CMake converts forward slashes to backslashes in PKG_CONFIG_PATH on Cygwin.
It happens due to the bug https://gitlab.kitware.com/cmake/cmake/-/issues/21629. It prevents using the workaround described in [2].
Solution: manually update the function _pkg_set_path_internal() in the file C:/Program Files/CMake/share/cmake-3.x/Modules/FindPkgConfig.cmake. Comment/remove the line:
file(TO_NATIVE_PATH "${_pkgconfig_path}" _pkgconfig_path)
4) CMAKE_PREFIX_PATH, CMAKE_FRAMEWORK_PATH, CMAKE_APPBUNDLE_PATH have no effect on pkg-config in Cygwin.
Reason: the bug https://gitlab.kitware.com/cmake/cmake/-/issues/21775.
Solution: Use only PKG_CONFIG_PATH as an environment variable if you run CMake builds on Cygwin. Forget about CMAKE_PREFIX_PATH, CMAKE_FRAMEWORK_PATH, CMAKE_APPBUNDLE_PATH.
There's a jquery plugin for this: jquery.floatThead
There are only two ways:
If the memory pointer to by your char *
represents a C string (that is, it contains characters that have a 0-byte to mark its end), you can use strlen(a)
.
Otherwise, you need to store the length somewhere. Actually, the pointer only points to one char
. But we can treat it as if it points to the first element of an array. Since the "length" of that array isn't known you need to store that information somewhere.
Since you're using LibreSSL
, try re-installing curl
with OpenSSL
instead of Secure Transport.
All options have been removed from the curl
formula, so now you need to install via:
brew install curl-openssl
Install curl
with --with-openssl
:
brew reinstall curl --with-openssl
Note: If above won't work, check brew options curl
to display install options specific to formula.
Here are few other suggestions:
http_proxy
/https_proxy
.-v
to curl
for more verbose output.curl
at /usr/bin/curl
, run which -a curl
to list them all.curl
in your firewall (such as Little Snitch).wget
.Bind a change
handler, then just uncheck all of the checkboxes, apart from the one checked:
$('input.example').on('change', function() {
$('input.example').not(this).prop('checked', false);
});
Exposing the Entity instead of the details of the entity.
"Details are there, but we do not consider them. They are not required."
Various calculations: Addition, Multiplication, Subtraction, Division, Square, Sin, Cos, Tan.
We do not show the details of how do we calculate the Sin, Cos or Tan. We just Show Calculator and it's various Methods which will be, and which needs to be used by the user.
Employee has: First Name, Last Name, Middle Name. He can Login(), Logout(), DoWork().
Many processes might be happening for Logging employee In, such as connecting to database, sending Employee ID and Password, receiving reply from Database. Although above details are present, we will hide the details and expose only "Employee".
Enclosing. Treating multiple characteristics/ functions as one unit instead of individuals. So that outside world will refer to that unit instead of it's details directly.
"Details are there, we consider them, but do not show them, instead we show what you need to see."
Instead of calling it as Addition, Subtraction, Multiplication, Division, Now we will call it as a Calculator.
All characteristics and operations are now referred by the employee, such as "John". John Has name. John Can DoWork(). John can Login().
Hiding the implemention from outside world. So that outside world will not see what should not be seen.
"Details are there, we consider them, but we do not show them. You do not need to see them."
Your requirement: Addition, Substraction, Multiplication, Division. You will be able to see it and get the result.
You do not need to know where operands are getting stored. Its not your requirement.
Also, every instruction that I am executing, is also not your requirement.
John Would like to know his percentage of attendance. So GetAttendancePercentage() Will be called.
However, this method needs data saved in database. Hence it will call FetchDataFromDB(). FetchDataFromDB() is NOT required to be visible to outside world.
Hence we will hide it. However, John.GetAttendancePercentage() will be visible to outside world.
Abstraction, encapsulation and hiding complement each others.
Because we create level of abstraction over details, the details are encapsulated. And because they are enclosed, they are hidden.
Just want to share with what I used so far to save your time.
Here are examples of hard-coded headers and dynamic headers (in case if don't care about data structure). In both cases I wrote some simple directive: customSort
customSort
.directive("customSort", function() {
return {
restrict: 'A',
transclude: true,
scope: {
order: '=',
sort: '='
},
template :
' <a ng-click="sort_by(order)" style="color: #555555;">'+
' <span ng-transclude></span>'+
' <i ng-class="selectedCls(order)"></i>'+
'</a>',
link: function(scope) {
// change sorting order
scope.sort_by = function(newSortingOrder) {
var sort = scope.sort;
if (sort.sortingOrder == newSortingOrder){
sort.reverse = !sort.reverse;
}
sort.sortingOrder = newSortingOrder;
};
scope.selectedCls = function(column) {
if(column == scope.sort.sortingOrder){
return ('icon-chevron-' + ((scope.sort.reverse) ? 'down' : 'up'));
}
else{
return'icon-sort'
}
};
}// end link
}
});
I used single ng-repeat
This is a good example in Fiddle (Notice, there is no jQuery library!)
<tbody>
<tr ng-repeat="item in pagedItems[currentPage] | orderBy:sortingOrder:reverse">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.description}}</td>
<td>{{item.field3}}</td>
<td>{{item.field4}}</td>
<td>{{item.field5}}</td>
</tr>
</tbody>
Demo 2: Fiddle
HTML
<table class="table table-striped table-condensed table-hover">
<thead>
<tr>
<th ng-repeat="header in table_headers"
class="{{header.name}}" custom-sort order="header.name" sort="sort"
>{{ header.name }}
</th>
</tr>
</thead>
<tfoot>
<td colspan="6">
<div class="pagination pull-right">
<ul>
<li ng-class="{disabled: currentPage == 0}">
<a href ng-click="prevPage()">« Prev</a>
</li>
<li ng-repeat="n in range(pagedItems.length, currentPage, currentPage + gap) "
ng-class="{active: n == currentPage}"
ng-click="setPage()">
<a href ng-bind="n + 1">1</a>
</li>
<li ng-class="{disabled: (currentPage) == pagedItems.length - 1}">
<a href ng-click="nextPage()">Next »</a>
</li>
</ul>
</div>
</td>
</tfoot>
<pre>pagedItems.length: {{pagedItems.length|json}}</pre>
<pre>currentPage: {{currentPage|json}}</pre>
<pre>currentPage: {{sort|json}}</pre>
<tbody>
<tr ng-repeat="item in pagedItems[currentPage] | orderBy:sort.sortingOrder:sort.reverse">
<td ng-repeat="val in item" ng-bind-html-unsafe="item[table_headers[$index].name]"></td>
</tr>
</tbody>
</table>
As a side note:
The ng-bind-html-unsafe
is deprecated, so I used it only for Demo (2nd example). You welcome to edit.
I've taken DLog
and ALog
from above, and added ULog
which raises a UIAlertView
message.
To summarize:
DLog
will output like NSLog
only when the DEBUG variable is set ALog
will always output like NSLog
ULog
will show the UIAlertView
only when the DEBUG variable is set
#ifdef DEBUG # define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__); #else # define DLog(...) #endif #define ALog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__); #ifdef DEBUG # define ULog(fmt, ...) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%s\n [Line %d] ", __PRETTY_FUNCTION__, __LINE__] message:[NSString stringWithFormat:fmt, ##__VA_ARGS__] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; [alert show]; } #else # define ULog(...) #endif
This is what it looks like:
+1 Diederik
I change permission to storage and error was gone. It seemed lack of permission was the issue.
sudo chmod -R 775 storage/
Bundling is all about compressing several JavaScript or stylesheets files without any formatting (also referred as minified) into a single file for saving bandwith and number of requests to load a page.
As example you could create your own bundle:
bundles.Add(New ScriptBundle("~/bundles/mybundle").Include(
"~/Resources/Core/Javascripts/jquery-1.7.1.min.js",
"~/Resources/Core/Javascripts/jquery-ui-1.8.16.min.js",
"~/Resources/Core/Javascripts/jquery.validate.min.js",
"~/Resources/Core/Javascripts/jquery.validate.unobtrusive.min.js",
"~/Resources/Core/Javascripts/jquery.unobtrusive-ajax.min.js",
"~/Resources/Core/Javascripts/jquery-ui-timepicker-addon.js"))
And render it like this:
@Scripts.Render("~/bundles/mybundle")
One more advantage of @Scripts.Render("~/bundles/mybundle")
over the native <script src="~/bundles/mybundle" />
is that @Scripts.Render()
will respect the web.config
debug setting:
<system.web>
<compilation debug="true|false" />
If debug="true"
then it will instead render individual script tags for each source script, without any minification.
For stylesheets you will have to use a StyleBundle and @Styles.Render().
Instead of loading each script or style with a single request (with script or link tags), all files are compressed into a single JavaScript or stylesheet file and loaded together.
Xcode Workspace vs Project
- What is the difference between the two of them?
Workspace
is a set of projects
- What are they responsible for?
Workspace
is responsible for dependencies between projects.
Project
is responsible for the source code.
- Which one of them should I work with when I'm developing my Apps in team/alone?
You choice should depends on a type of your project. For example if your project relies on CocoaPods dependency manager it creates a workspace.
- Is there anything else I should be aware of in matter of these two files?
A competitor of workspace is cross-project references
[About]
You can also do like this :
$("#table-filters li").parent().find('li').removeClass("active");
It looks like the best way to explain is that tags act as read only branches. You can use a branch as a tag, but you may inadvertently update it with new commits. Tags are guaranteed to point to the same commit as long as they exist.
From the documentation Restore activity UI state using saved instance state it is stated as:
Instead of restoring the state during onCreate() you may choose to implement onRestoreInstanceState(), which the system calls after the onStart() method. The system calls onRestoreInstanceState() only if there is a saved state to restore, so you do not need to check whether the Bundle is null:
IMO, this is more clear way than checking this at onCreate, and better fits with single responsiblity principle.
If using maven, just add to your pom.xml:
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.5.0-b01</version>
</dependency>
Of course, you need to check the current version.
The first thing to consider is that it is rare that you would only want to check whether or not a file exists. In most situations, you're trying to do something with the file if it exists. In Go, any time you try to perform some operation on a file that doesn't exist, the result should be a specific error (os.ErrNotExist
) and the best thing to do is check whether the return err
value (e.g. when calling a function like os.OpenFile(...)
) is os.ErrNotExist
.
The recommended way to do this used to be:
file, err := os.OpenFile(...)
if os.IsNotExist(err) {
// handle the case where the file doesn't exist
}
However, since the addition of errors.Is
in Go 1.13 (released in late 2019), the new recommendation is to use errors.Is
:
file, err := os.OpenFile(...)
if errors.Is(err, os.ErrNotExist) {
// handle the case where the file doesn't exist
}
It's usually best to avoid using os.Stat
to check for the existence of a file before you attempt to do something with it, because it will always be possible for the file to be renamed, deleted, etc. in the window of time before you do something with it.
However, if you're OK with this caveat and you really, truly just want to check whether a file exists without then proceeding to do something useful with it (as a contrived example, let's say that you're writing a pointless CLI tool that tells you whether or not a file exists and then exits ¯\_(?)_/¯
), then the recommended way to do it would be:
if _, err := os.Stat(filename); errors.Is(err, os.ErrNotExist) {
// file does not exist
} else {
// file exists
}
If you don't want to add id's to your data, you could track by the index in the array, which will cause the items to be keyed by their position in the array instead of their value.
Like this:
var myArray = [1,1,1,1,1];
<li ng-repeat="item in myArray track by $index">
Learn More Using this link https://developer.android.com/training/improving-layouts/reusing-layouts.html
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Game_logic">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:id="@+id/text1"
android:textStyle="bold"
tools:text="Player " />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_marginLeft="20dp"
android:id="@+id/text2"
tools:text="Player 2" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Blockquote
Above layout you can used in other activity using
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SinglePlayer">
<include layout="@layout/activity_game_logic"/>
</androidx.constraintlayout.widget.ConstraintLayout>
WordPress asks for your FTP credentials when it can't access the files directly. This is usually caused by PHP running as the apache user (mod_php or CGI) rather than the user that owns your WordPress files.
This is rather normal in most shared hosting environments - the files are stored as the user, and Apache runs as user apache
or httpd
. This is actually a good security precaution so exploits and hacks cannot modify hosted files. You could circumvent this by setting all WP files to 777 security, but that means no security, so I would highly advise against that. Just use FTP, it's the automatically advised workaround with good reason.
I had read some of the responses and they didn't seem to work for me. I am using Typescript 2.9.2, Angular 6 and trying to import JSON in a Jasmine Unit Test. This is what did the trick for me.
Add:
"resolveJsonModule": true,
To tsconfig.json
Import like:
import * as nameOfJson from 'path/to/file.json';
Stop ng test
, start again.
Reference: https://blogs.msdn.microsoft.com/typescript/2018/05/31/announcing-typescript-2-9/#json-imports
The rule is as following :
A B
B as a descendant of A
A > B
B as a child of A
So
div.dropdown *
and not
div.dropdown > *
I think you are confused about how the compiler puts things together. When you use -c
flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o
files thus don't mix with -c
, and compiler warns you about that. Symbols from object file are not moved to other object files like that.
All object files should be on the final linker invocation, which is not the case here, so linker (called via g++
front-end) complains about missing symbols.
Here's a small example (calling g++
explicitly for clarity):
PROG ?= myprog
OBJS = worker.o main.o
all: $(PROG)
.cpp.o:
g++ -Wall -pedantic -ggdb -O2 -c -o $@ $<
$(PROG): $(OBJS)
g++ -Wall -pedantic -ggdb -O2 -o $@ $(OBJS)
There's also makedepend
utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the -M
gcc
option for building make
rules.
I had the same issue recently. This might help if you need a fix immediately, but this needs to be done every time you re-start your system
From terminal, run : ssh-add ~/.ssh/id_rsa
Enter your system password and that should work.
Check out Abraxas Code Check http://www.abxsoft.com/codchk_user.html
this seems to be an ASPX pages problem, I have never been able to show a favicon in any page for IE (all others yes Chrome, FF and safari) the only sites that I've seen that are the exception to that rule are bing.com, msdn.com and others that belong to MS and run on asp.net, there is something that they are not telling us! even world-known sites cant show in IE eg: manu.com (most browsed sports team in the world) aspx site and fails to dislplay the favicon on IE. http://www.manutd.com/favicon.ico does show the icon.
Please prove me wrong.
You want:
java -cp myJar.jar myClass
The Documentation gives the following example:
C:> java -classpath C:\java\MyClasses\myclasses.jar utility.myapp.Cool
Moment.js stores dates it utc and can apply different timezones to it. By default it applies your local timezone. If you want to set time on utc date time you need to specify utc timezone.
Try the following code:
var m = moment().utcOffset(0);
m.set({hour:0,minute:0,second:0,millisecond:0})
m.toISOString()
m.format()
The convention is to ask a question in the name.
Here are a few examples that can be found in the JDK:
isEmpty()
hasChildren()
That way, the names are read like they would have a question mark on the end.
Is the Collection empty?
Does this Node have children?
And, then, true
means yes, and false
means no.
Or, you could read it like an assertion:
The Collection is empty.
The node has children
Note:
Sometimes you may want to name a method something like createFreshSnapshot?
. Without the question mark, the name implies that the method should be creating a snapshot, instead of checking to see if one is required.
In this case you should rethink what you are actually asking. Something like isSnapshotExpired
is a much better name, and conveys what the method will tell you when it is called. Following a pattern like this can also help keep more of your functions pure and without side effects.
If you do a Google Search for isEmpty()
in the Java API, you get lots of results.
You can use the .NET Path class:
[IO.Path]::Combine('C:\', 'Foo', 'Bar')
I was looking for a way how to output a formatted time with minimal code, so here is my solution. Many people use Pandas anyway, so in some cases this can save from additional library imports.
import pandas as pd
start = pd.Timestamp.now()
# code
print(pd.Timestamp.now()-start)
Output:
0 days 00:05:32.541600
I would recommend using this if time precision is not the most important, otherwise use time
library:
%timeit pd.Timestamp.now()
outputs 3.29 µs ± 214 ns per loop
%timeit time.time()
outputs 154 ns ± 13.3 ns per loop
similar solution can be found here using jquery to set the auto width when focus (or mouseenter) and set the orignal width back when blur (or mouseleave) http://css-tricks.com/select-cuts-off-options-in-ie-fix/.
What you want is a SQL case statement. The form of these is either:
select case [expression or column]
when [value] then [result]
when [value2] then [result2]
else [value3] end
or:
select case
when [expression or column] = [value] then [result]
when [expression or column] = [value2] then [result2]
else [value3] end
In your example you are after:
declare @temp as varchar(100)
set @temp='Measure'
select case @temp
when 'Measure' then Measure
else OtherMeasure end
from Measuretable
The SmtpClient can be used by code:
SmtpClient mailer = new SmtpClient();
mailer.Host = "mail.youroutgoingsmtpserver.com";
mailer.Credentials = new System.Net.NetworkCredential("yourusername", "yourpassword");
Do it in the controller
$timeout(function(){
$scope.checked = true;
}, 1);
_x000D_
then remove ng-checked.
copy() only works with files.
Both the DOS copy and Unix cp commands will copy recursively - so the quickest solution is just to shell out and use these. e.g.
`cp -r $src $dest`;
Otherwise you'll need to use the opendir
/readdir
or scandir
to read the contents of the directory, iterate through the results and if is_dir returns true for each one, recurse into it.
e.g.
function xcopy($src, $dest) {
foreach (scandir($src) as $file) {
if (!is_readable($src . '/' . $file)) continue;
if (is_dir($src .'/' . $file) && ($file != '.') && ($file != '..') ) {
mkdir($dest . '/' . $file);
xcopy($src . '/' . $file, $dest . '/' . $file);
} else {
copy($src . '/' . $file, $dest . '/' . $file);
}
}
}
New Selenium libraries are now out, according to: https://github.com/SeleniumHQ/selenium/issues/2110
The download page http://www.seleniumhq.org/download/ seems not to be updated just yet, but by adding 1 to the minor version in the link, I could download the C# version: http://selenium-release.storage.googleapis.com/2.53/selenium-dotnet-2.53.1.zip
It works for me with Firefox 47.0.1.
As a side note, I was able build just the webdriver.xpi Firefox extension from the master branch in GitHub, by running ./go //javascript/firefox-driver:webdriver:run
– which gave an error message but did build the build/javascript/firefox-driver/webdriver.xpi file, which I could rename (to avoid a name clash) and successfully load with the FirefoxProfile.AddExtension method. That was a reasonable workaround without having to rebuild the entire Selenium library.
With Postgresql 9.5 it can be done by following-
UPDATE test
SET data = data - 'a' || '{"a":5}'
WHERE data->>'b' = '2';
OR
UPDATE test
SET data = jsonb_set(data, '{a}', '5'::jsonb);
Somebody asked how to update many fields in jsonb value at once. Suppose we create a table:
CREATE TABLE testjsonb ( id SERIAL PRIMARY KEY, object JSONB );
Then we INSERT a experimental row:
INSERT INTO testjsonb
VALUES (DEFAULT, '{"a":"one", "b":"two", "c":{"c1":"see1","c2":"see2","c3":"see3"}}');
Then we UPDATE the row:
UPDATE testjsonb SET object = object - 'b' || '{"a":1,"d":4}';
Which does the following:
Selecting the data:
SELECT jsonb_pretty(object) FROM testjsonb;
Will result in:
jsonb_pretty
-------------------------
{ +
"a": 1, +
"c": { +
"c1": "see1", +
"c2": "see2", +
"c3": "see3", +
}, +
"d": 4 +
}
(1 row)
To update field inside, Dont use the concat operator ||
. Use jsonb_set instead. Which is not simple:
UPDATE testjsonb SET object =
jsonb_set(jsonb_set(object, '{c,c1}','"seeme"'),'{c,c2}','"seehim"');
Using the concat operator for {c,c1} for example:
UPDATE testjsonb SET object = object || '{"c":{"c1":"seedoctor"}}';
Will remove {c,c2} and {c,c3}.
For more power, seek power at postgresql json functions documentation. One might be interested in the #-
operator, jsonb_set
function and also jsonb_insert
function.
func currentmicrotimeTimeMillis() -> Int64{
let nowDoublevaluseis = NSDate().timeIntervalSince1970
return Int64(nowDoublevaluseis*1000)
}
To Close a fragment while inside the same fragment
getActivity().onBackPressed();
you can do this with jdk >= 8
getComboBox().addItemListener(this::comboBoxitemStateChanged);
so
public void comboBoxitemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
YourObject selectedItem = (YourObject) e.getItem();
//TODO your actitons
}
}
The code has the following issues:
<a4j:commandButton .../>
) does not work with attachments.a4j
tags.<a4j:commandButton .../>
to <h:commandButton .../>
.bw.write( getDomainDocument() );
to bw.write( document );
.String document = getDomainDocument();
to the first line of the try/catch
.<a4j:outputPanel.../>
(not shown) to <h:messages showDetail="false"/>
.Essentially, remove all the Ajax facilities related to the commandButton
. It is still possible to display error messages and leverage the RichFaces UI style.
You could as well get more easy-to-interpret picture of where tags point to using
git log --graph |git name-rev --stdin --tags |less
and then scroll to the tag you're looking for via /
.
More compact view (--pretty=oneline
) plus all heads (-a
) could also help:
git log -a --pretty=oneline --graph |git name-rev --stdin --tags |less
Looks a bit terrifying, but could also be aliased in ~/.gitconfig
if necessary.
~/.gitconfig
[alias]
ls-tags = !git log -a --pretty=oneline --graph |git name-rev --stdin --tags |less
I recently found this library that converts an Excel workbook file into a DataSet: Excel Data Reader
As others have stated it's combination of your schema and the number of indexes.
A friend had about 100,000,000 historical stock prices, daily closing quotes, in an MDB which approached the 2 Gb limit.
He pulled them down using some code found in a Microsoft Knowledge base article. I was rather surprised that whatever server he was using didn't cut him off after the first 100K records.
He could view any record in under a second.
Instead of downloading curl, down libcurl.
curl is just the application, libcurl is what you need for your C++ program
USE BINARY
This is a simple select
SELECT * FROM myTable WHERE 'something' = 'Something'
= 1
This is a select with binary
SELECT * FROM myTable WHERE BINARY 'something' = 'Something'
or
SELECT * FROM myTable WHERE 'something' = BINARY 'Something'
= 0
80 % of the times, this would due to wrong input by in soapRequest.xml file
I did the following:
void BrowserDocumentCompleted(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
if (e.Url.AbsolutePath != (sender as WebBrowser).Url.AbsolutePath)
return;
//The page is finished loading
}
The last page loaded tends to be the one navigated to, so this should work.
From here.
To replace a character at a specified position :
public static String replaceCharAt(String s, int pos, char c) {
return s.substring(0,pos) + c + s.substring(pos+1);
}
Void doesn't return anything; it tells the compiler the method doesn't have a return value.
I think what you are being asked to do (or perhaps asking yourself?) is take a character value which matches the name of a column in a particular dataframe (possibly also given as a character). There are two tricks here. Most people learn to extract columns with the "$" operator and that won't work inside a function if the function is passed a character vecor. If the function is also supposed to accept character argument then you will need to use the get
function as well:
df1 <- data.frame(a=1:10, b=11:20)
mean_col <- function( dfrm, col ) mean( get(dfrm)[[ col ]] )
mean_col("df1", "b")
# [1] 15.5
There is sort of a semantic boundary between ordinary objects like character vectors and language objects like the names of objects. The get
function is one of the functions that lets you "promote" character values to language level evaluation. And the "$" function will NOT evaluate its argument in a function, so you need to use"[[". "$" only is useful at the console level and needs to be completely avoided in functions.
May be this post (Secure Metro JAX-WS UsernameToken Web Service with Signature, Encryption and TLS (SSL)) provides more insight. As they mentioned "Remember, unless password text or digested password is sent on a secured channel or the token is encrypted, neither password digest nor cleartext password offers no real additional security. "
The accepted answer didn't work for me on Azure SQL, here's one that did, it's super fast and did exactly what I wanted:
select t.name, s.row_count
from sys.tables t
join sys.dm_db_partition_stats s
ON t.object_id = s.object_id
and t.type_desc = 'USER_TABLE'
and t.name not like '%dss%'
and s.index_id = 1
order by s.row_count desc
Already many valid answers to this question. Not many using a functional approach though. Here is an alternative solution using the forEach
method, which works well with callbacks and closures:
let arr = [1,2,3];
let myFunc = (val, index) => {
console.log('val: '+val+'\nindex: '+index);
};
arr.forEach(myFunc);
In your state, home is initialized as an array
homes: []
In your return, there is an attempt to render home (which is an array).
<p>Stuff: {homes}</p>
Cannot be done this way --- If you want to render it, you need to render an array into each single item. For example: using map()
Ex: {home.map(item=>item)}
Just to give a short, working example to see an effect of their difference
new Thread(foo).Start();
private void foo()
{
this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
(ThreadStart)delegate()
{
myTextBox.Text = "bing";
Thread.Sleep(TimeSpan.FromSeconds(3));
});
MessageBox.Show("done");
}
If use BeginInvoke, MessageBox pops simultaneous to the text update. If use Invoke, MessageBox pops after the 3 second sleep. Hence, showing the effect of an asynchronous (BeginInvoke) and a synchronous (Invoke) call.