input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Playing encrypted MP4 <p><p>I'm making a <strong>(local - Multi-Platform) video protection app</strong> but I don't know what is the right solution to first "encrypt->save on HDD" and then <strong>"load from HDD->decrypt->play"</strong> encrypted video.</p> <p>I read about MPEG-DASH and some DRMs and found this Bento4 command:</p>
<pre><code>mp4dash --encryption-key=000102030405060708090a0b0c0d0e0f:00112233445566778899aabbccddeeff --encryption-args="--property 1:ClearLeadFragments:10 --property 2:ClearLeadFragments:10" movie.mp4
</code></pre>
<p>but I'm not sure that MPEG-DASH can be a part of solution or not.</p> How can I solve this?</p>
| <p>After many searches on google I found the answer of <a href="http://stackoverflow.com/users/1936622/erti-chris-eelmaa">@erti-chris-eelmaa</a> here:<p>
<a href="http://stackoverflow.com/questions/7316729/playing-encrypted-video">Playing encrypted video</a></p>
<blockquote>
<p>I wrote my own Videoplayer using openGL+FFMPEG that could play mp4 and
decrypt each frame in the GPU using shaders. I also experimented with
another possible solutions, such as streaming from a webserver using
VLC. (VLC offers some kind of encryption/decryption when dealing with
streams), and yada yada yada.</p>
<p>Also one solution was to use 4 mediaelements(WPF) and the actual video
was virtually split into 4 areas and each area was rotated so the
video was not viewable. Once you loaded the video into 4
mediaelements, you could map out which part you wanted to show and
also rotate it back. But in all honesty, MediaElement is bad.</p>
<p>However I ended up exactly with what RomanR said. I built DirectShow
graph using mp4splitter, ffdshow, videorenderer and I modified
mp4splitter sourcefilter. The reading happens in
BaseSplitter/AsyncReader.cpp (just modify SyncRead function) that
mp4splitter uses.</p>
<p>If you would like to implement it yourself, just use MPC-HC project
and modify the filters as you like. It took me some time to get around
the DirectShow concept, but once you understand it, it becomes great
weapon.</p>
</blockquote>
|
Android:Custom Fonts to Text View. It mess up my other code <p>I was able to change the font in a new fresh project (only one activity and text "hello world") in Android Studio to a unique font not available in Android Studio. It worked great. </p>
<p>But when I followed the exact same procedure and used the exact same code in my existing project it worked too BUT it messed up my other java code in the activity. </p>
<p>Specifically, the Activity On Button Click via Intent. Clicking on the button did not open the new activity anymore. </p>
<p>I removed the java code for the custom font because priority is for the button intent to work. I am a complete amateur and have only been doing development in android for 6 weeks (no prior coding experience). </p>
<p>Below you can see the code. You can see below I placed the code in the exact same place in both the fresh project and existing project. What do I need to do to get the custom font AND have the button intent work in the existing project? </p>
<p><strong>FRESH PROJECT</strong></p>
<pre><code>package com.example.android.practice2;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Typeface myTypeFace = Typeface.createFromAsset (getAssets(),"font.ttf");
TextView myTextview = (TextView)findViewById(R.id.textview99);
myTextview.setTypeface(myTypeFace);
}
}
</code></pre>
<p><strong>EXISTING PROJECT:</strong></p>
<p>Where do I place the code here?
Placed where it is now creates a custom font but the button intent stops working?</p>
<pre><code> package com.example.android.xxxxxx;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
/* Below for button to open new activity */
private static Button button_sbm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OnClickButtonListener();
Typeface myTypeFace = Typeface.createFromAsset(getAssets(),"font.ttf");
TextView myTextview = (TextView)findViewById(R.id.textview99);
myTextview.setTypeface(myTypeFace);
}
/* Opens 3rd Activity */
public void OnClickButtonListener() {
button_sbm = (Button) findViewById(R.id.start);
button_sbm.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("com.example.android.yes.FirstActivity");
startActivity(intent);
}
}
);
}
}
</code></pre>
| <p>You can try to this code..</p>
<pre><code>public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button button_sbm;
private TextView myTextview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_sbm = (Button) findViewById(R.id.start);
myTextview = (TextView) findViewById(R.id.textview99);
Typeface myTypeFace = Typeface.createFromAsset(getAssets(), "font.ttf");
myTextview.setTypeface(myTypeFace);
button_sbm.setOnClickListener(this);
}
@Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Click is Working", Toast.LENGTH_LONG).show();
Intent intent = new Intent("com.example.android.yes.FirstActivity");
startActivity(intent);
}
</code></pre>
<p>}</p>
|
Dutch flag with four colors <p>I went through a solution for two and three colors but I am unable to get it for four colors.</p>
<p>Please help.</p>
<p>Will it be <code>rrbb????yyyggg</code>?
How will we swap the green flag?</p>
<p>I tried the solution below but it is not working with swapping the last yellow with green.</p>
<pre><code> public class count123 {
// Java program to sort an array of 0, 1 and 2,3
static void sort0123(int a[], int arr_size)
{
int lo = 0;
int hi = arr_size - 1;
int mid = 0,temp=0;
int h2=arr_size - 1;
while (mid <= hi)
{
switch (a[mid])
{
case 0:
{
temp = a[lo];
a[lo] = a[mid];
a[mid] = temp;
lo++;
mid++;
break;
}
case 1:
mid++;
break;
case 2:
{
temp = a[mid];
a[mid] = a[hi];
a[hi] = temp;
hi--;
h2=hi;
break;
}
case 3:{
temp = a[mid];
a[mid] = a[h2];
a[h2] = temp;
// h2--;
//hi=h2;
break;
}
}
}
}
/* Utility function to print array arr[] */
static void printArray(int arr[], int arr_size)
{
int i;
for (i = 0; i < arr_size; i++)
System.out.print(arr[i]+" ");
System.out.println("");
}
/*Driver function to check for above functions*/
public static void main (String[] args)
{
int arr[] = {0, 1, 0,1,2,2,0,3,3,0,0,1};
int arr_size = arr.length;
sort0123(arr, arr_size);
System.out.println("Array after seggregation ");
printArray(arr, arr_size);
}
}
/*This code is contributed by Devesh Agrawal*/
</code></pre>
| <p>I run your code and realized that your code goes into <em>infinite loop</em>, which let does your programm do nothing.</p>
<p>In the main method, <code>sort0123(arr, arr_size);</code> is called and within this method, <code>while (mid <= hi)</code>, mid = 6 and hi = 9 and that means <code>6 <= 9</code> and because of this resaon, this condition returns true infinitely because of the fact that it goes always to the case 3 at some point and in the case 3, the values of mid and hi are not changed.</p>
<p>In order to be able to run your code, you should change the value(s) of <code>mid</code> and/or <code>hi</code> logically and with it, your program can behave, how you wanted. </p>
|
Implementing both SAML and legacy login without Spring Security API <p>I have a similar question to <a href="http://stackoverflow.com/questions/29027961/can-i-implement-both-saml-and-basic-spring-security-within-an-application">this</a> one however our application (which makes use of only Spring Beans & Annotations) currently does not use the Spring Security component/API. Would like to know if we can support the plain vanilla login (based on username password) mechanism for one set of users and support SAML based logins for another set of users (thereby using only Spring SAML extension). Or is there some basic Spring security config to incorporate before we use the SAML extension? Thanks in advance.</p>
| <p>It is in fact possible to use Spring SAML extension without 'implementing' the Spring security aspect in the project. However the spring security jars are needed as a dependency.</p>
|
busyindicator for angular2 kendo ui grid before data is loaded through http <p>I'm using angular2 kendo ui grid and binding data to the grid by http call</p>
<p>before http call returns the data i need to show busy indicator without showing grid header till data is assigned.How to achive this</p>
<p>Thanks,
Raghu s</p>
| <p>I achieved this by declaring the following within the HTML template.</p>
<p>Add a new div above the grid with a conditional loading text for when the grid is loading:</p>
<pre><code><div *ngIf="loading == true" class="loader">Loading..</div>
</code></pre>
<p>Add a div wrapper around the grid for when the loading in completed:</p>
<pre><code><div *ngIf="loading == false">
<kendo-grid [data]="view1">
<kendo-grid>
</div>
</code></pre>
<p>In <code>app.component.ts</code></p>
<pre><code>export class AppComponent{
private loading: boolean = true;
constructor(private http: Http
) {
http.get('/api/Data')
.map(response => response.json())
.subscribe(result => {
this.loading = false;
this.view1 = result;
this.loadProducts();
},
err => console.log(err)
);
}
}
</code></pre>
|
PLSQL - How does this Prime number code work? <pre><code>DECLARE
i number(3);
j number(3);
BEGIN
i := 2;
LOOP
j:= 2;
LOOP
exit WHEN ((mod(i, j) = 0) or (j = i));
j := j +1;
END LOOP;
IF (j = i ) THEN
dbms_output.put_line(i || ' is prime');
END IF;
i := i + 1;
exit WHEN i = 50;
END LOOP;
END;
</code></pre>
<p>The code works properly. I tried to figure out how it works and ended up having 4 as a prime number, which isn't. If you could help me understand how this nested loop works, I'd be very thankful.</p>
<p>Thank you.</p>
| <p>Lets rewrite it so its a bit simpler:</p>
<pre><code>BEGIN
<<outer_loop>>
FOR value IN 2 .. 50 LOOP
FOR divisor IN 2 .. value - 1 LOOP
CONTINUE outer_loop WHEN MOD( value, divisor ) = 0;
END LOOP;
DBMS_OUTPUT.PUT_LINE( value || ' is prime' );
END LOOP;
END;
/
</code></pre>
<p>All it is doing is, in the outer loop going through the number 2 .. 50 and in the inner loop is checking whether there is a number that divides exactly into that value; if there is then continue the outer loop and if there is not then output that the number is prime.</p>
<p>Your code is effectively the same code but it is complicated by not using <code>FOR .. IN ..</code> loops </p>
|
Wordpress Query posts wrap each item in a div rather than an li and show descendants of current page <p>I am using the following to wrap through a list of posts as I want to display them within divs.</p>
<p>Despite using </p>
<pre><code> global $post;
$currentPage = $post->ID;
</code></pre>
<p>and</p>
<pre><code> 'post_parent' => $currentPage,
</code></pre>
<p>Which has worked fine elsewhere. I can't get the page to only show children and grandchildren of this page.</p>
<pre><code><?php
global $post;
$currentPage = $post->ID;
// Get posts (tweak args as needed)
$args = array(
'post_parent' => $currentPage,
'post_type' => 'page',
'orderby' => 'menu_order',
'order' => 'ASC'
);
$posts = get_pages( $args );
?>
<?php foreach (array_chunk($posts, 1, true) as $posts) : ?>
<div class="column small-4 medium-4 large-4">
<?php foreach( $posts as $post ) : setup_postdata($post); ?>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
<?php endforeach; ?>
</div>
<?php endforeach; ?>
</code></pre>
<p>I am using the code within a custom template.</p>
<p>I have also tried</p>
<pre><code> <?php
global $post;
$currentPage = $post->ID;
$args=array(
'child_of' => $currentPage,
'post_type' => 'page'
);
$my_query = null;
$my_query = new WP_Query($args);
echo $currentPage;
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<?php $img = wp_get_attachment_image_src( get_post_meta($post->ID, 'image_or_video', true)); ?>
<?php $alt_text_for_logo = get_post_meta($post->ID, 'article_name', true); ?>
<?php $short_description = get_post_meta($post->ID, 'article_short_description', true); ?>
<div class="column small-12 medium-6 large-4 box">
<div>
<a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>" itemprop="url">
<?php if( $img ): ?>
<img src="<?php echo $img[0]; ?>" alt="<?php echo $alt_text_for_logo; ?>" />
<?php endif; ?>
<span><?php the_title(); ?></span>
</a>
</div>
</div>
<?php endwhile; } ?>
<?php wp_reset_query();?>
</code></pre>
<p>but this lists the pages I want followed by what appears to be 10 other random pages from the site's root though it doesn't list every page from the site.</p>
| <p>Originally posted this solution as a comment, because I wasn't sure it was the only change that was necessary. Turned out it is, so here's the solution:</p>
<pre><code><?php
global $post;
$currentPage = $post->ID;
// Get posts (tweak args as needed)
$args = array(
'child_of' => $currentPage,
'post_type' => 'page',
'orderby' => 'menu_order',
'order' => 'ASC'
);
$posts = get_pages( $args );
?>
<?php foreach (array_chunk($posts, 1, true) as $posts) : ?>
<div class="column small-4 medium-4 large-4">
<?php foreach( $posts as $post ) : setup_postdata($post); ?>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
<?php endforeach; ?>
</div>
<?php endforeach; ?>
</code></pre>
<p>The function <code>get_pages</code> doesn't seem to have <code>post_parent</code> as a valid argument. So you need to use <code>child_of</code> instead.</p>
<p><a href="http://codex.wordpress.org/Function_Reference/get_pages" rel="nofollow">Reference to Codex</a></p>
|
MySQL creating a table with 2 diffirent selects <pre><code>SELECT COUNT(*) as not_returned_devices, contact_email FROM device_rent WHERE rent_end IS NULL GROUP BY contact_email;
SELECT COUNT(*) as returned_devices, contact_email FROM device_rent WHERE rent_end IS NOT NULL GROUP BY contact_email;
</code></pre>
<p>What i need is make a table with 3 columns: contact_name, number of returned devices and number of not returned devices. Basically, what i need is merge those two selects in one table, but im stuck. </p>
| <p>Just use conditional aggregation:</p>
<pre><code>SELECT contact_email, SUM(rent_end IS NULL) as not_returned_devices,
SUM(rent_end IS NOT NULL) as returned_devices
FROM device_rent
GROUP BY contact_email;
</code></pre>
<p>Note that this uses a MySQL short-cut, where boolean expressions are treated as "1" for true and "0" for false. This is a convenience, and save you from writing a <code>case</code> statement. That would look like:</p>
<pre><code>SELECT contact_email,
SUM(CASE WHEN rent_end IS NULL THEN 1 ELSE 0
END) as not_returned_devices,
COUNT(rent_end) as returned_devices
FROM device_rent
GROUP BY contact_email;
</code></pre>
|
Power shell to create user and set Regional Configuration <p>Can anyone help. I'm creating users on our exchange 2016 system by using the following cmd's</p>
<pre><code>Enable-MailUser -Identity "joe.bloggs" -ExternalEmailAddress 'joe.bloggs@domain.co.uk'
Get-MailUser -Identity "joe.bloggs" | Enable-Mailbox
Add-MailboxPermission -Identity "joe.bloggs" -User MailboxAdmins -AccessRights Fullaccess -InheritanceType all
Set-MailboxRegionalConfiguration -Identity "joe.bloggs" -TimeZone "GMT Standard Time" -DateFormat "dd/MM/yyyy" -Language "en-GB" -TimeFormat "HH:mm"
</code></pre>
<p>They all work however the Set-MailboxRegionalConfiguration always throws an error. I have to wait a few minutes and then run it again and it completes. I believe it is because the Enable user cmd is still working in the background.</p>
<p>Does anyone know of a way of changing it so that the cmd runs after the mailbox has been enabled?</p>
<p>Thanks</p>
| <p>You could add <code>sleep</code> interval into your script to give exchange time to sort out the account before running the <code>Set-MailboxRegionalConfiguration</code> cmdlet. </p>
<pre><code>Enable-MailUser -Identity "joe.bloggs" -ExternalEmailAddress 'joe.bloggs@domain.co.uk'
Get-MailUser -Identity "joe.bloggs" | Enable-Mailbox
Add-MailboxPermission -Identity "joe.bloggs" -User MailboxAdmins -AccessRights Fullaccess -InheritanceType all
Sleep -Seconds 30
Set-MailboxRegionalConfiguration -Identity "joe.bloggs" -TimeZone "GMT Standard Time" -DateFormat "dd/MM/yyyy" -Language "en-GB" -TimeFormat "HH:mm"
</code></pre>
|
Implement async method synchronously <p>I have an interface which forces me to implement an (async) Task:</p>
<pre><code>namespace Microsoft.Owin.Security.Infrastructure
{
public interface IAuthenticationTokenProvider
{
..
Task CreateAsync(AuthenticationTokenCreateContext context);
..
}
}
</code></pre>
<p>I want to implement this method, but I'm not awaiting anything. Although I have to await something or return some task, otherwise my code does not compile.:</p>
<pre><code>public class MyImplementation: IAuthenticationTokenProvider
{
public async Task CreateAsync(AuthenticationTokenCreateContext context)
{
/// do something synchronously.
await something here? ??
}
}
</code></pre>
<p>My question is: How would I implement this method without doing something asynchronously? I've have found a couple of solutions (await <code>task.Yield()</code>, or <code>await Task.Run(() => {}))</code>, yet I can't fully understand what would be the correct implementation and why.</p>
| <p>Just implement the method without awaiting:</p>
<pre><code>public async Task<Foo> GetFooAsync()
{
return new Foo();
}
</code></pre>
<p>It doesn't matter that you're not awaiting anything. It's not a requirement of an async method to await anything (although the compiler will warn you that you're not awaiting anything).</p>
<p>If you don't want the overhead of an aysnc method (there's a cost associated with the async "state machine" that might be undesirable), you could</p>
<pre><code>public Task<Foo> GetFooAsync()
{
return Task.FromResult(new Foo());
}
</code></pre>
|
Typescript compiler suddenly started to generate errors <p>I'm working on an angular/2 project and all of a sudden I have started to get lots and lots of errors when I try and run the typescript compiler. Can anybody please advise on where to start searching? I have not knowingly changed anything fundamental and even when I clone a fresh copy from the repo the errors persist. The errors are below:</p>
<p>node_modules/@types/node/index.d.ts(102,6): error TS2300: Duplicate identifier 'BufferEncoding'.
node_modules/@types/node/index.d.ts(256,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'errno' must be of type 'number', but here has type 'string'.
node_modules/@types/node/index.d.ts(263,18): error TS2300: Duplicate identifier 'EventEmitter'.
node_modules/@types/node/index.d.ts(549,26): error TS2300: Duplicate identifier 'Buffer'.
node_modules/@types/node/index.d.ts(549,50): error TS2300: Duplicate identifier 'SlowBuffer'.
node_modules/@types/node/index.d.ts(570,18): error TS2300: Duplicate identifier 'EventEmitter'.
node_modules/@types/node/index.d.ts(570,18): error TS2415: Class 'EventEmitter' incorrectly extends base class 'NodeJS.EventEmitter'.
Types of property 'eventNames' are incompatible.
Type '() => (string | symbol)[]' is not assignable to type '() => string[]'.
Type '(string | symbol)[]' is not assignable to type 'string[]'.
Type 'string | symbol' is not assignable to type 'string'.
Type 'symbol' is not assignable to type 'string'.
node_modules/@types/node/index.d.ts(733,18): error TS2300: Duplicate identifier 'Agent'.
node_modules/@types/node/index.d.ts(788,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'addressType' must be of type 'string', but here has type 'number | "udp4" | "udp6"'.
node_modules/@types/node/index.d.ts(791,18): error TS2300: Duplicate identifier 'Worker'.
node_modules/@types/node/index.d.ts(1377,17): error TS2300: Duplicate identifier 'CompleterResult'.
node_modules/@types/node/index.d.ts(1414,18): error TS2300: Duplicate identifier 'Script'.
node_modules/@types/node/index.d.ts(2550,18): error TS2300: Duplicate identifier 'TLSSocket'.
node_modules/@types/node/index.d.ts(2684,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'pfx' must be of type 'any', but here has type 'string | Buffer[]'.
node_modules/@types/node/index.d.ts(2685,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'key' must be of type 'any', but here has type 'string | any[] | string[] | Buffer'.
node_modules/@types/node/index.d.ts(2687,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'cert' must be of type 'any', but here has type 'string | string[] | Buffer | Buffer[]'.
node_modules/@types/node/index.d.ts(2688,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'ca' must be of type 'any', but here has type 'string | string[] | Buffer | Buffer[]'.
node_modules/@types/node/index.d.ts(2689,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'crl' must be of type 'any', but here has type 'string | string[]'.
node_modules/@types/node/index.d.ts(2691,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'honorCipherOrder' must be of type 'any', but here has type 'boolean'.
node_modules/@types/node/index.d.ts(2694,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'NPNProtocols' must be of type 'any', but here has type 'string[] | Buffer'.
node_modules/@types/node/index.d.ts(2711,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'key' must be of type 'string | Buffer', but here has type 'string | string[] | Buffer | Buffer[]'.
node_modules/@types/node/index.d.ts(2713,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'cert' must be of type 'string | Buffer', but here has type 'string | string[] | Buffer | Buffer[]'.
node_modules/@types/node/index.d.ts(2714,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'ca' must be of type '(string | Buffer)[]', but here has type 'string | Buffer | (string | Buffer)[]'.
node_modules/@types/node/index.d.ts(2953,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'padding' must be of type 'any', but here has type 'number'.
node_modules/@types/node/index.d.ts(2958,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'padding' must be of type 'any', but here has type 'number'.
node_modules/@types/node/index.d.ts(3216,5): error TS2309: An export assignment cannot be used in a module with other exported elements.
node_modules/@types/node/index.d.ts(3299,5): error TS2300: Duplicate identifier 'export='.
node_modules/@types/node/index.d.ts(3321,18): error TS2300: Duplicate identifier 'Domain'.
node_modules/@types/node/index.d.ts(3613,5): error TS2300: Duplicate identifier 'export='.
typings/globals/node/index.d.ts(78,6): error TS2300: Duplicate identifier 'BufferEncoding'.
typings/globals/node/index.d.ts(234,18): error TS2300: Duplicate identifier 'EventEmitter'.
typings/globals/node/index.d.ts(516,9): error TS2502: 'BuffType' is referenced directly or indirectly in its own type annotation.
typings/globals/node/index.d.ts(517,9): error TS2502: 'SlowBuffType' is referenced directly or indirectly in its own type annotation.
typings/globals/node/index.d.ts(518,26): error TS2300: Duplicate identifier 'Buffer'.
typings/globals/node/index.d.ts(518,50): error TS2300: Duplicate identifier 'SlowBuffer'.
typings/globals/node/index.d.ts(539,18): error TS2300: Duplicate identifier 'EventEmitter'.
typings/globals/node/index.d.ts(580,22): error TS2320: Interface 'Server' cannot simultaneously extend types 'EventEmitter' and 'Server'.
Named property 'addListener' of types 'EventEmitter' and 'Server' are not identical.
typings/globals/node/index.d.ts(580,22): error TS2320: Interface 'Server' cannot simultaneously extend types 'EventEmitter' and 'Server'.
Named property 'emit' of types 'EventEmitter' and 'Server' are not identical.
typings/globals/node/index.d.ts(580,22): error TS2320: Interface 'Server' cannot simultaneously extend types 'EventEmitter' and 'Server'.
Named property 'on' of types 'EventEmitter' and 'Server' are not identical.
typings/globals/node/index.d.ts(580,22): error TS2320: Interface 'Server' cannot simultaneously extend types 'EventEmitter' and 'Server'.
Named property 'once' of types 'EventEmitter' and 'Server' are not identical.
typings/globals/node/index.d.ts(580,22): error TS2320: Interface 'Server' cannot simultaneously extend types 'EventEmitter' and 'Server'.
Named property 'prependListener' of types 'EventEmitter' and 'Server' are not identical.
typings/globals/node/index.d.ts(580,22): error TS2320: Interface 'Server' cannot simultaneously extend types 'EventEmitter' and 'Server'.
Named property 'prependOnceListener' of types 'EventEmitter' and 'Server' are not identical.
typings/globals/node/index.d.ts(580,22): error TS2320: Interface 'Server' cannot simultaneously extend types 'EventEmitter' and 'Server'.
Named property 'removeListener' of types 'EventEmitter' and 'Server' are not identical.
typings/globals/node/index.d.ts(591,22): error TS2320: Interface 'ServerResponse' cannot simultaneously extend types 'EventEmitter' and 'Writable'.
Named property 'addListener' of types 'EventEmitter' and 'Writable' are not identical.
typings/globals/node/index.d.ts(591,22): error TS2320: Interface 'ServerResponse' cannot simultaneously extend types 'EventEmitter' and 'Writable'.
Named property 'emit' of types 'EventEmitter' and 'Writable' are not identical.
typings/globals/node/index.d.ts(591,22): error TS2320: Interface 'ServerResponse' cannot simultaneously extend types 'EventEmitter' and 'Writable'.
Named property 'on' of types 'EventEmitter' and 'Writable' are not identical.
typings/globals/node/index.d.ts(591,22): error TS2320: Interface 'ServerResponse' cannot simultaneously extend types 'EventEmitter' and 'Writable'.
Named property 'once' of types 'EventEmitter' and 'Writable' are not identical.
typings/globals/node/index.d.ts(591,22): error TS2320: Interface 'ServerResponse' cannot simultaneously extend types 'EventEmitter' and 'Writable'.
Named property 'prependListener' of types 'EventEmitter' and 'Writable' are not identical.
typings/globals/node/index.d.ts(591,22): error TS2320: Interface 'ServerResponse' cannot simultaneously extend types 'EventEmitter' and 'Writable'.
Named property 'prependOnceListener' of types 'EventEmitter' and 'Writable' are not identical.
typings/globals/node/index.d.ts(591,22): error TS2320: Interface 'ServerResponse' cannot simultaneously extend types 'EventEmitter' and 'Writable'.
Named property 'removeListener' of types 'EventEmitter' and 'Writable' are not identical.
typings/globals/node/index.d.ts(621,22): error TS2320: Interface 'ClientRequest' cannot simultaneously extend types 'EventEmitter' and 'Writable'.
Named property 'addListener' of types 'EventEmitter' and 'Writable' are not identical.
typings/globals/node/index.d.ts(621,22): error TS2320: Interface 'ClientRequest' cannot simultaneously extend types 'EventEmitter' and 'Writable'.
Named property 'emit' of types 'EventEmitter' and 'Writable' are not identical.
typings/globals/node/index.d.ts(621,22): error TS2320: Interface 'ClientRequest' cannot simultaneously extend types 'EventEmitter' and 'Writable'.
Named property 'on' of types 'EventEmitter' and 'Writable' are not identical.
typings/globals/node/index.d.ts(621,22): error TS2320: Interface 'ClientRequest' cannot simultaneously extend types 'EventEmitter' and 'Writable'.
Named property 'once' of types 'EventEmitter' and 'Writable' are not identical.
typings/globals/node/index.d.ts(621,22): error TS2320: Interface 'ClientRequest' cannot simultaneously extend types 'EventEmitter' and 'Writable'.
Named property 'prependListener' of types 'EventEmitter' and 'Writable' are not identical.
typings/globals/node/index.d.ts(621,22): error TS2320: Interface 'ClientRequest' cannot simultaneously extend types 'EventEmitter' and 'Writable'.
Named property 'prependOnceListener' of types 'EventEmitter' and 'Writable' are not identical.
typings/globals/node/index.d.ts(621,22): error TS2320: Interface 'ClientRequest' cannot simultaneously extend types 'EventEmitter' and 'Writable'.
Named property 'removeListener' of types 'EventEmitter' and 'Writable' are not identical.
typings/globals/node/index.d.ts(647,22): error TS2320: Interface 'IncomingMessage' cannot simultaneously extend types 'EventEmitter' and 'Readable'.
Named property 'addListener' of types 'EventEmitter' and 'Readable' are not identical.
typings/globals/node/index.d.ts(647,22): error TS2320: Interface 'IncomingMessage' cannot simultaneously extend types 'EventEmitter' and 'Readable'.
Named property 'emit' of types 'EventEmitter' and 'Readable' are not identical.
typings/globals/node/index.d.ts(647,22): error TS2320: Interface 'IncomingMessage' cannot simultaneously extend types 'EventEmitter' and 'Readable'.
Named property 'on' of types 'EventEmitter' and 'Readable' are not identical.
typings/globals/node/index.d.ts(647,22): error TS2320: Interface 'IncomingMessage' cannot simultaneously extend types 'EventEmitter' and 'Readable'.
Named property 'once' of types 'EventEmitter' and 'Readable' are not identical.
typings/globals/node/index.d.ts(647,22): error TS2320: Interface 'IncomingMessage' cannot simultaneously extend types 'EventEmitter' and 'Readable'.
Named property 'prependListener' of types 'EventEmitter' and 'Readable' are not identical.
typings/globals/node/index.d.ts(647,22): error TS2320: Interface 'IncomingMessage' cannot simultaneously extend types 'EventEmitter' and 'Readable'.
Named property 'prependOnceListener' of types 'EventEmitter' and 'Readable' are not identical.
typings/globals/node/index.d.ts(647,22): error TS2320: Interface 'IncomingMessage' cannot simultaneously extend types 'EventEmitter' and 'Readable'.
Named property 'removeListener' of types 'EventEmitter' and 'Readable' are not identical.
typings/globals/node/index.d.ts(698,18): error TS2300: Duplicate identifier 'Agent'.
typings/globals/node/index.d.ts(743,18): error TS2300: Duplicate identifier 'Worker'.
typings/globals/node/index.d.ts(1004,22): error TS2300: Duplicate identifier 'CompleterResult'.
typings/globals/node/index.d.ts(1044,18): error TS2300: Duplicate identifier 'Script'.
typings/globals/node/index.d.ts(1886,18): error TS2300: Duplicate identifier 'TLSSocket'.
typings/globals/node/index.d.ts(2343,5): error TS2300: Duplicate identifier 'export='.
typings/globals/node/index.d.ts(2365,18): error TS2300: Duplicate identifier 'Domain'.
typings/globals/node/index.d.ts(2625,5): error TS2300: Duplicate identifier 'export='.</p>
<p>Many thanks.</p>
| <p>It looks like you have the node typings in two places.</p>
<p>node_modules/@types/node/index.d.ts</p>
<p>typings/globals/node/index.d.ts</p>
|
dispatch_async ( queue, block) vs dispatch_async (queue) { block } <p>Is there any difference between these two snippets? In the first one, the block is inside the <code>dispatch</code> part. Tks </p>
<pre><code> dispatch_async(dispatch_get_main_queue(),{
//do something
})
dispatch_async(dispatch_get_main_queue()){
//do something
}
</code></pre>
| <p>No, there is no difference between these two blocks.</p>
<p>It is part of Swift's ability to accept closures provided as an argument after the function parentheses.</p>
<p><em>NB: This answer and its examples are written in Swift 3, but the syntax for Swift 2 should be similar.</em></p>
<p>Consider the following situation:</p>
<pre><code>func a(callback: (_ s: String) -> Void) {
callback(s: "hello there")
}
</code></pre>
<p>This function can be expressed as either, similar to your snippets:</p>
<pre><code>a(callback: { str in
print(str) // prints "hello there"
})
</code></pre>
<p>or</p>
<pre><code>a() { str in
print(str) // also prints "hello there"
}
</code></pre>
<p>Closures with similar behavior are seen in other functions/methods that require closures such as <code>autoreleasepool</code>, Dispatch and <code>URLConnection</code>. From a personal standpoint, I almost always use the first example as it is more readable.</p>
|
Resize UIImageView based on HTTP image response in Swift <p>I have an UIImageView in my story board and I am using SDWebImage to set image the property.</p>
<pre><code>imageView.sd_setImageWithURL(photoURL)
</code></pre>
<p>How could I update the UIImageView size to match this image that is coming as a response from a HTTP request?</p>
| <p>After you load the image into the imageView: </p>
<pre><code>var frame = imageView.frame
let imageSize = imageView.image.size
frame.size.width = imageSize.width
frame.size.height = imageSize.height
imageView.frame = frame
</code></pre>
|
get selected row Id from jquery datatable version 1.9.4 <p>Sorry this may be a duplicated question, but couldn't able to find the solution any where in the web as well as in StackOverflow</p>
<p><strong>Problem</strong> </p>
<p>I need to get the selected row id from jquery data table</p>
<p><strong>My code what I have tried</strong></p>
<pre><code>$.each($("#myDataTable").dataTable().fnGetNodes(), function (i, row) {
var id = $(this).attr("id");
console.log(id)
});
</code></pre>
<p>The selected TR has the class row_selected selected </p>
<blockquote>
<p>class="even row_selected selected"</p>
</blockquote>
<p>So I need to get the id of the selected row based on this selected class, please help in solving this issue</p>
| <p>Use <a href="http://legacy.datatables.net/ref" rel="nofollow"><code>$()</code></a> API method to perform a jQuery selector action on the table's <code>TR</code> elements. </p>
<p>For example:</p>
<pre class="lang-js prettyprint-override"><code>$("#myDataTable").dataTable().$("tr.selected").each(function(){
var id = $(this).attr("id");
console.log(id);
});
</code></pre>
|
SQLException: java.util.Date cannot be cast to java.sql.Time using hibernate <p>I have a object and I created it by using <strong>Hibernate Reverse Engineering Wizard</strong> and <strong>Hibernate Mapping Files and POJOs From Database</strong>.</p>
<p>In this case my table has a sql time field(<strong>reminder_time</strong>), but hibernate generated the field as java.util.Date field . </p>
<p>This is my table,</p>
<p><a href="http://i.stack.imgur.com/PRBCj.png" rel="nofollow"><img src="http://i.stack.imgur.com/PRBCj.png" alt="enter image description here"></a></p>
<p>The mentioned field is reminder_time.</p>
<p>This is my object,</p>
<pre><code>import java.util.Date;
public class Reminder implements java.io.Serializable {
private Integer idreminder;
private Patient patient;
private String remindAbout;
private Date reminderTime;
private Date reminderDate;
private boolean active;
private boolean repeat;
private Date dateCreated;
private Date lastUpdated;
public Reminder() {
}
public Reminder(Patient patient, String remindAbout, Date reminderTime, Date reminderDate, boolean active, boolean repeat, Date lastUpdated) {
this.patient = patient;
this.remindAbout = remindAbout;
this.reminderTime = reminderTime;
this.reminderDate = reminderDate;
this.active = active;
this.repeat = repeat;
this.lastUpdated = lastUpdated;
}
public Reminder(Patient patient, String remindAbout, Date reminderTime, Date reminderDate, boolean active, boolean repeat, Date dateCreated, Date lastUpdated) {
this.patient = patient;
this.remindAbout = remindAbout;
this.reminderTime = reminderTime;
this.reminderDate = reminderDate;
this.active = active;
this.repeat = repeat;
this.dateCreated = dateCreated;
this.lastUpdated = lastUpdated;
}
public Integer getIdreminder() {
return this.idreminder;
}
public void setIdreminder(Integer idreminder) {
this.idreminder = idreminder;
}
public Patient getPatient() {
return this.patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
public String getRemindAbout() {
return this.remindAbout;
}
public void setRemindAbout(String remindAbout) {
this.remindAbout = remindAbout;
}
public Date getReminderTime() {
return this.reminderTime;
}
public void setReminderTime(Date reminderTime) {
this.reminderTime = reminderTime;
}
public Date getReminderDate() {
return this.reminderDate;
}
public void setReminderDate(Date reminderDate) {
this.reminderDate = reminderDate;
}
public boolean isActive() {
return this.active;
}
public void setActive(boolean active) {
this.active = active;
}
public boolean isRepeat() {
return this.repeat;
}
public void setRepeat(boolean repeat) {
this.repeat = repeat;
}
public Date getDateCreated() {
return this.dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public Date getLastUpdated() {
return this.lastUpdated;
}
public void setLastUpdated(Date lastUpdated) {
this.lastUpdated = lastUpdated;
}
}
</code></pre>
<p>When I tried to save some data in to this table using above object, I got following exception,</p>
<pre><code>Oct 06, 2016 4:40:06 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'repeat, date_created, last_updated) values (3, 'Taking medicine', '15:30:18', '2' at line 1
org.hibernate.exception.SQLGrammarException: could not execute statement
</code></pre>
<p>Have any ideas about this ?</p>
| <p><code>repeat</code> is a <a href="http://dev.mysql.com/doc/refman/5.5/en/keywords.html" rel="nofollow">reserved keyword in MySQL</a> and needs to be escaped by backticks or use a different column name.</p>
|
How to send and receive multipart data in node.js? <p>Here is my HTML page where I want to send an image file and information about a TODO task and description.
<a href="http://pastebin.com/W9TVy4An" rel="nofollow">http://pastebin.com/W9TVy4An</a></p>
<pre><code>form.on('part', (part) => {
if (part.filename) {
let imagePath = ''
let privateIndex // will hold the index for private images
let index // will hold the index for the public images
let file = ''
part.setEncoding('binary')
part.on('data', (data) => {
file += data
})
part.on('end', () => {
if (isPrivate) {
// handle a private image
} else {
// handle a public image
}
if (!fs.existsSync(imagePath)) {
fs.mkdir(imagePath) // create the folder for the image
}
imagePath += isPrivate ? privateIndex + '.jpg' : index + '.jpg' // add the image name to complete the path for saving
fs.writeFile(imagePath, file, 'ascii', (err) => {
// stuff
}
})
callback(part.filename)
})
</code></pre>
<p>I know how to receive the file using multiparty in node.js as shown above but I cannot for the life of me receive the information about the description and name of a TODO task.</p>
<p>Can anybody tell me the way to do it or point out some stupid mistake I'm making?</p>
| <p>Okay, I figured out a way and it is to read the <code>fields</code> and <code>files</code> properties when parsing a form.</p>
<pre><code>let form = new multiparty.Form()
form.parse(req, (err, fields, files) => {
console.log(fields)
})
</code></pre>
<p>Fields is a object with the name of the attribute as a key and it's value as the value.
The result is</p>
<pre><code>{ todoname: [ 'Post the answer' ], tododesc: [ 'Post the answer you figured out on your StackOverflow question' ] }
</code></pre>
|
Spring Cloud Contract and plain Spring AMQP <p>We are using plain <a href="http://projects.spring.io/spring-amqp/" rel="nofollow">Spring AMQP</a> in our spring boot projects. </p>
<p>We want to make sure that our message consumers can test against real messages and avoid to test against static test messages. </p>
<p>Thus our producers could generate message snippets in a test phase that can be picked up by the consumer test to make sure it tests against the latest message version and see if changes in the producer break the consumer.</p>
<p>It seems like <a href="https://cloud.spring.io/spring-cloud-contract/" rel="nofollow">Spring Cloud Contract</a> does exactly that. So is there a way to integrate spring cloud contract with spring amqp? Any hints in which direction to go would be highly appreciated.</p>
| <p>Actually we don't support it out of the box but you can set it up yourself. In the autogenerated tests we're using an interface to receive and send messages so
you could implement your own class that uses spring-amqp. The same goes for the consumer side (the stub runner). What you would need to do is to implement and register a bean of
<code>org.springframework.cloud.contract.verifier.messaging.MessageVerifier</code> type for both producer and consumer. This should work cause what we're doing in the autogenerated tests is that we <code>@Inject MessageVerifier</code>
so if you register your own bean it will work.</p>
|
existing Cassandra 2.2.x cluster, changing the number of vNodes - will data be lost or not? <p>If the number of vNodes in the existing Cassandra 2.2.x cluster is changed - will it cause all the data in that cluster to be lost or not?<br>
Is it possible to change # of vNodes and keep all the data stored in the Cassandra cluster?</p>
| <p>The value in the config (cassandra.yaml) is only read on startup. Changing the value here will basically have no effect. You won't lose data.</p>
<p>There used to be a feature called shuffle - but it turned out you really don't want to change the token layout in this way, the streaming associated with shuffle will pretty much kill your cluster. </p>
<p>If you need to do this - the best method is to create a new DC with the desired token ranges and then rebuild them as per the instructions here:</p>
<p><a href="https://docs.datastax.com/en/cassandra/2.1/cassandra/operations/ops_add_dc_to_cluster_t.html" rel="nofollow">https://docs.datastax.com/en/cassandra/2.1/cassandra/operations/ops_add_dc_to_cluster_t.html</a></p>
<p>You can then point your app at the new DC and throw away the old.</p>
|
swift 3 equivalent for indexAtPosition, urlRequest.url!.isEqual <p>Hi i am getting following errors while upgrading from swift 2.2 to swift 3 </p>
<blockquote>
<p>Argument labels '(atPosition:)' do not match any available overloads"</p>
</blockquote>
<p>Below are the following code in swift 2.2.could you guys help me out.</p>
<pre><code>private func getIndexInTheLastSection(indexPath: NSIndexPath) -> Int? {
let index = indexPath.indexAtPosition(indexPath.length - 1)
if index == NSNotFound {
return nil
}
return index
}
</code></pre>
<p>////////////////</p>
| <p>For <code>isEqual</code> error with <code>URL</code> use <code>==</code> instead of <code>isEqual</code> to compare.</p>
<pre><code>if urlRequest.URL! == strongSelf.request?.urlRequest?.URL {
</code></pre>
<p>For error <code>Argument labels '(atPosition:)'</code> </p>
<pre><code>indexPath.index(atPosition: (indexPath as NSIndexPath).length - 1)
</code></pre>
|
SQLite3 - Why LEFT JOIN differs from other RDBMSes? <p>For example, two tables have has many (or has one) relation. Author and books. For example, we want to check if this an new author which doesn't have any books written.</p>
<pre><code>SELECT authors.id
FROM authors
LEFT JOIN books ON authors.id = books.author_id AND books.id IS NULL
</code></pre>
<p>This will work properly in any RDBMS: MySQL, PostgreSQL, SQL Server, maybe Oracle, but not in SQLite3. In SQLite3 the last part needs to be moved to <code>WHERE</code>:</p>
<pre><code>SELECT authors.id
FROM authors
LEFT JOIN books ON authors.id = books.author_id
WHERE books.id IS NULL
</code></pre>
<p>to work properly. Why?</p>
| <p>You are incorrect that the version with the condition in the <code>ON</code> clause does any filtering. For instance, <a href="http://www.sqlfiddle.com/#!9/afa7df/1" rel="nofollow">here</a> is a MySQL SQL Fiddle that shows that putting the condition in the <code>ON</code> clause returns two rows.</p>
<p>This is the correct way to get authors with no books, using <code>LEFT JOIN</code>:</p>
<pre><code>SELECT authors.id
FROM authors LEFT JOIN
books
ON authors.id = books.author_id
WHERE books.id IS NULL;
</code></pre>
<p>This filters out authors that have books, leaving the authors with no books. The logic of <code>LEFT JOIN</code> is simple: Keep all rows in the first table, regardless of whether the <code>ON</code> conditions evaluates to true, false, or <code>NULL</code>.</p>
<p>Putting the condition in the <code>ON</code> clause has a different logic. It will return <em>all</em> authors. There is no filtering.</p>
<p>I have a vague recollection that some versions of some databases have a bug where such a constant expression is treated as a filtering clause. However, that is not correct. What you think of as the "exception" is correct and should work in any database.</p>
|
SQL - date group by year, month, days - update <p>I used code to calculate difference between two date group by year, months, date:</p>
<pre><code>;WITH calendar AS (
SELECT CAST(MIN([From date]) as datetime) as d,
MAX([To date]) as e
FROM ItemTable
UNION ALL
SELECT DATEADD(day,1,d),
e
FROM calendar
WHERE d < e
), cte AS(
SELECT i.Item,
DATEPART(year,c.d) as [Year],
DATEDIFF(month,MIN(c.d),MAX(c.d)) as NoOfMonth,
DATEDIFF(day,DATEADD(month,DATEDIFF(month,MIN(c.d),MAX(c.d)),MIN(c.d)),
MAX(c.d)) as NoOfDays
FROM ItemTable i
INNER JOIN calendar c
ON c.d between i.[From date] and i.[To date]
GROUP BY i.Item, DATEPART(year,c.d),[From date],[To date]
)
SELECT Item,
[Year],
SUM(NoOfMonth) as NoOfMonth,
SUM(NoOfDays) as NoOfDays
FROM cte
GROUP BY Item,[Year]
ORDER BY Item
OPTION (MAXRECURSION 0)
</code></pre>
<p>I found this code in <a href="http://stackoverflow.com/questions/39872204/sql-date-group-by-year-month-days">SQL - date group by year, month, days</a></p>
<p>But not work for me...</p>
<p>When I execute my query </p>
<pre><code>SELECT Item,
[From date],
[To date]
from ItemDate;
</code></pre>
<p>I got </p>
<pre><code>('A1','2013-08-27','2013-09-27'),
('A1','2013-09-28','2013-11-28'),
('A1','2013-11-30','2013-12-03'),
('A1','2013-12-31','2014-03-31'),
('A1','2014-04-01','2014-07-01'),
('A1','2014-07-02','2014-10-02'),
('A1','2014-10-03','2014-12-31')
</code></pre>
<p>and when execute code from this link <a href="http://stackoverflow.com/questions/39872204/sql-date-group-by-year-month-days">SQL - date group by year, month, days</a></p>
<p>I get this:</p>
<pre><code> Item Year NoOfMonth NoOfDays
A1 2013 4 -27
A2 2014 10 58
</code></pre>
<p>This is not good.... It should be 3 months and 4 day for year 2013,
and for year 2014 11 month and 28 days</p>
<p>How to update the code to get the desired result?</p>
| <p>Change the last select to:</p>
<pre><code>SELECT Item,
[Year],
CASE WHEN SUM(NoOfDays) < 0 THEN SUM(NoOfMonth)-1
WHEN SUM(NoOfDays) > 30 THEN SUM(NoOfMonth)+1
ELSE SUM(NoOfMonth) END as NoOfMonth,
CASE WHEN SUM(NoOfDays) >= 30 THEN SUM(NoOfDays)-30
WHEN SUM(NoOfDays) < 0 THEN SUM(NoOfDays)+30
ELSE SUM(NoOfDays) END as NoOfDays
FROM cte
GROUP BY Item,[Year]
ORDER BY Item
OPTION (MAXRECURSION 0)
</code></pre>
<p>The main problem of such report - it is hard to define what is <strong>1 month</strong>, DATEDIFF just takes number from 2 dates and subtract one from another.</p>
<p>I have choose 30 as a days count in month, and now I compare values of days with 30 so we can add <code>+1</code> to month if the day count goes under zero or below 30</p>
|
ToggleClass - very basic <p>My toggle does not work.</p>
<pre><code><head>
<script src="js/jquery-2.2.3.min.js"></script>
<script src="js/functions.js"></script>
</head>
<body class="bkg-blue">...
</code></pre>
<p>In functions.js, I just have :</p>
<pre><code>$(document).ready(function(){
$('.logo').on('click',function(){
//alert("test"); > works fine
$("body").toggleClass("bkg-white");
});
});
</code></pre>
<p>My bkg-white class never appears on the body.</p>
| <p>In fact, I just removed the $(document).ready(function() at the beginning and it now works.</p>
|
How to get front camera, back camera and audio with AVCaptureDeviceDiscoverySession <p>Before iOS 10 came out I was using the following code to get the video and audio capture for my video recorder:</p>
<pre><code> for device in AVCaptureDevice.devices()
{
if (device as AnyObject).hasMediaType( AVMediaTypeAudio )
{
self.audioCapture = device as? AVCaptureDevice
}
else if (device as AnyObject).hasMediaType( AVMediaTypeVideo )
{
if (device as AnyObject).position == AVCaptureDevicePosition.back
{
self.backCameraVideoCapture = device as? AVCaptureDevice
}
else
{
self.frontCameraVideoCapture = device as? AVCaptureDevice
}
}
}
</code></pre>
<p>When iOS 10 finally came out, I received the following warning when I was running my code. Note that my video recorder was still working smoothly for about 2 weeks.</p>
<blockquote>
<p>'devices()' was deprecated in iOS 10.0: Use AVCaptureDeviceDiscoverySession instead.</p>
</blockquote>
<p>As I was running my code this morning, my video recorder stopped working. xCode8 does not give me any errors but the previewLayer for the camera capture is completely white. When I then start recording I receive the following error:</p>
<blockquote>
<p>Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed" UserInfo={NSLocalizedDescription=The operation could not be completed, NSUnderlyingError=0x17554440 {Error Domain=NSOSStatusErrorDomain Code=-12780 "(null)"}, NSLocalizedFailureReason=An unknown error occurred (-12780)}</p>
</blockquote>
<p>I believe that has something to do with the fact that I am using the deprecated approach <code>AVCaptureDevice.devices()</code>. Hence, I was wondering how to use <code>AVCaptureDeviceDiscoverySession</code> instead?</p>
<p>Thank you for your help in advance!</p>
| <p>You can get the front camera with the following:</p>
<pre><code>AVCaptureDevice.defaultDevice(withDeviceType: .builtInWideAngleCamera, mediaType: AVMediaTypeVideo, position: .front)
</code></pre>
<p>The back camera:</p>
<pre><code>AVCaptureDevice.defaultDevice(withDeviceType: .builtInWideAngleCamera, mediaType: AVMediaTypeVideo, position: .back)
</code></pre>
<p>And the microphone:</p>
<pre><code>AVCaptureDevice.defaultDevice(withDeviceType: .builtInMicrophone, mediaType: AVMediaTypeAudio, position: .unspecified)
</code></pre>
|
Connecting rounded squares <p>How do I create the div logo, as per the attached image below:</p>
<p><a href="http://i.stack.imgur.com/6om35.png"><img src="http://i.stack.imgur.com/6om35.png" alt="2 sets of connected round squares"></a></p>
<p>This is what I have created in <a href="https://jsfiddle.net/60jnk66d/16/">JsFiddle</a></p>
<p>Main issue is how do I connect the two boxes with the shape as below image, can anybody please suggest?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body,html {
width: 100%;
height: 100%;
margin: 0;
}
body {
background-color: #efefef;
}
.wrapper {
height: 40px;
width: 40px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -22.5px;
margin-left: -22.5px;
}
ul {
list-style-type: none;
margin: 0 auto;
padding: 0;
width: 80px;
height: 80px;
position: relative;
-moz-transform: rotate(45deg);
-ms-transform: rotate(45deg);
-webkit-transform: rotate(45deg);
transform: rotate(45deg);
}
ul li {
width: 2em;
height: 2em;
position: absolute;
/*animation: dance 888ms infinite alternate;
animation-timing-function: cubic-bezier(0.5, 0, 0.5, 1);*/
-moz-transform: rotate(45deg);
-ms-transform: rotate(45deg);
-webkit-transform: rotate(45deg);
transform: rotate(45deg);
animation: dance 888ms infinite alternate;
}
.block-1 {
top: 0;
left: 0;
background: #0076aa;
border-radius: 4px;
}
.block-2 {
top: 0;
right: 0;
background: #98bd81;
border-radius: 4px;
}
.block-3 {
bottom: 0;
right: 0;
background: #98bd81;
border-radius: 4px;
}
.block-4 {
bottom: 0;
left: 0;
background: #0076aa;
border-radius: 4px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='wrapper'>
<ul class='blocks'>
<li class='block-1'></li>
<li class='block-2'></li>
<li class='block-3'></li>
<li class='block-4'></li>
</ul>
</div></code></pre>
</div>
</div>
</p>
| <p>Considering the hassle of aligning and <a href="http://stackoverflow.com/questions/28986125/double-curved-shape">making double curves with <em>CSS</em></a>, this is clearly a job for SVG. The curves are much easier to create and control. Here is an example using :</p>
<ul>
<li>Inline SVG</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths#Bezier_Curves">quadratic bezier curves</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Basic_Transformations">transform</a></li>
<li>the <a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Element/use">use element</a> so there is only one occurrence of the path tag</li>
</ul>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>svg{ display:block; width:40%; margin:0 auto;}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg viewbox="0 0 16 15">
<defs>
<path id="shape" d="M7 0 H10 Q11 0 11 1 V4 Q11 5 10 5 H7 Q5 5 5 7 V9 Q5 10 4 10 H1 Q0 10 0 9 V6 Q0 5 1 5 H4 Q6 5 6 3 V1 Q6 0 7 0z" />
</defs>
<use xlink:href="#shape" fill="#0076AA"/>
<use xlink:href="#shape" fill="#98BD81" transform="translate(5,5)"/>
</svg></code></pre>
</div>
</div>
</p>
<p>With a loading animation :</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>svg{ display:block; width:40%; margin:0 auto;}
.sq{ animation: opacity .6s infinite alternate; }
.gr{ animation-delay:-.6s;}
@keyframes opacity { to {opacity: 0;} }</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg viewbox="0 0 16 15">
<defs>
<path id="shape" d="M7 0 H10 Q11 0 11 1 V4 Q11 5 10 5 H7 Q5 5 5 7 V9 Q5 10 4 10 H1 Q0 10 0 9 V6 Q0 5 1 5 H4 Q6 5 6 3 V1 Q6 0 7 0z" />
</defs>
<use class="sq bl" xlink:href="#shape" fill="#0076AA"/>
<use class="sq gr" xlink:href="#shape" fill="#98BD81" transform="translate(5,5)"/>
</svg></code></pre>
</div>
</div>
</p>
<p><em>Note that you will need to add vendor prefixes in the animation and that animations on svg elements aren't supported by IE/Edge.</em></p>
|
getting org.xml.sax.SAXParseException in web.xml on line <taglib> <p>I want to use jstl tag library, for that I have included tag in web.xml</p>
<p>but its showing following exception on starting apache tomcat server.</p>
<pre><code>SEVERE: Begin event threw exception
java.lang.IllegalArgumentException: taglib definition not consistent with specification version
at org.apache.catalina.startup.TaglibLocationRule.begin(WebRuleSet.java:1274)
at org.apache.tomcat.util.digester.Digester.startElement(Digester.java:1276)
......
Oct 06, 2016 4:31:04 PM org.apache.catalina.startup.ContextConfig parseWebXml
SEVERE: Parse error in application web.xml file at jndi:/localhost/SpringExceptionHandling/WEB-INF/web.xml
org.xml.sax.SAXParseException; systemId: jndi:/localhost/SpringExceptionHandling/WEB-INF/web.xml; lineNumber: 33; columnNumber: 13; Error at (33, 13) : taglib definition not consistent with specification version
at org.apache.tomcat.util.digester.Digester.createSAXException(Digester.java:2687)
Caused by: java.lang.IllegalArgumentException: taglib definition not consistent with specification version
at org.apache.catalina.startup.TaglibLocationRule.begin(WebRuleSet.java:1274)
at org.apache.tomcat.util.digester.Digester.startElement(Digester.java:1276)
...
</code></pre>
<p>its saying "<strong>taglib definition not consistent with specification version</strong>"
how to check version</p>
<p>..part of web.xml file</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-app_3_0.xsd"
version="3.0">
<taglib>
<taglib-uri>http://java.sun.com/jstl/core</taglib-uri>
<taglib-location>/WEB-INF/tld/c.tld</taglib-location>
</taglib>
</code></pre>
| <p>The xsi:schemaLocation - url "<a href="http://java.sun.com/xml/ns/j2ee" rel="nofollow">http://java.sun.com/xml/ns/j2ee</a> web-app_3_0.xsd" does not contain a schema .. Try "<a href="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" rel="nofollow">http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd</a>"</p>
|
How to subtract two days from a date in Java? <pre><code> String dateSample = "2016-09-30 21:59:22.2500000";
String oldFormat = "yyyy-MM-dd HH:mm:ss";
String newFormat = "MM-dd-yyyy";
SimpleDateFormat sdf1 = new SimpleDateFormat(oldFormat);
SimpleDateFormat sdf2 = new SimpleDateFormat(newFormat);
sdf2.format(sdf1.parse(dateSample));
</code></pre>
<p>From this, I got 09-30-2016
But, I want the result 09-28-2016
How to do it?</p>
| <pre><code>Calendar cal = GregorianCalendar.getInstance();
cal.setTime( sdf1.parse(dateSample));
cal.add( GregorianCalendar.DAY_OF_MONTH, -2); // date manipulation
System.out.println(sdf2.format(cal.getTime()));
</code></pre>
<p>Hope I helped</p>
|
How to undo and redo event in Javascript with browser compatible? <p>I am having a tshirt custom design software tool and have to add the redo and undo event for text which is draggable</p>
<p><a href="http://wordpress.tshirtecommerce.com/design-online/?product_id=17" rel="nofollow">http://wordpress.tshirtecommerce.com/design-online/?product_id=17</a></p>
<p>I have tried with undo manager plugin <a href="http://mattjmattj.github.io/simple-undo/" rel="nofollow">http://mattjmattj.github.io/simple-undo/</a> </p>
| <p>Here we are..</p>
<p>This is a simple example of doing an Undo & Redo buffer, and using a function closure to handle the redo..</p>
<p>This is of course a very simple example, so that it is hopefully easy too follow, but there is no reason this technique can't be used to undo/redo anything. Anything, you pass to a function closure can be captured, and then made to play back.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var e = {}; //lets store references to the dom elemements
Array.prototype.slice.call(document.querySelectorAll("[id]")).
forEach(function (el) { e[el.id] = el; });
var stack = [],
stackPos = 0,
names = [];
function showNames() {
e.lbNames.textContent = names.join(', ');
e.btUndo.disabled = stackPos <= 0;
e.btRedo.disabled = stackPos >= stack.length;
e.lbBuffer.textContent = stack.length;
}
btAdd.onclick = function () {
if (!ipName.value) return alert("Please enter some text");
//a function closure to capture the name
function add(name) {
return function () {
e.ipName.value = '';
e.ipName.focus();
names.push(name);
stackPos ++;
showNames();
}
}
//no need for closure here, as were just going to pop the
//last one of the names, and shift the undo-pos back
function undo() {
stackPos --;
names.pop();
showNames();
}
//now lets add our do & undo proc
var doadd = add(ipName.value);
stack.splice(stackPos);
stack.push({
do: doadd,
undo: undo
});
//lets now do our inital do
doadd();
};
btUndo.onclick = function () {
var p = stack[stackPos - 1];
p.undo();
};
btRedo.onclick = function () {
var p = stack[stackPos];
p.do();
};
showNames();</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><form onsubmit="return false">
name: <input id="ipName">
<br><br>
<button type="submit" id="btAdd" >Add</button>
<button id="btUndo">Undo</button>
<button id="btRedo">Redo</button>
Buffer = <span id="lbBuffer"></span>
<pre id="lbNames"></pre>
</form></code></pre>
</div>
</div>
</p>
|
MYSQL UPDATE and SET statements in PHP (500 error response) <p>I'm a newb, so thanks in advance for bearing with me. That being said, I'm trying to update a table in my database and failing. I received a few NULL responses, adjusted a few things, and most recently got a few 500 internal server errors, which typically seem to be related to invalid PHP... any help is greatly appreciated. </p>
<pre><code>if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($_POST['room']) {
$room_current = $conn->query('SELECT `Room_Availability` FROM Room_Status WHERE `Room_Name` = "'.$_POST['room'].'"');
if (!$room_current) {
die('ERROR: '.$conn->error);
}
$room_current = $room_current->fetch_assoc();
if ($room_current['Room_Availability'] == `OUT`); {
$room_set = $conn->query('UPDATE `Room_Status` SET `Room_Availability`= `IN` WHERE `Room_Name` = "'.$_POST['room'].'"');
if (!$room_set); {
die('ERROR: '.$conn->error);
}
}
var_dump($room_set);
?>
</code></pre>
| <p>This is your <code>UPDATE</code>:</p>
<pre><code>UPDATE `Room_Status`
SET `Room_Availability` = `IN`
WHERE `Room_Name` = "'.$_POST['room'].'"'
</code></pre>
<p>The backticks around <code>IN</code> mean that this is a column reference. You probably want a string, so use single quotes:</p>
<pre><code>UPDATE `Room_Status`
SET `Room_Availability` = 'IN'
WHERE `Room_Name` = "'.$_POST['room'].'"'
</code></pre>
|
Successfully installed azure toolkit for java plugin for eclipse but not showing any option âNew Azure Deployment Projectâ <p>I have successfully installed azure toolkit for java plugin for eclipse from <a href="http://dl.msopentech.com/eclipse" rel="nofollow">http://dl.msopentech.com/eclipse</a> via "install new software" option but not showing any option âNew Azure Deployment Projectâ or I am unable to create any Azure Deployment Project. I need this solution please help all. </p>
| <p>Per my experience, the following steps may be useful for you.</p>
<p>1.You should use a pure Eclipse Environment and you could get a pure eclipse from this URL <a href="http://www.eclipse.org/downloads/eclipse-packages/" rel="nofollow">http://www.eclipse.org/downloads/eclipse-packages/</a>.</p>
<p>2.You could click Help->Installation Details in order in your eclipse Env and then you could select Configuration pane.
After, you could click View Error Log to see whether there are some plug-in conflict error.
<a href="https://i.stack.imgur.com/4maJb.png" rel="nofollow"><img src="https://i.stack.imgur.com/4maJb.png" alt="enter image description here"></a>
3.You could get the Plug-in installed by the Eclipse Marketplace. Click Help->Eclipse Marketplace in order and then input word azure in the search bar. After, you could see the Azure Toolkit for Eclipse and you could click install button to install it.
<a href="https://i.stack.imgur.com/3tQeO.png" rel="nofollow"><img src="https://i.stack.imgur.com/3tQeO.png" alt="enter image description here"></a> </p>
<p>If you click the links more info->Learn more in order, you could see more infromation about the Azure Toolkit for Eclipse.
<a href="https://i.stack.imgur.com/3GD1i.png" rel="nofollow"><img src="https://i.stack.imgur.com/3GD1i.png" alt="enter image description here"></a>
Notice that:</p>
<p>You should restart your eclipse Env after getting the Azure Toolkit installed.</p>
<p>Hope it helps. Any concerns, please feel free to let me know.</p>
|
How to dump one database to another database using mysql? <p>i have tried the following query but i gate with an error.</p>
<pre><code>mysql> mysqldump test |mysql test1;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'mysqldump test |mysql test1' at line 1
mysql> mysqldump test |mysql test1
-> ;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'mysqldump test |mysql test1' at line 1
mysql>
</code></pre>
| <p>You have to use these commands on command prompt.</p>
<p><strong>Syntax :</strong> </p>
<pre><code>mysqldump --opt -u [uname] -p[pass] [dbname] > [backupfile.sql]
</code></pre>
<p>i.e.</p>
<pre><code>C:\>mysqldump --all-databases > dump.sql
</code></pre>
<p>If you want to create dump for any specific database then you have to mention that database name in the command.</p>
<pre><code>C:\>mysqldump --databases yourdb > dump.sql
</code></pre>
<p>To import the database you have to use following command,</p>
<pre><code>C:\>mysql -p -u[user] [database] < dump.sql
</code></pre>
|
Generate html document with images and text within python script (without servers if possible) <p>How can I generate HTML containing images and text, using a template and css, in python?</p>
<p>There are few similar questions on stackoverflow (e.g.: <a href="http://stackoverflow.com/questions/6748559/generating-html-documents-in-python">Q1</a>, <a href="http://stackoverflow.com/questions/98135/how-do-i-use-django-templates-without-the-rest-of-django">Q2</a>, <a href="http://stackoverflow.com/questions/16523939/how-to-write-and-save-html-file-in-python">Q3</a>) but they offer solutions that (to me) seem overkill, like requiring servers (e.g. genshi).</p>
<p>Simple code using <code>django</code> would be as follows:</p>
<pre><code>from django.template import Template, Context
from django.conf import settings
settings.configure() # We have to do this to use django templates standalone - see
# http://stackoverflow.com/questions/98135/how-do-i-use-django-templates-without-the-rest-of-django
# Our template. Could just as easily be stored in a separate file
template = """
<html>
<head>
<title>Template {{ title }}</title>
</head>
<body>
Body with {{ mystring }}.
</body>
</html>
"""
t = Template(template)
c = Context({"title": "title from code",
"mystring":"string from code"})
print t.render(c)
</code></pre>
<p>(From here: <a href="http://stackoverflow.com/questions/6748559/generating-html-documents-in-python">Generating HTML documents in python</a>)</p>
<p>This code produces an error, supposedly because I need to set up a backend:</p>
<pre><code>Traceback (most recent call last):
File "<input>", line 17, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/template/base.py", line 184, in __init__
engine = Engine.get_default()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/template/engine.py", line 81, in get_default
"No DjangoTemplates backend is configured.")
django.core.exceptions.ImproperlyConfigured: No DjangoTemplates backend is configured.
</code></pre>
<p>Is there a simple way to have a template.html and style.css and a bunch of images, and use data in a python script to replace placeholders in the template.html without having to set up a server?</p>
| <p>There are quite a few python template engines - for a start you may want to have a look here : <a href="https://wiki.python.org/moin/Templating" rel="nofollow">https://wiki.python.org/moin/Templating</a></p>
<p>As far as I'm concerned I'd use jinja2 but YMMV.</p>
|
How to set Windows application ToolstripMenuItems Text Foreground Color Change When Hover Mouse in C# <p>Windows application ToolstripMenuItems Text Foreground Color Change When Hover Mouse in C#</p>
<p><img src="http://i.stack.imgur.com/OHKLf.png" alt="My ToolStripMenuItems .Click Here to Show"></p>
| <p>Use the MouseEnter and MouseLeave event as follows:</p>
<pre><code> private void helpToolStripMenuItem_MouseEnter(object sender, EventArgs e)
{
helpToolStripMenuItem.ForeColor = Color.Green;
}
private void helpToolStripMenuItem_MouseLeave(object sender, EventArgs e)
{
helpToolStripMenuItem.ForeColor = Color.Black;
}
</code></pre>
|
Run a bash script on a remote server <p>I am developing an application which would require me to execute a bash script on a remote server when my users give me a command through a web interface.</p>
<p>What would be some ways to run a bash script on a remote server when I get a command on my main application server?</p>
<p>P.S. The bash script will need to do some tasks which only a root user can do, like, restart NGINX.</p>
| <p>Take a look at this:</p>
<p>Let us say you have 2 servers, A and B. You want to run a bash script on B, when you get a command on A.</p>
<p>In order to make it work, we may want to setup auto-ssh between 2 server. Otherwise, it would require manual intervention, of entering password, each time.</p>
<pre><code># Setting up auto ssh from A to B. Execute below commands from Server A.
cat ~/.ssh/id_pub.rsa | ssh user_of_B@IP_of_B ">> ~/.ssh/authorized_keys"
ssh user_ofB@IP_of_B "chmod 640 ~/.ssh/authorized_keys ; chmod 700 ~/.ssh"
</code></pre>
<p>Above step assumes that your server A has proper directory permissions setup and server B has standard SSH configuration (which allows for auto ssh to be configured and used ["PubKeyAuthentication yes"]</p>
<p>Since you have not mentioned, how you are going to process the command on A, i will assume that you have a logfile and we can read from logfile to invoke a script on A, which will invoke a script on B.</p>
<p>Here is my uname -a and hostname, for reference. For now, this is our server A.</p>
<pre><code>bash$> uname -a
Linux STATION.84station.com 3.10.0-327.36.1.el7.x86_64 #1 SMP Sun Sep 18 13:04:29 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
bash$> hostname
STATION.84station.com
bash$>
</code></pre>
<p>Now the second part, to to parse incoming log and take action.</p>
<pre><code># Reading logfile on A, invoke a script on A to invoke a script on server B.
bash$> tail -f logfile |perl -nle 'if (m/2559/) {system("./a.sh")} '
SunOS solaris 5.10 Generic_147148-26 i86pc i386 i86pc
lo0: flags=2001000849<UP,LOOPBACK,RUNNING,MULTICAST,IPv4,VIRTUAL> mtu 8232 index 1
inet 127.0.0.1 netmask ff000000
e1000g0: flags=1004843<UP,BROADCAST,RUNNING,MULTICAST,DHCP,IPv4> mtu 1500 index 2
inet 192.168.2.135 netmask ffffff00 broadcast 192.168.2.255
-rwxr-xr-x 1 gaurav other 53 Oct 6 21:04 /export/home/b.sh
^C
bash$>
</code></pre>
<p>On Server A, the logfile is read, fed to a perl filter, which is looking for keyword "2559" and as soon as it matches it, it invokes the script on A, i.e "a.sh" which logs on to B and executes script "b.sh" on B, and its output is seen on A. You can put another script inside "b.sh" to execute something else or whatever you want.</p>
<p>Here is the a.sh on A, which invokes b.sh on B.</p>
<pre><code>bash$> cat a.sh
#!/bin/bash
ssh gaurav@192.168.2.135 "
uname -a
echo
/usr/sbin/ifconfig -a
echo
ls -lrtha /export/home/b.sh
"
bash$>
</code></pre>
<p>You can put your commands in between quotes as shown above.</p>
<p>So this is one way we can do the desired operation. Cheers!</p>
|
Object to Objects mapper with differing names <p>I have a legacy application which contains a Class called <code>CustomerInvoice</code>. I need to relate these items to database tables which have less than friendly names (for example there is <code>CUSTOMER_INV_HEAD</code>, <code>CUST_INV_LINES</code>, <code>CUST_INV_POSTS</code>, and potentially many others).</p>
<p>First attempt was inheriting interfaces for the internal names and then use getters and setters to place the correct data in respective tables, the issue here is that the logic lives in the wrong layer of my application, and it all needs to be public which is not desirable - nevermind the maintenance aspect!</p>
<p>I have read lots about ORM and thought that AutoMapper may work but most of the examples that I have seen demonstrate where the names either side are the same. I also reviewed NHibernate which seems similar.</p>
<p>I need to do something like this:</p>
<pre><code>public class CustomerInvoice
{
public string id; // lives in CUSTOMER_INV_HEAD
public decimal netTotal; // lives in CUSTOMER_INV_HEAD called NET_INV_TOTAL
public IEnumerable<InvoiceLine> Lines; // collection of CUST_INV_LINES but including the id
}
</code></pre>
<p>So what i need to be able to do is say...</p>
<pre><code>List<CUST_INV_LINES> l = Map<CustomerInvoice.Lines, CUST_INV_LINES>();
</code></pre>
<p>But how can i define that relationship in a clever, maintainable way without hand coding the relationships in special methods?</p>
| <p>You can add Attributes to your class properties to give their underlying database names. This is the approach taken by the frameworks XML serializer. You then only need one "special method" to extract the database name attribute from the property of a class, via reflection. Note on the following example link the override of the property name with an XML Element name - you could do the same thing for your database mappable properties with your own custom attribute.</p>
<p><a href="https://msdn.microsoft.com/en-us/library/2baksw0z(v=vs.110).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/2baksw0z(v=vs.110).aspx</a></p>
|
Sinatra on Rails 5 <p>I have problems adding sinatra as rack middleware for rails 5. The issue is that once I add <code>gem "sinatra"</code> to Rails Gemfile I cannot get the server running. But <code>bundle install</code> still finishes without errors. Could someone please explain to me how to add a (middleware) Sinatra App on Rails 5?</p>
| <p>Rails will automatically <code>require</code> all gems in the gemfile, which is not ideal when using Sinatra as a middleware. This is documented on the Sinatra website <a href="http://www.sinatrarb.com/intro.html#Sinatra::Base%20-%20Middleware,%20Libraries,%20and%20Modular%20Apps" rel="nofollow">here</a>.</p>
<p>A workaround to this is changing your Gemfile to say <code>gem "sinatra", :require => false</code> then adding <code>require "sinatra/base"</code> to your app where it is needed.</p>
|
Play 2.5: Depedency injection in templates <p>I am trying to deal with dependency injected objects in Scala template (I am using Java-based Play 2.5). </p>
<p>I have a system of templates, where I have layout template with minimal HTML base and that one is included by almost all other HTML templates which are constructing the rest of the HTML body.</p>
<p>In the template, I am also including top menu with the "Logout" button and also there is a name of currently logged user.</p>
<p>I have a singleton object called LocalAuthenticator which is delivering the User object containing username. So far I was using dependency injection using helper Scala object like this</p>
<pre><code>object LocalAuthenticator {
private val cache = Application.instanceCache[core.security.LocalAuthenticator]
object Implicits {
implicit def localAuth(implicit application: Application): core.security.LocalAuthenticator = cache(application) }
}
</code></pre>
<p>Then I was able to access LocalAuthenticator from template using this construct</p>
<pre><code>@import play.api.Play.current
@import scala.LocalAuthenticator.Implicits._
Logged in user is: @localAuth.getCurrentUser().name
</code></pre>
<p>This was working in 2.4, however 2.5 is complaining about <code>play.api.Play.current</code> to be deprecated as it uses static context.</p>
<p>I know that the correct approach is to inject LocalAuthenticator to Controller and pass it to template, however this object should be present in all templates and it is very annoying to inject it to every controller.</p>
<p>Is there any way how to inject a singleton class into template directly?</p>
<p>I was trying to get injector in helper object in order to get singleton, but that could be done only if I have Play <code>Application</code> object. And that could be retrieved only using DI. So I am running in circles :-)</p>
| <p>I think you can try to use ActionBuilder + implicit parameters on view to achieve your requirement. (My answer is based on the link on my comment).</p>
<p>First you need to define an ActionBuild that extract the current user from database or from session object field on request and add it to a subtype of WrappedRequest. </p>
<pre><code>//The subtype of WrapperRequest which now contains the username.
class UserRequest[A](val username: Option[String], request: Request[A]) extends WrappedRequest[A](request)
object UserAction extends
ActionBuilder[UserRequest] with ActionTransformer[Request, UserRequest] {
def transform[A](request: Request[A]) = Future.successful {
//request.session.get("username") in this example is the code to get the current user
//you can do db access here or other means.
new UserRequest(request.session.get("username"), request)
}
}
</code></pre>
<p>On you view you will define an implicit parameter of type UserRequest:</p>
<pre><code>(message: String)(implicit h: UserRequest[AnyContent])
@main("Welcome to Play") {
//DISPLAY h.username
@h.username
}
</code></pre>
<p>Lastly, on your Controller define a requestHandler that uses UserAction which implicify it's request object.</p>
<pre><code>// implicit user: UserRequest does the magic
def index = UserAction { implicit user: UserRequest[AnyContent] =>
Ok(views.html.index("Not Yet Implemented."))
}
</code></pre>
<p>Hope that's help. </p>
<p>More on ActionBuilder: <a href="https://www.playframework.com/documentation/2.5.x/ScalaActionsComposition" rel="nofollow">https://www.playframework.com/documentation/2.5.x/ScalaActionsComposition</a></p>
|
Easiest way to show differently styled buttons <p>I want to modernize an old VCL application based on a design template. That design template contains different button styles. Let's say there are three types of buttons: <code>LightButton</code>, <code>DarkButton</code> and <code>GreenButton</code>. </p>
<p>Since more than 50% of all buttons will appear as <code>DarkButton</code> I modified the appearance of <code>TButton</code> to the dark design using the <a href="http://docwiki.embarcadero.com/RADStudio/Seattle/en/Bitmap_Style_Designer" rel="nofollow">Bitmap Style Designer</a>. </p>
<p><strong>Now I want to add the other button styles to the <code>.vsf</code> file and use it in my application. What is the best way to do it?</strong></p>
<p>Do I need to create new button classes and new descendants of <code>TStyleHook</code> which paint entirely new buttons? If yes, is there a way to reuse as much code as possbile from <code>Vcl.StdCtrls.TButtonStyleHook</code>? </p>
<p>Are there any other approaches, best practices or examples?</p>
| <p><strong>Q</strong> : Now I want to add the other button styles to the .vsf file and use it in my application. What is the best way to do it?</p>
<p><strong>A</strong> : The VCL Styles internals doesn't allow to use more than one button style from the vsf file. (The images inside of the VCL Styles files are used to mimic and replace the <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/bb773210(v=vs.85).aspx">Windows Themes states and parts</a>).</p>
<hr>
<p><strong>Q</strong> : Do I need to create new button classes and new descendants of TStyleHook which paint entirely new buttons?</p>
<p><strong>A</strong> : Yes that is the way, you must create a new styleHook to paint the buttons your self.</p>
<hr>
<p><strong>Q</strong> : Is there a way to reuse as much code as possible from Vcl.StdCtrls.TButtonStyleHook?</p>
<p><strong>A</strong> : Yes, You only need to inherit your <em>style hook</em> from the <code>TButtonStyleHook</code> class and then override the <code>Paint</code> method.</p>
<pre><code> TNewButtonStyleHook = class(TButtonStyleHook)
protected
procedure Paint(Canvas: TCanvas); override;
end;
</code></pre>
<hr>
<p><strong>Q</strong> : Are there any other approaches, best practices or examples?</p>
<p><strong>A</strong> : Try these samples of custom TButton Style Hooks.</p>
<ul>
<li><a href="https://theroadtodelphi.com/2012/02/26/fixing-a-vcl-style-bug-in-the-tbutton-component/">Fixing a VCL Style bug in the TButton component</a> </li>
<li><a href="http://stackoverflow.com/a/9586702/91299">Disabling TButton issue on a VCL styled form</a> </li>
</ul>
<hr>
|
Remove specific characters in filename <p>Is there any easy solution how to trim suffix in my filename? Problem is, that my suffix length is vary. Only the same string in filename is _L001.</p>
<p>See the example:</p>
<pre><code>NAME-code_code2_L001_sufix
NAME-code_L001_sufix_sufix2_sufix3
NAME-code_code2_code3_L001_sufix_sufix2_sufix3
</code></pre>
<p>I need to output everything before _L001:</p>
<pre><code>NAME-code_code2
NAME-code
NAME-code_code2_code3
</code></pre>
<p>I was thinking do something like this (when suffix is fixed length):</p>
<pre><code>echo NAME-code_code2_L001_sufix | rev | cut -c 12- | rev
</code></pre>
<p>But of course my suffix length is vary. Is there any bash or awk solution?</p>
<p>Thank you.</p>
| <p>Using pure string manipulation technique:-</p>
<pre><code>$ string="NAME-code_code2_L001_sufix"; printf "%s\n" "${string%_L001*}"
NAME-code_code2
</code></pre>
<p>For all the lines int the file, you can do the same by <code>bash</code>, by reading the file in-memory and performing the extraction</p>
<pre><code># Setting a variable to the contents of a file using 'command-substitution'
$ mystringfile="$(<stringfile)"
# Read the new-line de-limited string into a bash-array for per-element operation
$ IFS=$'\n' read -d '' -ra inputArray <<< "$mystringfile"
# Run the sub-string extraction for each entry in the array
$ for eachString in "${inputArray[@]}"; do printf "%s\n" "${eachString%_L001*}"; done
NAME-code_code2
NAME-code
NAME-code_code2_code3
</code></pre>
<p>You can write the contents to a new-file by modifying the <code>printf</code> in the for loop as</p>
<pre><code>printf "%s\n" "${eachString%_L001*}" >> output-file
</code></pre>
|
How to choose object from list and print its name <p>I have class Something with few objects:</p>
<pre><code>class Something():
def __init__(self, name, attr1, attr2):
self.name= name
self.attr1= attr1
self.attr2= attr2
def getName(self):
return self.name
Obj1=Something('Name1', 'bla bla1', 'bla bla2')
Obj2=Something('Name2', 'bla bla3', 'bla bla4')
</code></pre>
<p>Those objects are stored in list:</p>
<pre><code>objects = [Obj1, Obj2]
</code></pre>
<p>I want to select object from the printed list and then (if object is on the list) print its name.
So far I wrote code below, but it doesn't work. with error (AttributeError: 'str' object has no attribute 'getNazwa')</p>
<pre><code>print('Select object from list: ', objects)
y=raw_input('enter the name of the object')
for i in objects:
if y == i:
print "Name: " + i.getName()
</code></pre>
<p>When print list it's someting like that:</p>
<pre><code>('Select object fromfrom list: ', [<__main__.Something instance at 0x024FB440>, <__main__.Something instance at 0x024FB490>])
</code></pre>
<p>How to convert it into print objects name?</p>
<p>I guess that solution isn't rocket science for You Guys, so someone will help me ;)</p>
| <p>Thing is that you compare string to an object here:</p>
<pre><code>if y == i:
</code></pre>
<p>so you should either look at <code>__eq__</code> method of your class, or compare input string with obj name like:</p>
<pre><code>if y == i.getName()
</code></pre>
|
css, lines dashing vertically through bullets <p>This may sound stupid, But I am on edge here. Does anyone knows how to do this in css or javascript? (preferably css)</p>
<p><img src="http://i.stack.imgur.com/wHEML.png" alt="enter image description here"></p>
| <p>You could try this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
font-family: Helvetica, Arial, sans-serif;
font-size: 12px;
}
.section_header {
background-color: #7e9489;
border-radius: 20px;
width: 200px;
height: 20px;
color: #fff;
text-align: center;
padding: 10px;
line-height: 20px;
}
.section_content {
margin: 0px;
padding: 0px;
display: block;
border-left: solid 2px #7e9489;
margin-left: 99px;
padding-top: 10px;
}
.section_content > li {
display: block;
position: relative;
line-height: 40px;
}
.section_content > li::before {
position: relative;
display: inline-block;
vertical-align: middle;
content: '';
width: 12px;
height: 12px;
border-radius: 10px;
background-color: #7e9489;
margin-left: -7px;
margin-right: 20px;
z-index: 10;
}
.section_content > li > span {
display: inline-block;
vertical-align: middle;
}
.section_content > li:last-child::after {
content: '';
display: block;
position: absolute;
bottom: 0px;
left: -2px;
width: 2px;
height: 50%;
background-color: white;
z-index: 1;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="section_header">OCT 5, 2016</div>
<ul class="section_content">
<li><span>Segment 1</span></li>
<li><span>Segment 2</span></li>
<li><span>Segment 3</span></li>
<li><span>Segment 4</span></li>
</ul></code></pre>
</div>
</div>
</p>
|
Can I change numerous HTML elements using an array in Javascript? <p>I want to change the contents of two HTML elements simultaneously when a user clicks on a button. What the contents of the elements changes to is based on a random number which will then access arrays defined within the function.</p>
<p>That's what I want to happen, but currently I'm not getting any change when I click on the button (which calls the 'deal()' function).</p>
<p>Can anyone give me any advice?</p>
<p>Here's my code - </p>
<pre><code>function createCard(){
var shuffle = Math.floor(Math.random()*2) +1;
var title = document.getElementById("cardTitle");
var text = document.getElementById('cardText');
var button = document.getElementById('cardButton');
var cardTitle = ["Bacon", "Hot Dog Lattice"];
var cardText = ['Frabdious Day', 'Calee, Calay',];
var cardId = [cardTitle, cardText];
switch (shuffle) {
case 1:
title.innerHTML = cardId(cardTitle[0]);
text.innerHTML = cardId(cardText[0]);
break;
case 2:
title.innerHTML = cardId(cardTitle[1]);
text.innerHTML = cardId(cardText[1]);
break;
default:
title.innerHTML = "Oops";
text.innerHTML = "Whoopsie";
break;
}
}
function deal(){
createCard();
}
</code></pre>
| <p>This might work out as a better solution:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function createCard(){
var shuffle = Math.floor(Math.random()*2);
var cards = [
{
title: "Bacon",
text: "Frabdious Day"
},
{
title: "Hot Dog Lattice",
text: "Calee, Calay"
}
];
var shuffledCard = cards[shuffle];
if (!shuffledCard){
shuffledCard = {
title: "Oops",
text: "Whoopsie"
}
}
var title = document.getElementById("cardTitle");
var text = document.getElementById('cardText');
var button = document.getElementById('cardButton');
title.innerHTML = shuffledCard.title;
text.innerHTML = shuffledCard.text;
}
function deal(){
createCard();
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="cardTitle">Start value</div>
<div id="cardText">Start value</div>
<button id="cardButton" onClick="deal()">Deal</button></code></pre>
</div>
</div>
</p>
|
Select from table <p>select records from table using like for loop in postgres
where user given value less than particular column value then stop loop
else select next record based on remaining value</p>
<p>ex:</p>
<pre><code>NO: value:
inv1 5
inv2 20
inv3 30
</code></pre>
<p>user given value 23 means </p>
<p>No: value: selectedvalue</p>
<pre><code>inv1 5 5
inv2 20 18
</code></pre>
| <p>You are looking for a cumulative sum and some additional logic:</p>
<pre><code>select t.*,
(case when cume_value < 23 then value
else cume_value - value
end)
from (select t.*,
sum(value) over (order by ??) as cume_value
from t
) t
where cume_value < 23;
</code></pre>
<p>The <code>??</code> represents the column you are using for ordering the rows in the table. SQL tables represent unordered sets so you need an ordering column. In your case, this might be <code>value</code>.</p>
|
2D Orthogonal projection of vector onto line with numpy yields wrong result <p>I have 350 document scores that, when I plot them, have this shape:</p>
<pre><code>docScores = [(0, 68.62998962), (1, 60.21374512), (2, 54.72480392),
(3, 50.71389389), (4, 49.39723969), ...,
(345, 28.3756237), (346, 28.37126923),
(347, 28.36397934), (348, 28.35762787), (349, 28.34219933)]
</code></pre>
<p>I posted the complete array <a href="http://pastebin.com/JeW3kJf4" rel="nofollow">here</a> on <code>pastebin</code> (it corresponds to the <code>dataPoints</code> list on the code below).</p>
<p><a href="http://i.stack.imgur.com/BAeDE.png" rel="nofollow"><img src="http://i.stack.imgur.com/BAeDE.png" alt="Score distribution"></a></p>
<p>Now, I originally needed to find the <code>elbow point</code> of this <code>L-shape</code> curve, which I found thanks to <a href="http://stackoverflow.com/questions/2018178/finding-the-best-trade-off-point-on-a-curve">this post</a>.</p>
<p>Now, on the following plot, the red vector <code>p</code> represents the elbow point. I would like to find the point <code>x=(?,?)</code> (the yellow star) on the vector <code>b</code> which corresponds to the orthogonal projection of <code>p</code> onto <code>b</code>. </p>
<p><a href="http://i.stack.imgur.com/f1Kju.png" rel="nofollow"><img src="http://i.stack.imgur.com/f1Kju.png" alt="enter image description here"></a></p>
<p>The red point on the plot is the one I obtain (which is obviously wrong). I obtain it doing the following:</p>
<pre><code>b_hat = b / np.linalg.norm(b) #unit vector of b
proj_p_onto_b = p.dot(b_hat)*b_hat
red_point = proj_p_onto_b + s
</code></pre>
<p>Now, if the projection of <code>p</code> onto <code>b</code> is defined by the its starting and ending point, namely <code>s</code> and <code>x</code> (the yellow star), it follows that <code>proj_p_onto_b = x - s</code>, therefore <code>x = proj_p_onto_b + s</code> ?</p>
<p>Did I make a mistake here ?</p>
<p><strong>EDIT :</strong> In answer to @cxw, here is the code for computing the elbow point :</p>
<pre><code>def findElbowPoint(self, rawDocScores):
dataPoints = zip(range(0, len(rawDocScores)), rawDocScores)
s = np.array(dataPoints[0])
l = np.array(dataPoints[len(dataPoints)-1])
b_vect = l-s
b_hat = b_vect/np.linalg.norm(b_vect)
distances = []
for scoreVec in dataPoints[1:]:
p = np.array(scoreVec) - s
proj = p.dot(b_hat)*b_hat
d = abs(np.linalg.norm(p - proj)) # orthgonal distance between b and the L-curve
distances.append((scoreVec[0], scoreVec[1], proj, d))
elbow_x = max(distances, key=itemgetter(3))[0]
elbow_y = max(distances, key=itemgetter(3))[1]
proj = max(distances, key=itemgetter(3))[2]
max_distance = max(distances, key=itemgetter(3))[3]
red_point = proj + s
</code></pre>
<p><strong>EDIT</strong> : Here is the code for the plot :</p>
<pre><code>>>> l_curve_x_values = [x[0] for x in docScores]
>>> l_curve_y_values = [x[1] for x in docScores]
>>> b_line_x_values = [x[0] for x in docScores]
>>> b_line_y_values = np.linspace(s[1], l[1], len(docScores))
>>> p_line_x_values = l_curve_x_values[:elbow_x]
>>> p_line_y_values = np.linspace(s[1], elbow_y, elbow_x)
>>> plt.plot(l_curve_x_values, l_curve_y_values, b_line_x_values, b_line_y_values, p_line_x_values, p_line_y_values)
>>> red_point = proj + s
>>> plt.plot(red_point[0], red_point[1], 'ro')
>>> plt.show()
</code></pre>
| <p>If you are using the plot to visually determine if the solution looks correct, you must plot the data using the same scale on each axis, i.e. use <code>plt.axis('equal')</code>. If the axes do not have equal scales, the angles between lines are distorted in the plot.</p>
|
Primefaces p:messages won't show first FacesMessage <p><strong>Prerequisites</strong>:<br>
- JSF 2.1<br>
- Primefaces 5.2<br>
- Glassfish 3.1 </p>
<p><strong>Story</strong>:<br>
I've created a p:dialog used for displaying FacesMessages on a p:messages element. This dialog is needed, because the user has to commit specific FacesMessages with an "OK"-Button before proceeding.</p>
<p><em>Dialog</em>: </p>
<pre><code><p:outputPanel id="modalMessage">
<p:dialog id="dlgMessageDialog" dynamic="true" style="z-index: 100"
closable="false" widgetVar="wigVarMessageDialog" modal="true"
appendTo="@(body)">
<f:facet name="header">
<h:outputText id="messageDialogHeader"
value="#{messageDialogBean.header}" />
</f:facet>
<p:outputPanel id="modalMessagePanel">
<h:form id="messageForm" enctype="multipart/form-data">
<p:messages id="messages" escape="false" closable="false"
showDetail="true" autoUpdate="true"
for="#{messageDialogBean.messageDialogId}"></p:messages>
<p:spacer height="20px"></p:spacer>
<p:commandButton value="#{msg.btnOk}"
oncomplete="PF('wigVarMessageDialog').hide()" />
</h:form>
</p:outputPanel>
</p:dialog>
</p:outputPanel>
</code></pre>
<p><em>Bean</em>: </p>
<pre><code>@Named("messageDialogBean")
@SessionScoped
public class MessageDialogBean implements Serializable {
private static final long serialVersionUID = 1L;
private final String messageDialogId = "messageDialogId";
private FacesMessage message = new FacesMessage();
private String header = "test";
public void showMessage(final String pHeader, final FacesMessage pMessage) {
if (pMessage != null) {
setHeader(pHeader);
this.message = pMessage;
show();
}
}
public void showWarn(final String pHeader, final String pSummary, final String pDetail) {
setHeader(pHeader);
this.message = new FacesMessage(FacesMessage.SEVERITY_WARN, pSummary, pDetail);
show();
}
public void showInfo(final String pHeader, final String pSummary, final String pDetail) {
setHeader(pHeader);
this.message = new FacesMessage(FacesMessage.SEVERITY_INFO, pSummary, pDetail);
show();
}
public void showError(final String pHeader, final String pSummary, final String pDetail) {
setHeader(pHeader);
this.message = new FacesMessage(FacesMessage.SEVERITY_ERROR, pSummary, pDetail);
show();
}
public void updateDialog() {
RequestContext context = RequestContext.getCurrentInstance();
context.update("mainForm:messageDialogHeader");
}
private void show() {
updateDialog();
RequestContext context = RequestContext.getCurrentInstance();
context.execute("PF('wigVarMessageDialog').show();");
FacesContext.getCurrentInstance().addMessage(this.messageDialogId, this.message);
}
public String getMessageDialogId() {
return this.messageDialogId;
}
public void setHeader(final String pHeader) {
this.header = pHeader;
}
public String getHeader() {
return this.header;
}
public FacesMessage getLastMessage() {
return this.message;
}
}
</code></pre>
<p><em>One of the messages which have to be commited</em>: </p>
<pre><code>this.messageDialogBean.showInfo("Title", "Summary", "Detail");
</code></pre>
<p><strong>Problem</strong>:<br>
The p:messages element of the dialog does not show the message when the dialog is opened the first time. After opening and hiding it once it shows all further FacesMessages just fine.</p>
<p><strong>Question</strong>:<br>
So far i am useing opening and closeing the dialog once when the interface is initialized as a workarround. Does annyone know what causes this problem in the first place and also how to solve it properly?</p>
<p>Thanks for answers</p>
| <p>First of all it is not allowed to put a form inside of another, as stated in W3C XHTML specification, "form must not contain other form elements." visit: <a href="https://www.w3.org/TR/xhtml1/#prohibitions" rel="nofollow">https://www.w3.org/TR/xhtml1/#prohibitions</a>.</p>
<p>So your dialog should not be inside of the main form, you have to sperate the dialog from the form, your code sould be orginsed like this :</p>
<pre><code><form id="mainForm" >
<!--your main page-->
</form>
<p:dialog id="dlgMessageDialog" >
<h:form id="messageForm" enctype="multipart/form-data">
<f:facet name="header">
<h:outputText id="messageDialogHeader"
value="#{messageDialogBean.header}" />
</f:facet>
<p:messages id="messages" escape="false" closable="false"
showDetail="true" autoUpdate="true"
for="#{messageDialogBean.messageDialogId}"></p:messages>
<p:spacer height="20px"></p:spacer>
<p:commandButton value="#{msg.btnOk}"
oncomplete="PF('wigVarMessageDialog').hide()" />
</h:form>
</p:dialog>
</code></pre>
<p>Another thing, you have to update the whole dialog, so when the dialog is opened the messges is automaticly updated :</p>
<pre><code>context.update("dlgMessageDialog");
</code></pre>
|
Terminal does not recognize git <p>None of my git repositories work. I open the terminal and I go to the folder where I have git: cd ... I usually see a green asterisk . It means that it recognizes that the folder has git. But now, I do not see the green asterisk. It happens with all my repositories. </p>
<p>I have checked that inside the folder there is the .git hidden folder.</p>
<p>I have updated my Operating Sistem. Now I have MacOS Sierra 10.12 I do not know if there is any relation. It has a coincidence in time.</p>
<p>I tried to create a new repository in a test folder:<br>
cd test<br>
git init</p>
<p>Then, the terminal say:
Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo.</p>
<p>I am new, I do not understand what does it mean. Can anyone explain, please</p>
| <p>After trying a lot of things I could find that the program XCode creates some problem. I had a new version of XCode downloaded but not opened yet. When I opened and agreed to the new conditions, git and the terminal work well again. </p>
|
Creating ipa from XCode 7.x and submit to AppStore is supported for iOS 10? <p>Our app already live in AppStore. Now i am going to take ipa from Xcode 7 with iOS 7.0 greater choosen. Also ll upload this binary from Application loader not from XCode. Xcode 7.3 has iOS 9 sdk. I know to run this app in device i need to go for Xcode 8.</p>
<p>Will this binary support iOS 10 devices?</p>
<p>OR I need to create ipa in Xcode 8.0?</p>
| <p>Sure, i've uploaded an ipa file (built with xCode 7.3) to ItunesConnect and it's currently online and available for iOS 10 devices. You could install manually iOS 10 simulators to test your app on iOS 10 using xCode 7.x</p>
|
how can I launch a first time installation project? <p>I have an android project for first time installation.
It is related with my firm agreement pages. It comes after google agreement pages.</p>
<p>I tried some technics for doing it. For example,I set it as a system application. However, it is cleaned when backup and reset operation.</p>
<p>Does anybody know how to run it?</p>
<p>on AndroidManifest.xml</p>
<pre><code><application
android:theme="@android:style/Theme.NoTitleBar"
android:allowBackup="true"
android:icon="@drawable/launcher"
android:label="@string/appname" >
<activity
android:name="xxxagreement.MainActivity"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:label="@string/app_name"
android:screenOrientation="portrait" >
<intent-filter android:priority="3">
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.HOME" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</code></pre>
<p>on MainActivity.java</p>
<pre><code>protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onResume() {
Intent i = new Intent();
i.setAction(AGREEGATE_STARTED);
sendBroadcast(i);
TextView t = (TextView)findViewById(R.id.textView1);
t.setSelected(true);
...
super.onResume();
}
</code></pre>
<p>Event Log prints:</p>
<p>Session 'app': Error Launching activity</p>
| <p>Your application doesn't have any launcher activity. Replace these lines</p>
<pre><code><category android:name="android.intent.category.HOME" />
<category android:name="android.intent.category.DEFAULT" />
</code></pre>
<p>with</p>
<pre><code><category android:name="android.intent.category.LAUNCHER" />
</code></pre>
|
How to get coverage report for external APIs? <p>I'm trying to get coverage report for the API code. I have all the test cases running perfectly in mocha. My problem is that my API server and the test cases are written in separate repositories.</p>
<p>I start my node API server on localhost, on a particular port, and then using supertest in mocha, hit the localhost url to test server's response.</p>
<p>Can you suggest me the best way to generate a coverage report for those APIs?</p>
| <h2>Testing env</h2>
<p>If you want to get coverage, supertest should be able to bootstrap the app server, like in the <a href="https://github.com/visionmedia/supertest#example" rel="nofollow">express example</a>. </p>
<p>The drawback is that <em>you must not run your tests against a running server</em>, like</p>
<pre><code>var api = request('http://127.0.0.1:8080');
</code></pre>
<p>but you must include your app entrypoint to allow supertest to start it like</p>
<pre><code>var app = require('../yourapp');
var api = request(app);
</code></pre>
<p>Of course, this may (or may not) result in a bit of refactoring on your app bootstrap process.</p>
<p>As other options, you can use node CLI debug capabilities or use <a href="https://github.com/node-inspector/node-inspector" rel="nofollow">node-inspector</a>.</p>
<h2>Coverage setup</h2>
<p>Supposing you are willing to install <a href="https://github.com/gotwarlost/istanbul" rel="nofollow">istanbul</a> in association with mocha to get coverage.</p>
<pre><code>npm install -g istanbul
</code></pre>
<p>then</p>
<pre><code>istanbul cover mocha --root <path> -- --recursive <test-path>
</code></pre>
<ul>
<li><code>cover</code> is the command use to generate code coverage</li>
<li><code>mocha</code> is the executable js file used to run tests</li>
<li><code>--root <path></code> the root path to look for files to instrument (aka the "source files")</li>
<li><code>--</code> is used to pass arguments to your test runner</li>
<li><code>--recursive <test-path></code> the root path to look for test files</li>
</ul>
<p>You can then add <code>--include-all-sources</code> to get cover info on all your source files.</p>
<p>In addition you can get more help running
<code>istanbul help cover</code></p>
|
How to check if an Android OS is forcing an application icon background color? <p>I am working with a team to develop a cross-platform application on mobile, and we're using Visual Studio 2015 and Xamarin.Forms v2.3.2.127. </p>
<p>We have already created the application icons that we need for the three different platforms (Android, iOS, UWP) and each one follows the native platform specifications. </p>
<p>There's only one more problem that we have faced, and I would like to know if there's any answer for my problem. Some of the devices that run Android OS forces the application icon to have a squared background, and they seem to give arbitrarily colours for the background (please check the image afterwards). We don't want to change the application icon by itself for Android so we're looking for a better way. </p>
<p>Is there any way in Xamarin to be able to detect that the device is adding a coloured background for the application icon so we can provide it with the icon that we want, or at least change the colour the device is going to use?</p>
<p><a href="http://i.stack.imgur.com/DoByv.png" rel="nofollow"><img src="http://i.stack.imgur.com/DoByv.png" alt="Home Page of Leagoo Z5 mobile"></a></p>
<p>As you can see, Whatsapp, Facebook and Dropbox icons are all modified and given a squared coloured background. </p>
<p>Thanks in advance for any help that could be given.<br>
Regards, Paul.</p>
| <p>This is a custom launcher / icon pack's doing. Most likely the manufacturer's doing(LEAGOO). You may notice that "Known" apps will have a custom icon, but if you created a custom app it might look much different with a random background and perhaps an icon transformation of some sort. </p>
<p>It might be worth getting a stock Android device to ensure your Icon looks great on stock Android as you'll never know what different launchers(bloatware) will do to your app's icon.</p>
<p>If the OEM has a way to interop with it, then by all means that would be the easiest way to customize this behavior. However most launchers are included in the OEM's package/bloatware.</p>
|
How Can I populate a JTable from an excel file, as long as there is more than 1 matching element in my Array List? [Java] <p>[![enter image description here][1]][1]I'm having a problem populating a JTable from an excel file. Here is the operation, I will search, lets say "Line 1", there are 2 cells matching this value, if there is a match, I would like to pull the row and insert it into my JTable. I was able to get this working, however, this only creates one row for the first matching value, when i click on search button again, it will replace the row, with a new row, if there was more than 1 match. </p>
<p>I would the jtable to add both rows in the same table, rather one by one. I attached what I have so far. </p>
<p>Thank You in advanced. </p>
<pre><code>try {
FileInputStream fis = new FileInputStream(
new File("S:\\Tester Support\\0LineTester Database\\Audit\\LASAudit.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
if (cell.getRichStringCellValue().getString().trim().equals(LinNum_Text.getText())) {
int rowNum = row.getRowNum();
Row r = sheet.getRow(rowNum);
DefaultTableModel model = new DefaultTableModel();
int col_0 = 0;
String val_0 = r.getCell(col_0).getStringCellValue();
int col_1 = 1;
String val_1 = r.getCell(col_1).getStringCellValue();
int col_2 = 2;
String val_2 = r.getCell(col_2).getStringCellValue();
int col_3 = 3;
String val_3 = r.getCell(col_3).getStringCellValue();
model.addColumn("ID", new Object[] { val_0 });
model.addColumn("Date", new Object[] { val_1 });
model.addColumn("Auditor Name", new Object[] { val_2 });
model.addColumn("Line #", new Object[] { val_3 });
table = new JTable(model);
table.setVisible(true);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 278, 670, 303);
contentPane.add(scrollPane);
scrollPane.setViewportView(table);
}
}
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
</code></pre>
| <blockquote>
<p>I was able to get this working, however, this only creates one row for the first matching value, </p>
</blockquote>
<p>That is because in your "looping code" you create a new JTable each time.</p>
<p>Instead you want to create the table once and add data to your TableModel inside the loop. So the structure of your code should be something like:</p>
<pre><code>String[] columnNames = { "Id", "Date", ... };
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
for (...)
{
...
if (matched row found)
{
...
Object[] row = { val_0, val_1, ...};
model.addRow( row );
}
JTable table = new JTable( model );
...
</code></pre>
|
Pig Script Merging Rows after join and group by <p><strong>Movie table</strong>:</p>
<pre><code>id movie genre
1 ABC A|B|C
2 DEF D|A|F
</code></pre>
<p>There are multiple genres which are separated by a <code>|</code> delimiter.</p>
<p><strong>Ratings table:</strong></p>
<pre><code>user_id movie_id rating
1 1 3.5
1 2 4.5
</code></pre>
<p><strong>Result:</strong></p>
<p>I want the result as <code>user_id</code> + all genres</p>
<pre><code>user_id genres
1 (A|B|C|D|A|F)
</code></pre>
<p><strong>Code:</strong></p>
<pre><code>genre_data = join movie by id, ratings by movie_id;
genre_data = group genre_data by (user_id);
user1_data = foreach genre_data generate ratings::user_id, movie::genre;
</code></pre>
| <p>You can achieve it by:</p>
<pre><code>genre_data = join movie by id, ratings by movie_id;
genre_data = group genre_data by user_id;
user_data = foreach genre_data {
genres = foreach genre_data generate movie::genre as genres;
generate group as user_id, BagToString(genres, '|');
};
</code></pre>
|
Need URL for Appstore connectivity and Xcode developer account connectivity <p>In my office, proxy and URL restriction is there so am not able to update the app/softwares through Appstore application and also not able to add the Team, signing certificate in Xcode. I raised the complaint to IT admin and inorder to enable the access they are asking for the URL's.. I searched but no luck .. Can you please share if you know the URL details.</p>
| <p>Best to run a network traffic analyser on your computer and make a list of attempted accesses.</p>
<p>Even better, do the same from home (or wherever you have access), and list the actual URLs.</p>
<p>Or (in the mean time) ask/urge IT if they can open HTTPS (and HTTP) access <code>*.apple.com/*</code> and <code>*.itunesconnect.com/*</code> and see how far you get.</p>
<p>Good luck, this is a very annoying situation I've in too a few times.</p>
|
Regex pattern match by delimiter <p>to get the value of gs from the below query.</p>
<p><strong>(2|3|4|5|6|7|8|9|10|11|gs=accountinga sdf* |gs=tax*|12|ic='38')</strong></p>
<p>I have tried with below pattern</p>
<p><strong>(?<=gs=)(.*)([|])</strong></p>
<p>But this results <strong>gs=accounting asdf* |gs=tax*|12|</strong></p>
<p>Desired output should be : <strong>accounting asdf*,tax*</strong></p>
<p>is that possible with change in pattern ?</p>
| <p>This regex will match as you want.</p>
<pre><code>(?<=gs=)([^|)]*)
</code></pre>
<p>It will also handle the case where gs is the last clause without including the closing bracket in the group.</p>
|
Webdav Servlet Implementation <p>I am trying to use WebDAV protocol to access my file store on my server. I want all functionalities of WebDAV both level 1 and level 2+.</p>
<p>My server is Apache Tomcat, and authentication rules are in MySQL database. </p>
<p>I have seen libraries like Jackrabbit and Tomcat's default WebDAV Servlet, But I do not know what to do.</p>
<p>Are there any good tutorials available out there? How do I give separate home directory for each user in WebDAV? </p>
| <p>The best option is <a href="http://milton.io" rel="nofollow">milton.io</a>, that allows you to completely control the persistence of content and authentication and authorisation rules. Milton with dav level 2 is not free, but I'm the author. You can get a trial license through the milton website.</p>
<p>Tutorials are here - <a href="http://milton.io/programs/milton/anno/" rel="nofollow">http://milton.io/programs/milton/anno/</a></p>
|
How to create a compound field in group by in sqlserver <p>I have a table that contains 2 fields (for simplicity). the first one is the one that I want to group by on, and the second one is the one that I want to show as a comma separated text field. How to do it?</p>
<p>So my data is like this:</p>
<pre><code>col 1 col2
------ ------
Ashkan s1
Ashkan s2
Ashkan s3
Hasan k1
Hasan k2
Hasan k3
Hasan kachal
</code></pre>
<p>I want this</p>
<pre><code>col1 count combination
------ ------ -------
Ashkan 3 s1, s2,s3
Hasan 4 k1, k2,k3,kachal
</code></pre>
<p>I can do the group by like below, but how to do the combination?</p>
<pre><code> select [col1],count(*)
FROM mytable
group by [col1]
order by count(*)
</code></pre>
| <p>You can use <code>FOR XML PATH</code> for this:</p>
<pre><code>select col1, count(*) ,
STUFF((SELECT ',' + col2
FROM mytable AS t2
WHERE t2.col1 = t1.col1
FOR XML PATH('')), 1, 1, '')
FROM mytable AS t1
group by col1
order by count(*)
</code></pre>
|
How to change the frame of a UIView subclass on device orientation which is programmatically created? <p>I have a UIView subclass which is created programmatically.I have portrait and landscape mode in my application which uses
Autolayout. Initially the UIView frame is set using initWithFrame.But when the orientation changes to landscape the CGRect of UIView is stuck with the portrait mode.How can I alert the UIView subclass to change the CGRect on device orientation?</p>
<p>Could anyone help me on this?</p>
<p>This is my initial frame setup code for the UIView:</p>
<pre><code>- (id)initWithFrame:(CGRect)frame videoUrl:(NSURL *)videoUrl{
self = [super initWithFrame:frame];
if (self) {
_frame_width = frame.size.width;
int thumbWidth = ceil(frame.size.width*0.05);
_bgView = [[UIControl alloc] initWithFrame:CGRectMake(thumbWidth-BG_VIEW_BORDERS_SIZE, 0, frame.size.width-(thumbWidth*2)+BG_VIEW_BORDERS_SIZE*2, frame.size.height)];
_bgView.layer.borderColor = [UIColor grayColor].CGColor;
_bgView.layer.borderWidth = BG_VIEW_BORDERS_SIZE;
[self addSubview:_bgView];
</code></pre>
| <p>Just detect the orientation of device whether it is in <code>landscape</code> or <code>portrait</code> mode and then change the size of <code>UIView</code> accordingly see below code:</p>
<p><strong>To detect device orientation:</strong></p>
<pre><code>-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft || [[UIDevice currentDevice] orientation ]== UIDeviceOrientationLandscapeRight)
{
UIView *view = [classObject setupView:xPos yPos:yPos width:widthValue height:heightValue];
yourView.frame = view.frame;
NSLog(@"device orientation Landscapse");
}
if([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait || [[UIDevice currentDevice] orientation] == UIDeviceOrientationPortraitUpsideDown )
{
UIView *view = [classObject setupView:xPos yPos:yPos width:widthValue height:heightValue];
yourView.frame = view.frame;
NSLog(@"device orientation portrait");
}
}
</code></pre>
<p>Write this method inside your class, no need to call from anywhere it will detect orientation when user rotate.</p>
<p>Create custom method inside your class which is returning <code>UIView</code> with complete frame and call by sending x,y position and its width and height when user changes orientation see below code:</p>
<pre><code>-(UIView *) setupView:(float)x yPos:(float)y width:(float)width height:(float) height{
UIView *yourView = [[UIView alloc] initWithFrame:CGRectMake(x,y,width,height)];
yourView.backgroundColor=[UIColor clearColor];
return yourView;
}
</code></pre>
|
Can checkins be blocked in VS2015 between certain times <p>In Visual Studio 2015 can a check in be blocked between certain times of the day so they do not actually get checked in until after the time period expires?</p>
| <p>For TFVC the only way I can think of doing this is to use scheduled tasks to change permissions.</p>
<p><a href="https://www.visualstudio.com/en-us/docs/tfvc/permission-command" rel="nofollow"><code>tf permission</code></a> from the command line â thus can be scheduled â can be used to change permissions.</p>
|
Angular Directive - Correct order of execution of functions <p>Being bit confused as per the following 2 blogs: </p>
<blockquote>
<p><strong>I.</strong> Eric W Green - Toptal
<a href="https://www.toptal.com/angular-js/angular-js-demystifying-directives" rel="nofollow">https://www.toptal.com/angular-js/angular-js-demystifying-directives</a></p>
</blockquote>
<p>Order of execution </p>
<pre><code>Compile -> Controller -> PreLink -> PostLink
</code></pre>
<blockquote>
<p><strong>II.</strong> JsonMore
<a href="http://jasonmore.net/angular-js-directives-difference-controller-link/" rel="nofollow">http://jasonmore.net/angular-js-directives-difference-controller-link/</a></p>
</blockquote>
<p>Order of execution</p>
<pre><code>Controller -> Compile -> PreLink -> PostLink
</code></pre>
<p>The answer to complex problem difference between <em>controller</em> & <em>link</em> is given here -- use code in controller if required before compile <strong><em>OR</em></strong> write in link if code to be run after compile. </p>
<p>But, blog 1 says both run after compilation. Please, suggest which one is correct? </p>
| <p>The concept is as a matter of fact indeed baffling , but ones you understand the actual flow, it would remain clear throughout.</p>
<p>The actual order of execution is ..<strong>Compile -> Controller -> Pre-Link -> Post-Link</strong></p>
<p>For further understanding, just go through this <a href="https://www.undefinednull.com/2014/07/07/practical-guide-to-prelink-postlink-and-controller-methods-of-angular-directives/" rel="nofollow">article</a>, it surely helped me.</p>
<p>Hope this helps.</p>
<p>Cheers</p>
|
Ngnix downloading php <p>I am trying to get nginx to route all requests starting with /embed to <code>/home/forge/dev.tline.io/embed/index.php</code> </p>
<p>My Nginx config: </p>
<pre><code>location /embed {
root /home/forge/dev.tline.io;
try_files /embed/index.php =404;
}
location / {
root /home/forge/dev.tline.io;
index index.html index.htm;
try_files $uri$args $uri$args/ $uri $uri/ /index.html =404;
}
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
</code></pre>
<p>All requests go to <code>/embed/index.php</code> but it doesn't run the php file it downloads it. </p>
<p>Note: <code>http://dev.tline.io/embed/index.php</code> is compiled not downloaded</p>
<p>I got it to work if add </p>
<pre><code>fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
</code></pre>
<p>into <code>location /embed</code> but there should be a better way to do this</p>
| <p>Please try out the following code,</p>
<pre><code>map $request_uri $rot {
"~ /embed" /home/forge/dev.tline.io/embed/;
default /home/forge/dev.tline.io/;
}
map $request_uri $ind {
"~ /embed" index.php;
default index.html;
}
server {
...
root $rot;
index index.php index.html index.htm;
...
location / {
try_files $uri$args $uri$args/ $uri $uri/ /$ind =404;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
...
}
</code></pre>
<p>If this doesn't work out, try switching <code>$ind</code> position suitably, and check error log in case of extra '/' found.</p>
|
How to let Q_PROPERTY only evaluate once <p>In <code>Qt</code> + <code>QML</code>, I'm using <code>Q_PROPERTY</code> a lot. The <code>NOTIFY</code> signals are excellent to reevaluate the value.</p>
<pre><code>class SomeComponent: public QObject
{
public:
const QString& GetMyValue(void) const;
void SetMyValue(const QString &value);
Q_PROPERTY(QString myValue READ GetMyValue WRITE SetMyValue NOTIFY myValueChanged)
signals:
void valueChanged();
}
Text {
text: myComponent.myValue
}
</code></pre>
<p>What I'm trying to do it that I now have a scenario where I only want to retrieve the value once, and not let it update in QML.</p>
<p><strong>For example:</strong> I want to be able to let the user know the previous value, while still be able to change it.</p>
<pre><code>TextInput {
text: myComponent.myValue
onAccepted:{
myComponent.myValue = text
}
}
Text {
text: "OldValue: " + myComponent.myValue
}
</code></pre>
<p>If I now type in the TextInput and press enter, the text in the Text element is also updated. How can I prevent this?</p>
<p>Can I disconnect from a property?</p>
<p>Or is the only way to change the <code>GetMyValue</code> and <code>SetMyValue</code> to <code>Q_INVOKABLE</code> ?</p>
| <p>You need to remove this: <code>text: "OldValue: " + myComponent.myValue</code> because reading <code>myComponent.myValue</code> will get the value from C++ by calling <code>GetMyValue</code>.</p>
<p>In QML, you create a function</p>
<pre><code>function updateDisplay(){
iText.text = "OldValue: " + myComponent.myValue
}
Text {
id: iText
text: "OldValue: "
}
</code></pre>
<p>and you call <code>updateDisplay()</code> from C++ each time you want to update the value.</p>
<p>Basically, in QML if you read a C++ value (<code>var aValue = myCPPComponent.myValue</code>), it will call the getter specified in Q_PROPERTY, and if you set the value (<code>myCPPComponent.myValue = aValue</code>) it will call the setter. Always.</p>
|
Create Javascript File/Blob object from image URI <p>Is it possible to create a File or Blob object for my image out of an image URI?</p>
<p>Using Cordova Image Picker, a plugin on my mobile app, I can retrieve photo URI's that look like this: "file:///data/user/0/..../image.jpg"</p>
<p>However, I am now trying to create a File or Blob object which Google Firebase requires for my images to be uploaded. I just can't figure out how. Every solution I try seems to be wrong to the point where I think I'm looking at it from a complete wrong perspective. I'm new to Javascript. Thanks a lot!</p>
| <p>Have a look at a question that I posted a while back which deals with this but for videos (same principle applies): <a href="http://stackoverflow.com/questions/38439987/uploading-video-to-firebase-3-0-storage-using-cordovafiletransfer/38501655#38501655">Uploading video to firebase (3.0) storage using cordovaFileTransfer</a></p>
<p>You need to read as an arrayBuffer using cordova's file plugin, then blob; something like:</p>
<pre><code>var file_path = "root/to/directory";
var name = "filename.jpg";
$cordovaFile.readAsArrayBuffer(file_path, name)
.then(function (success) {
// success
console.log(success);
blob = new Blob([success], {type: "image/jpeg"});
console.log(blob);
var uploadTask = storageRef.child(name).put(blob);
uploadTask.on('state_changed', function(snapshot){
// Observe state change events such as progress, pause, and resume
// See below for more detail
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
}, function(error) {
// Handle unsuccessful uploads
console.log("Error uploading: " + error)
}, function() {
// Handle successful uploads on complete
// For instance, get the download URL: https://firebasestorage.googleapis.com/...
var downloadURL = uploadTask.snapshot.downloadURL;
console.log("Success!", downloadURL);
});
}, function (error) {
// error
console.log("Failed to read file from directory, error.code);
}
</code></pre>
<p>If your program passes you a full path to the image you will need to separate the name from the path to the directory where the image is stored. Just look for everything after the final / </p>
|
How to integrate Admob Rewarded Ads in Android? <p>I am struggling with <code>admob rewarded ads</code> integration. I tried with google tutorials but unable to achieve what i want.</p>
<p>Please suggest me any good <code>tutorial</code> (prefer video tutorial) to integrate <code>admob rewarded</code> ads in android.</p>
| <pre><code> public class YourActivity extends AppCompatActivity implements RewardedVideoAdListener
RewardedVideoAd mAd = MobileAds.getRewardedVideoAdInstance(this);
mAd.setRewardedVideoAdListener(this);
loadRewardedVideo();
private void loadRewardedVideo() {
mAd.loadAd(getString("YOUR_AD_UNIT_ID"),
new AdRequest.Builder()
.build());
}
</code></pre>
<p>Here is the listener:</p>
<pre><code>@Override
public void onRewardedVideoAdLoaded() {
Log.i(TAG, "Rewarded: onRewardedVideoAdLoaded");
try {
if (mAd.isLoaded()) {
mAd.show();
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
@Override
public void onRewardedVideoAdOpened() {
Log.i(TAG, "Rewarded: onRewardedVideoAdOpened");
}
@Override
public void onRewardedVideoStarted() {
Log.i(TAG, "Rewarded: onRewardedVideoStarted");
}
@Override
public void onRewardedVideoAdClosed() {
Log.i(TAG, "Rewarded: onRewardedVideoAdClosed");
}
@Override
public void onRewarded(RewardItem rewardItem) {
Log.i(TAG, "Rewarded: onRewarded! currency: " + rewardItem.getType() + " amount: " +
rewardItem.getAmount());
}
@Override
public void onRewardedVideoAdLeftApplication() {
Log.i(TAG, "Rewarded: onRewardedVideoAdLeftApplication ");
}
@Override
public void onRewardedVideoAdFailedToLoad(int i) {
Log.i(TAG, "Rewarded: onRewardedVideoAdFailedToLoad: " + i);
}
</code></pre>
|
RxJS Observable fire onCompleted after a number of async actions <p>I'm trying to create an observable that produces values from a number of asynchronous actions (http requests from a Jenkins server), that will let a subscriber know once all the actions are completed. I feel like I must be misunderstanding something because this fails to do what I expect.</p>
<pre><code>'use strict';
let Rx = require('rx');
let _ = require('lodash');
let values = [
{'id': 1, 'status': true},
{'id': 2, 'status': true},
{'id': 3, 'status': true}
];
function valuesObservable() {
return Rx.Observable.create(function(observer) {
_.map(values, function(value) {
var millisecondsToWait = 1000;
setTimeout(function() { // just using setTimeout here to construct the example
console.log("Sending value: ", value);
observer.onNext(value)
}, millisecondsToWait);
});
console.log("valuesObservable Sending onCompleted");
observer.onCompleted()
});
}
let observer = Rx.Observer.create((data) => {
console.log("Received Data: ", data);
// do something with the info
}, (error) => {
console.log("Error: ", error);
}, () => {
console.log("DONE!");
// do something else once done
});
valuesObservable().subscribe(observer);
</code></pre>
<p>Running this, I get output:</p>
<pre><code>valuesObservable Sending onCompleted
DONE!
Sending value: { id: 1, status: true }
Sending value: { id: 2, status: true }
Sending value: { id: 3, status: true }
</code></pre>
<p>While what I would like to see is something more like:</p>
<pre><code>Sending value: { id: 1, status: true }
Received Data: { id: 1, status: true }
Sending value: { id: 2, status: true }
Received Data: { id: 2, status: true }
Sending value: { id: 3, status: true }
Received Data: { id: 3, status: true }
valuesObservable Sending onCompleted
DONE!
</code></pre>
<p>I don't actually care about the order of the items in the list, I would just like the observer to receive them.</p>
<p>I believe what is happening is that Javascript asynchronously fires the timeout function, and proceeds immediately to the <code>observer.onCompleted()</code> line. Once the subscribing observer receives the onCompleted event (is that the right word?), it decides that it's done and disposes of itself. Then when the async actions complete and the observable fires <code>onNext</code>, the observer no longer exists to take any actions with them.</p>
<p>If I'm right about this, I'm still stumped about how to make it behave in the way I would like. Have I stumbled into an antipattern without realising it? Is there a better way of approaching this whole thing?</p>
<hr>
<p>Edit:</p>
<p>Since I used setTimeout to construct my example, I realised I can use it to partially solve my problem by giving the observable a timeout.</p>
<pre><code>function valuesObservable() {
return Rx.Observable.create(function(observer) {
let observableTimeout = 10000;
setTimeout(function() {
console.log("valuesObservable Sending onCompleted");
observer.onCompleted();
}, observableTimeout);
_.map(values, function(value) {
let millisecondsToWait = 1000;
setTimeout(function() {
console.log("Sending value: ", value);
observer.onNext(value)
}, millisecondsToWait);
});
});
}
</code></pre>
<p>This gets me all of the information from the observable in the order I want (data, then completion) but depending on the choice of timeout, I either may miss some data, or have to wait a long time for the completion event. Is this just a inherent problem of asynchronous programming that I have to live with?</p>
| <p>Yes there is a better way. The problem right now is that you are relying on time delays for your synchronization when in fact you can use the <code>Observable</code> operators to do so instead.</p>
<p>The first step is to move away from directly using <code>setTimeout</code>. Instead use <code>timer</code></p>
<pre><code>Rx.Observable.timer(waitTime);
</code></pre>
<p>Next you can <em>lift</em> the values array into an Observable such that each value is emitted as an event by doing:</p>
<pre><code>Rx.Observable.from(values);
</code></pre>
<p>And finally you would use <code>flatMap</code> to convert those values into <code>Observables</code> and flatten them into the final sequence. The result being an <code>Observable</code> that emits each time one of the source <code>timers</code> emits, and completes when all the source Observables complete.</p>
<pre><code>Rx.Observable.from(values)
.flatMap(
// Map the value into a stream
value => Rx.Observable.timer(waitTime),
// This function maps the value returned from the timer Observable
// back into the original value you wanted to emit
value => value
)
</code></pre>
<p>Thus the complete <code>valuesObservable</code> function would look like:</p>
<pre><code>function valuesObservable(values) {
return Rx.Observable.from(values)
.flatMap(
value => Rx.Observable.timer(waitTime),
value => value
)
.do(
x => console.log(`Sending value: ${value}`),
null,
() => console.log('Sending values completed')
);
}
</code></pre>
<p>Note the above would work as well if you weren't using demo stream, i.e. if you had really http streams you could even simplify by using <code>merge</code> (or <code>concat</code> to preserve order)</p>
<pre><code>Rx.Observable.from(streams)
.flatMap(stream => stream);
// OR
Rx.Observable.from(streams).merge();
// Or simply
Rx.Observable.mergeAll(streams);
</code></pre>
|
How to programmatically maintain aspect ratio of object in wpf <p>I programmatically add a <code>Border</code> with a certain width and height to a grid. However, I want to get either one of the following:</p>
<ol>
<li>Make the border keep aspect ratio and fill make it as big as possible inside the grid</li>
<li>Make the border scale whenever the grid scales down or up (so not particularily the biggest possible, more like a percentage of the grid)</li>
</ol>
<p>At the moment this is the situation when I resize my window:</p>
<pre><code>Color borderColor = (Color)ColorConverter.ConvertFromString(BorderColor);
Color backgroundColor = (Color)ColorConverter.ConvertFromString(BackgroundColor);
Border border = new Border();
border.BorderThickness = new Thickness(BorderSize);
border.CornerRadius = new CornerRadius(TopLeftCornerRadius, TopRightCornerRadius, BottomRightCornerRadius, BottomLeftCornerRadius);
border.BorderBrush = (SolidColorBrush)(new BrushConverter().ConvertFrom(BorderColor));
border.Background = (SolidColorBrush)(new BrushConverter().ConvertFrom(BackgroundColor));
border.Width = Width;
border.Height = Height;
border.Margin = new Thickness(10);
previewgrid.Children.Add(border);
</code></pre>
<p>The normal situation:</p>
<p><a href="http://i.stack.imgur.com/0KSJY.png" rel="nofollow"><img src="http://i.stack.imgur.com/0KSJY.png" alt="enter image description here"></a></p>
<p>The scaled situation:</p>
<p><a href="http://i.stack.imgur.com/3PpUT.png" rel="nofollow"><img src="http://i.stack.imgur.com/3PpUT.png" alt="enter image description here"></a></p>
<p>So I would like it to resize properly and stay inside the white rectangle. By the way, the white grid has a margin as you can see ;-)
Thanks in advance!</p>
| <p>As lerthe61 suggested, just use a <a href="https://msdn.microsoft.com/en-us/library/system.windows.controls.viewbox(v=vs.110).aspx" rel="nofollow">Viewbox</a> with its <code>Stretch</code> property set to <code>Uniform</code>:</p>
<pre><code>Color borderColor = (Color)ColorConverter.ConvertFromString(BorderColor);
Color backgroundColor = (Color)ColorConverter.ConvertFromString(BackgroundColor);
Border border = new Border();
border.BorderThickness = new Thickness(BorderSize);
border.CornerRadius = new CornerRadius(TopLeftCornerRadius, TopRightCornerRadius, BottomRightCornerRadius, BottomLeftCornerRadius);
border.BorderBrush = (SolidColorBrush)(new BrushConverter().ConvertFrom(BorderColor));
border.Background = (SolidColorBrush)(new BrushConverter().ConvertFrom(BackgroundColor));
border.Width = Width;
border.Height = Height;
border.Margin = new Thickness(10);
Viewbox viewBox = new Viewbox();
viewBox.Stretch = Stretch.Uniform;
viewBox.Child = border;
previewgrid.Children.Add(viewBox);
</code></pre>
<p>Please, note that this solution does not work if <code>previewgrid</code> is a <code>Canvas</code>.
I hope it can help you.</p>
|
How to enable read only permision to some specified cells and sheets in excel using openxml in c# <p>I am reading XML data then I pasted to data-set and the I created spreadsheet and copied the data to to sheets in spreadsheet.So now I want to only allow some sheets and cells to read-only. To prevent to no changes to headers and data in some sheets, So I am posting code used to convert the XML to excel using open XML. So I need to prevent write for some sheets and also cells some sheets.
<code>enter code here</code></p>
<pre><code> public void ExportDSToExcel(DataSet ds, string dest)
{
using (var workbook = SpreadsheetDocument.Create(dest, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
var workbookPart = workbook.AddWorkbookPart();
workbook.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
workbook.WorkbookPart.Workbook.Sheets = new DocumentFormat.OpenXml.Spreadsheet.Sheets();
uint sheetId = 1;
foreach (DataTable table in ds.Tables)
{
var sheetPart = workbook.WorkbookPart.AddNewPart<WorksheetPart>();
var sheetData = new DocumentFormat.OpenXml.Spreadsheet.SheetData();
sheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(sheetData);
DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = workbook.WorkbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>();
string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);
if (sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Count() > 0)
{
sheetId =
sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Select(s => s.SheetId.Value).Max() + 1;
}
DocumentFormat.OpenXml.Spreadsheet.Sheet sheet = new DocumentFormat.OpenXml.Spreadsheet.Sheet() { Id = relationshipId, SheetId = sheetId, Name = table.TableName };
sheets.Append(sheet);
DocumentFormat.OpenXml.Spreadsheet.Row headerRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
List<String> columns = new List<string>();
foreach (DataColumn column in table.Columns)
{
columns.Add(column.ColumnName);
DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName);
headerRow.AppendChild(cell);
}
sheetData.AppendChild(headerRow);
foreach (DataRow dsrow in table.Rows)
{
DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
foreach (String col in columns)
{
DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString()); //
newRow.AppendChild(cell);
}
sheetData.AppendChild(newRow);
}
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if(txtname.Text != null)
{
if (FileUpload1.HasFile == true)
{
string myXMLfile = "/uploads/" + FileUpload1.FileName;
FileUpload1.SaveAs(Server.MapPath(myXMLfile));
string dest = "D:/uploads/" + txtname.Text+".xlsx";
DataSet ds = new DataSet();
try
{
ds.ReadXml(myXMLfile);
}
catch (Exception ex)
{
lblstatus.Text=(ex.ToString());
}
ExportDSToExcel(ds, dest);
}
else
{
lblstatus.Text = "Please Upload the file ";
}
}
else {
lblstatus.Text = "Please enter the name ";
}
}
}
</code></pre>
<p>thanks in advance so please help me to find solution in this code.</p>
| <p>We can customise protection by password in different means.For making excel sheet specified area or column or row as read only or a full sheet into read only by giving protection to sheet by password.If we want to protect whole sheet use this code</p>
<pre><code> PageMargins pageM = sheetPart.Worksheet.GetFirstChild<PageMargins>();
SheetProtection sheetProtection = new SheetProtection();
sheetProtection.Password = "admin";
sheetProtection.Sheet = true;
sheetProtection.Objects = true;
sheetProtection.Scenarios = true;
ProtectedRanges pRanges = new ProtectedRanges();
ProtectedRange pRange = new ProtectedRange();
ListValue<StringValue> lValue = new ListValue<StringValue>();
lValue.InnerText = ""; //set cell which you want to make it editable
pRange.SequenceOfReferences = lValue;
pRange.Name = "not allow editing";
pRanges.Append(pRange);
sheetPart.Worksheet.InsertBefore(sheetProtection, pageM);
sheetPart.Worksheet.InsertBefore(pRanges, pageM);
</code></pre>
<p>If we want specified page as read only then first give a condition filter by name then give this code .In this code lValue.InnerText = ""; is null so we are not mention cells have permission to overcome this protection. If we mention the cells we can edit up to that limit.</p>
|
wso2 esb authenticate webservice called inside the flow <p>I'w defining a flow in wso2 esb, in this flow
1)I receive a soap message from an external salesforce (salesforce1)
2)I send the same message to another salesforce (salesforce2)</p>
<p>salesforce 1 and 2 are associated with different account so when making the call in 2) I have to request a sessionid for salesforce soap api and use it to make the call.
What is the suggested way to implement this scenario?
Thanks</p>
| <p>You can use <a href="https://store.wso2.com/store/assets/esbconnector/details/fbb433b5-4d74-4064-84c2-e4b23c531aa2" rel="nofollow">Salesforce connector</a> to connect Salesforce API.Use the logout method to invalidate the session for the first Salesforce call and then use init method with Salesforce2 credentials to connect with
Salesforce2. Find more details <a href="https://docs.wso2.com/display/ESBCONNECTORS/Configuring+Salesforce+Connector+Operations#ConfiguringSalesforceConnectorOperations-LoggingoutofSalesforce" rel="nofollow">here</a>.</p>
<pre><code><salesforce.query configKey="SFConfig1">
<batchSize>200</batchSize>
<queryString>select id,name from Account</queryString>
</salesforce.query>
<salesforce.logout/>
<salesforce.create configKey="SFConfig2">
<allOrNone>0</allOrNone>
<allowFieldTruncate>0</allowFieldTruncate>
<sobjects xmlns:sfdc="sfdc">{//sfdc:sObjects}</sobjects>
</salesforce.create>
</code></pre>
|
SAPUI5 filter with and-operation over multiple arguments <p>I would like the implement multiple filter for the search on a table binding. The requirement is to associate multiple filter with an and-condition: </p>
<p>Pseudo code: </p>
<pre><code>if(filterA && filter1 || filterB && filter1 || filterC && filter1 ){...}
</code></pre>
<p>How can I achieve it?</p>
<p>I tried with the following:</p>
<pre><code>var filter1 = [ new sap.ui.model.Filter("desc", FilterOperator.Contains, sQuery), new sap.ui.model.Filter("flag", FilterOperator.NE, 'X')];
var filter2 = [ new sap.ui.model.Filter("costnr", FilterOperator.Contains, sQuery), new sap.ui.model.Filter("flag", FilterOperator.NE, 'X')];
var filter3 = [ new sap.ui.model.Filter("location", FilterOperator.Contains, sQuery), new sap.ui.model.Filter("flag", FilterOperator.NE, 'X')];
var filter4 = [ new sap.ui.model.Filter("location2", FilterOperator.Contains, sQuery), new sap.ui.model.Filter("flag", FilterOperator.NE, 'X')];
var filter5 = [ new sap.ui.model.Filter("street", FilterOperator.Contains, sQuery), new sap.ui.model.Filter("flag", FilterOperator.NE, 'X')];
var filter6 = [ new sap.ui.model.Filter("houseno", FilterOperator.Contains, sQuery), new sap.ui.model.Filter("flag", FilterOperator.NE, 'X')];
var filter7 = [ new sap.ui.model.Filter("customer", FilterOperator.Contains, sQuery), new sap.ui.model.Filter("flag", FilterOperator.NE, 'X')];
var filter8 = [ new sap.ui.model.Filter("ordernr", FilterOperator.Contains, sQuery), new sap.ui.model.Filter("flaga", FilterOperator.NE, 'X')];
var oFilterExt = new sap.ui.model.Filter({filters: [filter1,filter2, filter3, filter4, filter5, filter6, filter7, filter8], and: false});
//binding
binding.filter(oFilterExt, sap.ui.model.FilterType.Application);
</code></pre>
| <p>You were on the right track with the <a href="https://sapui5.netweaver.ondemand.com/sdk/#docs/api/symbols/sap.ui.model.Filter.html#constructor" rel="nofollow">and</a> property:</p>
<pre class="lang-js prettyprint-override"><code>new sap.ui.model.Filter({
and:false,
filters: [
new sap.ui.model.Filter({
and: true,
filters: [
new sap.ui.model.Filter("property1", FilterOperator.Contains, sQuery),
new sap.ui.model.Filter("property2", FilterOperator.Contains, sQuery)
]}),
new sap.ui.model.Filter({
and: true,
filters: [
new sap.ui.model.Filter("property3", FilterOperator.Contains, sQuery),
new sap.ui.model.Filter("property4", FilterOperator.Contains, sQuery)
]}),
new sap.ui.model.Filter({
and: true,
filters: [
new sap.ui.model.Filter("property5", FilterOperator.Contains, sQuery),
new sap.ui.model.Filter("property6", FilterOperator.Contains, sQuery)
]})
]});
</code></pre>
|
Why some JavaScript functions don't work when a anchor is activate (#anchor in URL) <p><strong>EDIT NUMBER ONE : It is really strange in fact my javascript functions don't work when I click on the anchor ! Really... If someone has an idea I would be so thanksful</strong> !</p>
<p>I am coding a simple home page composed of a header with forms and a section with an introduction to the content of my website.</p>
<p>And I have two problems because of my anchor (at least it seems) : it looks like my javascript functions don't work when I click on the anchor. I will explain you more precisely.</p>
<p><strong>I. Javascript function for displaying forms</strong></p>
<p>The first part is composed of a header. On this header you have a form to connect or register. I don't diplay the both forms : indeed I display first only the connection form. if the user is not a member he just need to click on "I don't have an account" and then my connection form is replaced by the register form. (thanks to a jquery code)</p>
<p>At the end of header I put an arrow. When you click on it you go directly to the presentation of the content of my website (thanks to an anchor). </p>
<p><strong>II. Javascript function for displaying a summary of precise content</strong></p>
<p>After having clicked on the anchor the users face to 3 circles (with title : content 1, content 2 and content 3). When the user flies over a circle, this circle moves into a rectangular form and display a summary of the content.</p>
<p>But when I don't click on the anchor : everything works fine. But when I click on the anchor the javascript functions for displaying the forms and for displaying the content from the circle don't work at all ! I have no idea how to fix it. I try to erase the anchor from the url for instance : <a href="http://mywebsite/#anchor" rel="nofollow">http://mywebsite/#anchor</a> to <a href="http://mywebsite" rel="nofollow">http://mywebsite</a> but I didn't manage so far. </p>
<p><strong>III. Codes</strong> </p>
<p>Here are my HTML code and Javascript code. </p>
<pre><code><header>
<div class="intro-header">
<h1>TEST MY WEBSITE</h1>
<div class="divForm_global">
<div class="divForm_connexion" id="divForm_connexion">
<h3>Connect to your account</h3>
<form class="form_connexion">
<div class="form-group">
<label for="email">Email address: </label>
<input type="email" class="form-control" id="loginemail">
</div>
<div class="form-group">
<label for="pwd">Password: </label>
<input type="password" class="form-control" id="loginpasswordd">
</div>
<div class="checkbox">
<label><input type="checkbox">Remember me</label>
</div>
<button type="submit" class="btn btn-default" id="login">Submit</button>
<p id="one"><a href="#">Forgot Password ?</a></p>
<p id="two">Don't have account? <a class="signup" href="#" id="signup">Sign up here</a></p>
</form>
</div>
<div class="divForm_register" id="divForm_register">
<h3>Register Form FOR TEST</h3>
<form class="form_register">
<div class="form-group">
<label for="name">Name/Pseudo: </label>
<input type="text" class="form-control" id="name">
</div>
<div class="form-group">
<label for="email">Email address: </label>
<input type="email" class="form-control" id="registeremail">
</div>
<div class="form-group">
<label for="pwd">Password: </label>
<input type="password" class="form-control" id="registerpassword">
</div>
<button type="submit" class="btn btn-default" id="register">Submit</button>
<p id="two">Already have an account? <a class="signin" href="#" id="signin">Sign in</a></p>
</form>
</div>
</div>
<div class="page-scroll">
<a href="#service" class="btn btn-circle">
<i class="fa fa-angle-double-down animated"></i>
</a>
</div>
<hr class="intro-divider" />
</div>
</header>
<section id="service">
<script src="js/display_content_circle.js" type="text/javascript"></script>
<div class="wow bounceInDown" data-wow-delay="0.4s">
<h2>I CONTINUE TO TEST HERE </h2>
</div>
<div id="test>
<div class="container">
<div class="row" style="margin-top: 75px;">
<div class="wow fadeInLeft" data-wow-delay="0.2s">
<div class="col-md-4" style="height: 250px;">
<div class="panel circular-panel panelGeneral">
<h3 class="header" style="font-family:stencil,serif;color:red;">TITLE CIRCLE 1 TEST</h3>
<div class="description-header" style="display: none;">
<i class="panel-icon flaticon-tool"></i><a href="#" style="color:red; font-style:bold;">TEST HERE</a>
</div>
<p class="description" style="display: none;">TEST TEST TEST TEST</p>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</code></pre>
<p>Here you will find my javascript function to display the content of the circle when I fly over the circle :</p>
<pre><code>var main = function()
{
$('.circular-panel').hover(function()
{
$(this).animate(
{
width: '250px',
height: '250px',
borderWidth: '1px',
borderRadius: '4px',
lineHeight: '24px'
}, 100);
$(this).children('.header').fadeOut(100);
$(this).children('.description-header').fadeIn(100);
$(this).children('.description').fadeIn(100);
}, function()
{
$(this).animate(
{
width: '150px',
height: '150px',
borderWidth: '5px',
borderRadius: '50%',
lineHeight: '140px'
}, 100);
$(this).children('.header').fadeIn(100);
$(this).children('.description-header').fadeOut(100);
$(this).children('.description').fadeOut(100);
});
$('.extra').children('.glyphicon-remove').click(function()
{
$('.extra').slideUp('fast');
$('.copyright').animate(
{
marginBottom: '0px'
}, 'fast');
});
};
$(document).ready(main);
</code></pre>
<p>In order not to overwhelm you with codes I decided not to show you my code for the function that changes the forms as I think if we manage to solve the problem with the "circle" I will manage to solve the problem for the forms I guess.But if you need it just ask me </p>
<p>I really think the problem comes from those functions as they use "$document" and maybe this is modified because of the anchor. So the selector doesn't work as document is my website withtout anchor (<a href="http://Website" rel="nofollow">http://Website</a>) and when I click on the anchor I have (<a href="http://website/#anchor" rel="nofollow">http://website/#anchor</a>).</p>
<p>Do you have an idea ? Can we deactivate the anchor's URL ? (clicking on the anchor without that #anchor is added to the URL of the website ?)</p>
| <p>You could do this:</p>
<pre><code>$('a').on('click', function(e){
e.preventDefault();
});
</code></pre>
<p>This would prevent the defaut behavior of links also tho.</p>
|
JS how to dynamically populate a second date picker with minDate of the first one <p>How can I populate 2 date pickers? The second date picker has to have at least the value of first date picker.This is my code right now:</p>
<pre><code>selector.dtmDlgLimitFrom.attr('readonly', true).datepicker({
changeMonth: true,
changeYear: true,
minDate: dateToday,
yearRange: "0:+100"
});
selector.dtmDlgLimtTo.attr('readonly', true).datepicker({
changeMonth: true,
changeYear: true,
minDate: selector.dtmDlgLimitFrom.datepicker("getDate"),
yearRange: "0:+100"
});
</code></pre>
| <p>you can try following to set the min date of second date selector:</p>
<pre><code> minDate: $("#idoffirstdateselector").datepicker("getDate") });
</code></pre>
<p>e.g.</p>
<pre><code>selector.dtmDlgLimtTo.attr('readonly', true).datepicker({
changeMonth: true,
changeYear: true,
minDate: $("#idoffirstdateselector").datepicker("getDate") }),
yearRange: "0:+100"
});
</code></pre>
<p><code>idoffirstdateselector</code> is id of the first date selector.</p>
<p><strong>Edit</strong></p>
<p>You can try to set the mindate in onselect of firstdate picker.</p>
<pre><code>selector.dtmDlgLimitFrom.attr('readonly', true).datepicker({
changeMonth: true,
changeYear: true,
minDate: dateToday,
yearRange: "0:+100",
onSelect: function(date){
var date2 = $('#idoffirstdateselector').datepicker('getDate');
$('#idofseconddateselector').datepicker('option', 'minDate', date2);
}
});
</code></pre>
|
Find the approximate value in data.frame <p>There vector of ideal values, it looks like this:</p>
<pre><code>gr <- c(2.12, 7.58, 1.23, 6.98, 1.98, 3.45) # 6 numbers
</code></pre>
<p>And there data.frame with a large number rows (for example, show data.frame with five rows):</p>
<p><img src="http://i.stack.imgur.com/HA9V7.png" alt="enter image description here"></p>
<p>In data.frame choose the approximate values of the vector</p>
<p><img src="http://i.stack.imgur.com/Xd95a.png" alt="enter image description here"></p>
<p>The more cells in a row matched the better the line and choose.</p>
<p>in this case row 1 and 3.</p>
<p>Please help me in solving this problem.</p>
| <p>Let <code>v</code> be a column and a be the value to approximate for that column. Then we want to minimize <code>abs(sum(v * x) - a)</code> over all zero-one vectors <code>x</code>. The ones in <code>x</code> will either all be less than <code>a</code> or else will be the least value in <code>v</code> no smaller than <code>a</code>. We can solve the first one using integer linear programming (i.e. maximize <code>sum(v * x)</code> subject to <code>sum(v * x) <= a</code>) and then compare to the second which can be solved using <code>which.min</code> since if there are any values greater than <code>a</code> there can only be one 1 in <code>x</code>.</p>
<p>Now we want to do that for each column of the input data.frame and then form the x values found into a matrix and find the row or rows with the most ones.</p>
<pre><code>library(lpSolve)
opt <- function(v, a) {
soln <- lp("max", v, t(v), "<=", a, all.bin = TRUE)$solution
w <- which.min(replace(v, v < a, Inf))
if (a < min(v) || abs(a - sum(v * soln)) > abs(v[w] - a))
(w == seq_along(v))+0
else soln
}
x <- mapply(opt, DF, gr)
rs <- rowSums(x) # number of ones in each row
ix <- which(rs == max(rs)) # indexes of rows of x with most ones
</code></pre>
<p>which gives:</p>
<pre><code>> x
c c1 c2 c3 c4 c5
[1,] 1 1 0 1 0 0
[2,] 0 0 0 1 0 1
[3,] 0 0 1 0 0 0
[4,] 0 0 0 0 1 0
[5,] 0 0 0 1 0 0
> rs
[1] 3 2 1 1 1
> ix
[1] 1
</code></pre>
<p><strong>Note:</strong> The input in reproducible form is:</p>
<pre><code>DF <- data.frame(
c = c(1.01, 4.12, 6.91, 3.51, 7.23),
c1 = c(8.01, 5.12, 9.91, 1.51, 4.23),
c2 = c(4.51, 7.45, 2.98, 5.23, 7.04),
c3 = c(0.76, 4.51, 5.64, 4.67, 1.56),
c4 = c(2.54, 5.45, 8.67, 1.45, 5.67),
c5 = c(6.78, 2.56, 9.67, 4.67, 2.56))
gr <- c(2.12, 7.58, 1.23, 6.98, 1.98, 3.45)
</code></pre>
|
How to prevent this css shape to scroll left and right <p>I would like to keep this shape so it is responsive and keeps the same direction, and that it can still scroll down the page. The problem is that because of its size it scrolls left and right, which I wish to avoid. </p>
<p>If I set <code>overflow: hidden;</code> to its parent element (body), it causes all other content to vanish in the bottom when it reaches it.</p>
<p>Is there a way to prevent the page to scroll left and right, to "cut" the extra part? Thank you</p>
<p>Here's the fiddle: <a href="https://jsfiddle.net/oytvt0p7/" rel="nofollow">https://jsfiddle.net/oytvt0p7/</a></p>
<pre><code> #angled-shape {
width: 3000px;
height: 800px;
background-color: lightgrey;
margin-top: 50px;
margin-left: -1000px;
position: absolute;
z-index: -1;
overflow: hidden;
-ms-transform: rotate(-30deg); /* IE 9 */
-webkit-transform: rotate(-30deg); /* Safari */
transform: rotate(-30deg); /* Standard syntax */
}
<div id="angled-shape"></div>
</code></pre>
| <p>You can just set <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-x"><code>overflow-x: hidden;</code></a>, so scrolling in y direction will be nevertheless possible:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
overflow-x: hidden;
}
#angled-shape {
width: 3000px;
height: 800px;
background-color: lightgrey;
margin-top: 50px;
margin-left: -1000px;
position: absolute;
z-index: -1;
overflow: hidden;
-ms-transform: rotate(-30deg);
/* IE 9 */
-webkit-transform: rotate(-30deg);
/* Safari */
transform: rotate(-30deg);
/* Standard syntax */
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="angled-shape"></div></code></pre>
</div>
</div>
</p>
|
Icons separation and horizontal line behind <p>I search any problem but without results. Have big problem with separation of icons in inline-block after add css spearation ::after and ::before in the middle icon and with rwd of it.here's my code.</p>
<p>HTML:</p>
<pre><code><div class="icon-box">
<div class="icon_1"></div>
<div class="icon_2"></div>
<div class="icon_3"></div>
</div>
</code></pre>
<p>CSS:</p>
<pre><code>.icon_1 {
float: left;
display: inline-block;
height: 66px;
width: 66px;
background-image: url("../img/timing_icon.png");
background-color: #97735e;
background-position: center;
background-repeat: no-repeat;
}
.icon_2 {
float: left;
display: inline-block;
height: 66px;
width: 66px;
background-image: url("../img/presentation_icon.png");
background-color: #97735e;
background-position: center;
background-repeat: no-repeat;
}
.icon_3 {
float: left;
display: inline-block;
height: 66px;
width: 66px;
background-image: url("../img/accurate_icon.png");
background-color: #97735e;
background-position: center;
background-repeat: no-repeat;
}
.icon_2::before,
.icon_2::after {
display: inline-block;
content: "";
height: 10px;
border-bottom: 1px solid #97735e;
width: 100%;
}
.icon_2::before {
right: 100%;
margin-right: 10%;
}
.icon_2::after {
left: 100%;
margin-left: 200%;
}
</code></pre>
<p>I think my code is very messy and got to fix.</p>
<p>effect,what I want get <a href="http://i.stack.imgur.com/QcDp8.png" rel="nofollow">enter image description here</a></p>
| <p>first. you have common styles for all the <code>.icon_1,.icon_2,.icon_3</code> divs except the <code>background-image</code> . so, give a common class <code>icon</code> for example, to all those divs, or, if you can't change the HTML , use <code>.icon_1,.icon_2,.icon_3</code> instead of <code>.icon</code> in my example below. but don't write the same styles 3 times.</p>
<p>second. either use <code>display:inline-block</code> either use <code>float:left</code> . i chose to use <code>float:left;</code> because <code>inline-block</code> adds additional whitespaces between elements. ( if you want to use <code>inline-block</code> let me know . there are ways to override the whitespaces . )</p>
<p>third. add <code>margin:0 15px</code> to <code>.icon_2</code> which adds <code>margin-left</code> and <code>margin-right</code> of <code>15px</code></p>
<p>fourth. add the <code>pseudo-element</code> ( <code>:before</code> in my example ) to the div that wraps the three icons ,respectively <code>.icon-box</code> . and style it as you want. </p>
<p>i added <code>z-index:-1</code> so that the line ( <code>:before</code> ) goes under the icons.
added <code>background:red</code> to it so you can see that it goes under the icons.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.icon {
float:left;
height: 66px;
width: 66px;
background-color: #97735e;
background-position: center;
background-repeat: no-repeat;
position:relative;
}
.icon_1 {
background-image: url("../img/timing_icon.png");
}
.icon_2 {
background-image: url("../img/presentation_icon.png");
margin:0 15px;
}
.icon_3 {
background-image: url("../img/accurate_icon.png");
}
.icon-box { position:relative;width:auto;float:left;}
.icon-box:before {
content:"";
position:absolute;
height:1px;
background:red;
top:50%;
width:100%;
left:0;
z-index:-1;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="icon-box">
<div class="icon icon_1"></div>
<div class="icon icon_2"></div>
<div class="icon icon_3"></div>
</div></code></pre>
</div>
</div>
</p>
|
Retruning multiple objects and using them as arguments <p>I have a function which goes something like this:</p>
<pre><code>def do_something(lis):
do something
return lis[0], lis[1]
</code></pre>
<p>and another function which needs to take those two return objects as arguments:</p>
<pre><code>def other_function(arg1, arg2):
pass
</code></pre>
<p>I have tried:</p>
<pre><code>other_function(do_something(lis))
</code></pre>
<p>but incurred this error:</p>
<pre><code>TypeError: other_function() missing 1 required positional argument: 'arg2'
</code></pre>
| <p>You need to unpack those arguments when calling <code>other_function</code>. </p>
<pre><code>other_function(*do_something(lis))
</code></pre>
<p>Based on the error message, it looks like your other function is defined (and should be defined as)</p>
<pre><code>def other_function(arg1, arg2):
pass
</code></pre>
<p>So, when you return from <code>do_something</code>, you are actually returning a tuple containing <code>(lis[0], lis[1])</code>. So when you originally called <code>other_function</code>, you passing a single tuple, when your <code>other_function</code> was still expecting a second argument. </p>
<p>You can see this if you break it down a bit further. Below is a breakdown of how the returns look like when handled differently, a reproduction of your error and a demo of the solution: </p>
<p>Returning in to a single variable will return a tuple of the result:</p>
<pre><code>>>> def foo():
... lis = range(10)
... return lis[1], lis[2]
...
>>> result = foo()
>>> result
(1, 2)
</code></pre>
<p>Returning in to two variables, unpacks in to each var:</p>
<pre><code>>>> res1, res2 = foo()
>>> res1
1
>>> res2
2
</code></pre>
<p>Trying to call other_function with <code>result</code> which now only holds a tuple of your result:</p>
<pre><code>>>> def other_function(arg1, arg2):
... print(arg1, arg2)
...
>>> other_function(result)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: other_function() missing 1 required positional argument: 'arg2'
</code></pre>
<p>Calling other_function with <code>res1</code>, <code>res2</code> that holds each value of the return from <code>foo</code>:</p>
<pre><code>>>> other_function(res1, res2)
1 2
</code></pre>
<p>Using <code>result</code> (your tuple result) and unpacking in your function call to <code>other_function</code>:</p>
<pre><code>>>> other_function(*result)
1 2
</code></pre>
|
PHP SOAP Credentials in Header securityContext <p>Im struggling with this 2 days and trying almost everything I found on internet. I have SOAP service with username and password in header securityContext but have no idea how to provide data in that form in PHP?</p>
<p>This is required header XML:</p>
<pre><code><soap:Header>
<SecurityContext xmlns="http://tempuri.org/">
<userName>string</userName>
<password>string</password>
</SecurityContext>
</soap:Header>
</code></pre>
| <p>Huh, i managed it to work. Here is what is necessery if someone have similar problem.</p>
<p>Part for adding header values:</p>
<pre><code> $soap = new SoapClient($wsdl, $options);
$auth = array(
'userName' => self::SOAP_USERNAME,
'password' => self::SOAP_PASSWORD,
);
$header = new SoapHeader(self::SOAP_NAMESPACE, 'SecurityContext', $auth);
$soap->__setSoapHeaders($header);
</code></pre>
<p>Also, because it's https request I needed to add some ssl options:</p>
<pre><code> // set stream context opts
$opts = array(
"ssl" => array(
"verify_peer" => false,
"verify_peer_name" => false,
),
);
// set options
$options = array(
'encoding' => 'UTF-8',
'soap_version' => SOAP_1_2,
'cache_wsdl' => WSDL_CACHE_NONE,
'connection_timeout' => 15,
'login' => self::SOAP_USERNAME,
'password' => self::SOAP_PASSWORD,
'stream_context' => stream_context_create($opts),
);
</code></pre>
|
Multiple ViewModels in View WPF <p>How to,bind the property of first/second/third Viewmodel to a grid column in a single view.</p>
<p>How could I explicitly reference each property in the appropriate view model to grid column in view..! </p>
<pre><code>DataContext="{DynamicResource VMContainer}">
<Window.Resources>
<vm:VMContainer x:Key="VMContainer"/>
</Window.Resources>
public class VMContainer
{
public FirstViewModel VM1 { get; set; }
public SecondViewModel VM2 { get; set; }
public ThirdViewModel VM3 { get; set; }
}
</code></pre>
<p>If it is a single viewmodel, can do like below.</p>
<pre><code>ItemsSource="{Binding Source={StaticResource VMContainer}}
GridColumn Header="Salary" Binding="{Binding Salary, Mode=TwoWay}"
</code></pre>
<p>Tried like below:</p>
<pre><code><ListView ItemsSource="{Binding Source={StaticResource VMContainer}}">
<ListView.View>
<GridView x:Name="grdTest">
<GridViewColumn Header="Salary" DisplayMemberBinding="{Binding VM1.Salary / VMContainer.M1.Salry, Mode=TwoWay}" Width="100" />
</GridView>
</ListView.View>
InitializeComponent();
VMContainer VMC = new VMContainer();
DataContext = VMC;
</code></pre>
<p>How could I explicitly reference each property in the appropriate view model to grid column in view..!
View model composed of other view models(Composite ViewModel in wpf_mvvm)</p>
<p>Issue is, always VMC returns null, I would appreciate for any suggestion..!</p>
| <p>If your <em>UserControl</em> have a <em>DataContext</em> of your <em>MyClass</em> and container is a public property below:</p>
<pre><code>public MyClass
{
public VMContainer Container {get; set;}
}
</code></pre>
<p>Your binding should looks like:</p>
<pre><code>Binding="{Binding Container.VM1.Salary, Mode=TwoWay}"
</code></pre>
|
Directory.createDirectory creates files instead of directory in iOS <p>I have to save some data locally on iOS device for an Unity Game. Unity provide</p>
<pre><code> Application.persistentDataPath
</code></pre>
<p>to get public directory to save data. And printing it on console shows that this path returned for iOS is correct i.e. /Users/userName/Library/Developer/CoreSimulator/Devices/********-****-****-****-************/data/Containers/Data/Application/********-****-****-****-************/Documents/</p>
<p>So one function returns the path and other check if directory exists, if not it should create an directory but it creates FILE without any extension. Here is my code</p>
<pre><code> void savePose(Pose pose){
if (!Directory.Exists(PoseManager.poseDirectoryPath())){
Directory.CreateDirectory(PoseManager.poseDirectoryPath());
//Above line creates a file
//by the name of "SavedPoses" without any extension
}
// rest of the code goes here
}
static string poseDirectoryPath() {
return Path.Combine(Application.persistentDataPath,"SavedPoses");
}
</code></pre>
| <p>Possible sloutions:</p>
<p><strong>1</strong>.<code>Path.Combine(Application.persistentDataPath,"SavedPoses");</code> adds back slash before <code>savedPoses</code> while others are forward slashes. Maybe this causes a problem on iOS. Try raw string concatenating without the <code>Path.Combine</code> function.</p>
<pre><code>static string poseDirectoryPath() {
return Application.persistentDataPath + "/" + "SavedPoses";
}
</code></pre>
<p><strong>2</strong>.If the <code>Directory</code> class does not work properly, Use the <code>DirectoryInfo</code> class. </p>
<pre><code>private void savePose(Pose pose)
{
DirectoryInfo posePath = new DirectoryInfo(PoseManager.poseDirectoryPath());
if (!posePath.Exists)
{
posePath.Create();
Debug.Log("Directory created!");
}
}
static string poseDirectoryPath()
{
return Path.Combine(Application.persistentDataPath, "SavedPoses");
}
</code></pre>
<p><strong>EDIT</strong>:</p>
<p>Likely a permission problem on iOS.</p>
<p>You can should create the folder in the <a href="https://docs.unity3d.com/Manual/StreamingAssets.html" rel="nofollow"><code>StreamingAssets</code></a> directory. You have permission to read and write to this directory.</p>
<p>The general way to access this is with <code>Application.streamingAssetsPath/</code>.</p>
<p>On iOS, it can also be accessed with <code>Application.dataPath + "/Raw"</code>. </p>
<p>On Android, it can also be accessed with <code>"jar:file://" + Application.dataPath + "!/assets/";</code> and for Windows and Mac with <code>Application.dataPath + "/StreamingAssets";</code>. Just use the one that works for you.</p>
<p>For your question, <code>Application.dataPath + "/Raw"+"/SavedPoses";</code> should do it.</p>
|
parallelize() method while using SparkSession in Spark 2.0 <p>I see that <code>SparkSession</code> doesn't have <code>.parallelize()</code> method, Do we need to use <code>SparkContext</code> again to create a RDD?. If so, is creating both <code>SparkSession</code> & <code>SparkContext</code> in a single program advisable? </p>
| <p>Once you build your SparkSession, you can fetch the underlying SparkContext created with it as followed :</p>
<p>Let's consider that SparkSession is already defined :</p>
<pre><code>val spark : SparkSession = ???
</code></pre>
<p>You can get SparkContext now :</p>
<pre><code>val sc = spark.sparkContext
</code></pre>
|
Kentico Universal Pager update panel <p>I have a Pages data source, repeater, and universal pager. All is working, but i'm trying to avoid a QueryString and page reload. </p>
<p>I've set the universal pager to Post back, but that still forces a page reload. Checking Use update panel as well, changes the pagination states, but doesn't actually change the pages.</p>
<p>Is there another setting i'm missing?</p>
| <p>Put all the web parts in a separate zone and set the zone to "Use update panel". Make sure the "Use update panel" setting is off for the web parts themselves though.</p>
|
Facebook sharing not work <p><strong>I used the below code for facebook sharing. It is working with google and twitter but not working in fb.Please help me with this code.</strong></p>
<pre><code><meta property='og:type' content='website' />
<meta property='og:title' content='<?php echo $title; ?>' />
<meta property='og:locale' content='nl-BE' />
<meta property='og:url' content='<?php echo ROOT_WWW; ?>' />
<meta property='og:site_name' content='Immo Margriet' />
<meta property='og:image' content='<?php echo $met_img; ?>' />
<meta property='og:description' content='<?php echo strip_tags($met_intro); ?>'>
</code></pre>
<p><strong>And facebook button as like below.</strong></p>
<p>http://www.facebook.com/sharer.php?s=100&p[title]=&p[summary]=&p[url]=&p[images][0]=','sharer','toolbar=0,status=0,width=548,height=325');" href="javascript: void(0);" title="Facebook"><p>Share on Facebook</p></p>
| <p>Check the URL in Facebook Debug Tool, <a href="https://developers.facebook.com/tools/debug/" rel="nofollow">https://developers.facebook.com/tools/debug/</a>. Scrape your URL again and again and check. It will display the error that you are missing.</p>
<p>The minimum image size is 200 x 200 pixels. If you try to use an image smaller than this you will see an error in the Sharing Debugger.</p>
<p>Refer the link,</p>
<p><a href="https://developers.facebook.com/docs/sharing/best-practices#images" rel="nofollow">https://developers.facebook.com/docs/sharing/best-practices#images</a></p>
|
Append one by one in input text from checkboxes <p>I have a <code>jQuery</code> script that appends all checkboxes values into one <code><input type="text"/></code> with <code>','</code>, but when I check one box, it appends all the values from the others checkboxes aswell, and I want only to append those I checked in sequence.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('.check_list').on('change', function() {
var n = $(this).siblings('input:checkbox');
var nControl = $('.codeParc');
if ($(this).prop('checked')) {
n.prop('checked', true);
var vals = nControl.map(function() {
return $(this).val();
}).get().join(',');
} else {
n.prop('checked', false);
}
$('#test').val(vals);
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input style="cursor: pointer;" type="checkbox" value="" class="check_list"></input>
<input type="checkbox" class="codeParc" value="1"></input>
<input type="checkbox" class="codeParc" value="2"></input>
<input type="checkbox" class="codeParc" value="3"></input>
<input type="text" id="test" value=""></input></code></pre>
</div>
</div>
</p>
<p>This code is returning me all values <code>1,2,3</code> whenever I check one checkbox, what I need is to check one box and display only his number, and then append the rest when they are checked.</p>
| <p>Firstly note that <code>input</code> elements are self-closing, so its <code><input /></code>, not <code><input></input></code>.</p>
<p>A simpler way to do this would be to map the selected values in to an array and update the text of the <code>input</code> with the values from that array each time a checkbox is clicked, something like this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('.check_list').change(function() {
$('.codeParc').prop('checked', this.checked);
updateText();
});
$('.codeParc').change(function() {
$('.check_list').prop('checked', $('.codeParc').length == $('.codeParc:checked').length);
updateText();
});
function updateText() {
var checkedValues = $('.codeParc:checked').map(function() {
return this.value;
}).get();
$('#test').val(checkedValues.join(','));
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input style="cursor: pointer;" type="checkbox" value="" class="check_list" />
<input type="checkbox" class="codeParc" value="1" />
<input type="checkbox" class="codeParc" value="2" />
<input type="checkbox" class="codeParc" value="3" />
<input type="text" id="test" value="" /></code></pre>
</div>
</div>
</p>
|
check if click is outside of Element - on removed item <p>I tried the jquery way with closest, to check if a click is outside of an Element:</p>
<pre><code>$(document).click(function(event) {
if(!$(event.target).closest("#wrapper").length) {
console.log($(event.target))
console.log("click outside of #wrapper");
}
});
$("#remove-me").click(function(){
$(this).remove();
console.log("remove me clicked");
});
$("#click-me").click(function(){
console.log("click clicked");
});
<div id="wrapper">
<div id="remove-me">click me to remove from dom</div>
<div id="click-me">click me</div>
</div>
</code></pre>
<p>But if i click <code>#remove-me</code>, the <code>div</code> gets removed from the DOM - its now somewhere in space - and it wont find any <code>closest()</code>. The suprising thing is that the <code>document</code> listener still gets the click AND the element, although its not in the DOM anymore...</p>
<p>How would i properly find a way, if this <code>div</code> is inside of my wrapper.
Is this a jQuery Problem or is there a pure Javascript way?
Why is the <code>$(document).click()</code> listener still trigger on the removed element?</p>
<p>One way i found out to check if the <code>div</code> has no <code>parent()</code>...</p>
<p>Codepen Example: <a href="http://codepen.io/urtopal/pen/BLJgrQ" rel="nofollow">http://codepen.io/urtopal/pen/BLJgrQ</a></p>
<hr>
<p>Summary/Question:</p>
<ol>
<li>Why is an listener on an removed Element still triggered(example above "click outside of #wrapper" should not be executed if <code>#remove-me</code> is clicked)?</li>
<li>How to resolve this? No trigger at all / or how to check if removed?</li>
</ol>
| <p>Try this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).click(function(event) {
if($(event.target).prop("tagName").toLowerCase() == "html") {
console.log("click outside of #wrapper");
}
});
$("#remove-me").click(function(){
$(this).remove();
console.log("remove me clicked");
});
$("#click-me").click(function(){
console.log("click clicked");
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#wrapper {
background-color: #ccc;
padding: 50px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<div id="remove-me">click me to remove from dom</div>
<div id="click-me">click me</div>
</div></code></pre>
</div>
</div>
</p>
|
Math in a NodeRed function block <p>I am trying to do a math function in a function-block in Node-RED but it can only handle easier task like multiply.</p>
<p>I am trying to do this function but it can't handle the exponents(^). Perhaps there is a math function or something to declare this? It just returns a wacko number as it is now.</p>
<pre><code>msg.payload = (6*10^47)/(msg.payload^16.66);
return msg;
</code></pre>
| <p>You can use the cmath header which contains the pow function, in your case it would look something like: </p>
<pre><code>#include <cmath>
msg.payload = (6*std::pow(10,47))/(std::pow(msg.payload,16.66));
return msg;
</code></pre>
<p>The number returned is the first parameter raised by the second. </p>
|
Why subroutine needs to be written after the declaration of variables used in it? <p>Let's assume we have this code, why it fails with the explicit package name error since the function is called only after the declaration of the <code>$value</code>?</p>
<pre><code>use strict;
use warnings;
sub print_value{
print "\n$value";
}
my $value = 2;
print_value();
</code></pre>
<p>This fails at compile time with :</p>
<pre><code>Global symbol "$value" requires explicit package name at file.pl line 5.
Execution of file.pl aborted due to compilation errors.
</code></pre>
<p>And this code works perfectly fine: </p>
<pre><code>use strict;
use warnings;
my $value = 2;
print_value();
sub print_value{
print "\n$value";
}
</code></pre>
<p>Ignore the unutility of this programming style or the deprecated coding style, just focus on the context.</p>
| <p>It's because of <a href="https://en.wikipedia.org/wiki/Scope_(computer_science)" rel="nofollow"><strong>scope</strong></a>. That's where in your program your variable is visible. Your <code>$value</code> is a <em>lexical</em> variable because you have declared it with <code>my</code>. That means, it exists inside a certain scope (and all the ones below that). In both of your examples that scope is the entire file (which can also be called <em>the global scope</em>). </p>
<p>Perl looks at your code in two stages. The first is <em>compile time</em>, where it checks the syntax and loads dependencies (like <code>use</code> statements). At this point, it will look for the availability of <code>$value</code> inside the function.</p>
<p>Perl will look in these places:</p>
<ol>
<li><p>Lexical (<code>my</code> and <code>our</code>) variables currently in scope.</p>
<p>A variable is in scope (i.e. a variable is visible) if the code that references it follows the declaration, and if it's in the same block as the declaration, or block nested within that block. The file itself is a block, and curlies form the others.</p>
<p>If there are multiple lexical variables with the same name in scope, the most recently declared obscure the others. That means that a variable declared in the function itself will be used before one outside the function.</p>
<pre><code>my $i; # +--------- $i is in scope (visible) here
my $x; # | +------- $x is in scope (visible) here
while (...) { # | |
my $j; # | | +---- $j is in scope (visible) here
my $x; # | | +-- This different $x is in scope (visible) here
... # | v v
} # | |
sub foo { # | |
my $j; # | | +---- This different $j is in scope (visible) here
my $x; # | | +-- This third $x is in scope (visible) here
... # | v v
} # | |
... # v v
</code></pre></li>
<li><p>Package variables</p>
<p>These are globally variables (undeclared, or declared with <code>use vars</code>).</p>
<p>Perl will look in the namespace declared by the latest "package" in scope (defaulting to <code>main</code>), except for "super-global" variables. This refers to the symbolic variables (like <code>$_</code>, <code>$$</code>, etc) for which Perl looks in <code>main</code> rather than the current package.</p></li>
</ol>
<p>Since <code>$value</code> hasn't been declared, Perl takes it to mean package variable <code>$main::value</code> (since the <code>main</code> is the default package).</p>
<pre><code>use strict; # | Code here will use package var $main::value
use warnings; # |
# |
sub print_value{ # |
print "\n$value"; # |
} # |
# v
my $value = 2; # | Code here will use this lexical var $value
print_value(); # v
</code></pre>
<p>None of this comes because you have <code>strict</code> turned on. Only the fact that you <em>have to declare variables</em>, either with <code>my</code>, or <code>our</code> or by using a fully qualified name is because of <code>use strict</code>.</p>
<p>If you did not have <code>strict</code> and did not declare the variable with <code>my</code>, your program would work. <code>$value</code> would be a package variable in that case.</p>
<p>In your second example you have declared <code>$value</code> before the subroutine, so Perl knows at compile time that there will be a <code>$value</code> available in that scope, so it doesn't complain.</p>
<pre><code>use strict; # | Code here will use package var $main::value
use warnings; # |
# v
my $value = 2; # | Code here will use this lexical var $value
print_value(); # |
# |
sub print_value{ # |
print "\n$value"; # |
} # v
</code></pre>
<hr>
<p>However, a better approach would be to pass the variable as an argument to <code>print_value</code>.</p>
<pre><code>use strict;
use warnings;
sub print_value{
my $arg = shift;
print "\n$arg";
}
my $value = 2;
print_value($value);
</code></pre>
<p>Now Perl sees that there is a <code>$arg</code> inside of the small scope. It doesn't know its value, but it doesn't have to. And <code>$value</code> is also already declared before using it.</p>
<p>Never use variables from the global scope (the entire file) inside of functions. Always pass them as arguments<sup>1</sup>.</p>
<hr>
<p>Here are some relevant links:</p>
<ul>
<li><a href="http://perlmaven.com/scope-of-variables-in-perl" rel="nofollow">Tutorial on scope on perlmaven</a></li>
<li><a href="http://perldoc.perl.org/perlmod.html#BEGIN%2C-UNITCHECK%2C-CHECK%2C-INIT-and-END" rel="nofollow">order of execution in perlmod</a></li>
</ul>
<p><sup>1) unless you want to build a singleton or some other type of <a href="https://en.wikipedia.org/wiki/Closure_(computer_programming)" rel="nofollow">closure</a></sup></p>
|
css |Â button:hover background still grey <p>I noticed that the buttons (button.term) next to the grid turn grey when hover. I've set the pseudo classes (hover, focus, active, visited) to white!important, but it still doesn't work.</p>
<p><a href="https://dercampus.ch/en/" rel="nofollow">Website</a></p>
| <p>Add to the css:</p>
<p><code>box-shadow:none;</code></p>
<pre><code>.is-desktop #course_grid button.term {
flex-basis: 7.5%;
color: transparent!important;
background: no-repeat center center;
background-color: white !important;
background-size: contain;
opacity: 0.7;
box-shadow: none;
}
</code></pre>
|
Display NULL if some value is not found in SQL <p>I have a sample data here</p>
<pre>
id name
----------
1 Test1
2 Test2
3 Test3
4 Test4
</pre>
<p>So when I execute this QUERY</p>
<pre><code>select id,name from table1 where name IN ('Test1','Test3','Test5')
</code></pre>
<p>It gives me an output of </p>
<pre>
id name
----------
1 Test1
3 Test3
</pre>
<p>Is there any way I can get ouput like this</p>
<pre>
id name
----------
1 Test1
3 Test3
null Test5
</pre>
| <p>You could use <a href="https://msdn.microsoft.com/en-us/library/dd776382.aspx" rel="nofollow">table value constructors</a>(>= 2008):</p>
<pre><code>SELECT CASE WHEN EXISTS(SELECT 1
FROM table1 t
WHERE E.Name = t.Name)
THEN E.Id
ELSE NULL END AS Id,
Name
FROM (VALUES(1,'Test1'),(3,'Test3'),(5,'Test5')) E(Id,Name)
</code></pre>
|
Get commands by two criteria <p>How can we execute Get-Command command to get result by two criteria? Let's say it this way: I want in one execution to get list of commands that starts with <strong>Add</strong> or <strong>Get</strong></p>
<p>Documentation of <code>Get-Command</code> command states that <code>-Verb</code> attribute accepts multiple verbs or verb pattern, but I don't get it how?</p>
| <p>For me it worked like this: </p>
<pre><code>Get-Command -verb Get,Add
</code></pre>
|
How to Increase socket memory allocation in Linux kernel <p>I'm implementing a custom transport layer datagram protocol in the Linux kernel. I've implement send and receive Queues for in-order delivery in lossy environments.</p>
<p>I noticed that with my current implementation, My socket runs out of memory with only 16 socket buffers with BUFSIZ payload in the queue. So I need to increase the value of memory allocated to my socket.</p>
<p>I figured that changing the values of <code>sk->sk_sendbuf</code> and <code>sk->sk_rcvbuf</code> should do the job. What is the correct way to do this?</p>
<p>P.S.- I haven't implemented the sysctl interface for this protocol yet, so can't use that for memory management.</p>
<p>Thanks.</p>
| <p>As it turns out, I need not define the sysctl interface manually for my protocol. I just used the following sysctl command on my test machine to increase the amount of memory allocated to each socket</p>
<pre><code>sysctl -w net.core.wmem_default=<new_value>
sysctl -w net.core.wmem_max=<new_value>
</code></pre>
<p>To select the <code>new_value</code>, I first checked the existing value of these parameters with</p>
<pre><code>sysctl -n net.core.wmem_default
sysctl -n net.core.wmem_max
</code></pre>
<p>Note that the actual memory assigned to the socket will be twice the <code>new_value</code>, that's just how the implementation is in the kernel.</p>
|
import a function to use the scope it is called from <p>Using Meteor, I am trying to use a function from one file on a template's scope lays in a different file. I tried using an arrow function:</p>
<p>first file:</p>
<pre><code>export const myFunc = ()=>{
console.log(this.x);
};
</code></pre>
<p>second file:</p>
<pre><code>import {myFunc} from './myFunc.js';
Template.MyTemplate.onCreated(function(){
this.x = 4;
myFunc(); //undefined
});
</code></pre>
<p>what is the best way of affecting template's variables using functions that aren't defined at the template itself? (I need those functions for some other templates as well)</p>
| <p>What about passing your template's variables as parameters to the function?
Combining that with the use of ReactiveVar you can set them in myFunc</p>
<pre><code>import { myFund } from './myFunc.js'
Template.MyTemplate.onCreated(function () {
this.myVar = new ReactiveVar('Foo');
});
Template.myTemplate.onRendered(function() {
myFunc(this.myVar);
console.log(this.myVar.get()) // 'Bar'
});
</code></pre>
<p>and in your function file</p>
<pre><code>export const myFunc = (myVar) => {
//Use myVar
myVar.set('Bar')
};
</code></pre>
|
Spring Security hasIpAddress causes errors <p>In my configuration, I have defined that:</p>
<pre><code>@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
</code></pre>
<p>And with the following code:</p>
<pre><code> http.exceptionHandling()
.authenticationEntryPoint(authEntryPoint)
.and()
.authorizeRequests()
.antMatchers("/api/payment").permitAll()
//.antMatchers("/api/payment").hasIpAddress("XXX.XXX.X.XX")
...
</code></pre>
<p>Now, when I have permited all traffic to '/api/payment', everything gets executed.</p>
<p>However, if I try to enable the IP verification:</p>
<pre><code> http.exceptionHandling()
.authenticationEntryPoint(authEntryPoint)
.and()
.authorizeRequests()
//.antMatchers("/api/payment").permitAll()
.antMatchers("/api/payment").hasIpAddress("XXX.XXX.X.XX")
...
</code></pre>
<p>The requests send from the given IP address receive the following response:</p>
<pre><code>{"errorMessage":"Not Found","errorId":"6ae34aa3-9195-42d6-8906-996906988ce0","errorDetails":null}
</code></pre>
<p>What am I doing wrong?</p>
<p><strong>EDIT</strong></p>
<p>This is the method that I am invoking:</p>
<pre><code>@RequestMapping(value = "/payment", method = POST)
public String saveOrder(@ModelAttribute PaymentDto paymentDto) {
paymentService.savePayment(paymentDto);
return "OK";
}
</code></pre>
<p>Since I always send request data (for example, the post is on the following url: <code>api/payment?id=123&whatever</code>)</p>
<p>I've added:</p>
<pre><code>.antMatchers("/api/payment?**").access("hasIpAddress('XXX.XXX.X.XX')")
</code></pre>
<p>But this didn't worked neither.</p>
<p><strong>UPDATE 2</strong></p>
<p>I've changed placement of my antMatcher like this:</p>
<pre><code>http.exceptionHandling()
.authenticationEntryPoint(authEntryPoint)
.and()
.authorizeRequests()
.antMatchers("/", "/app/**", "/assets/**", "/fonts/**", "/images/**").permitAll()
.antMatchers("/authentication/login", "/login.html").anonymous()
.antMatchers("/api/products/**").permitAll()
.antMatchers("/api/cities/**").permitAll()
.antMatchers("/api/order/**").permitAll()
.antMatchers("/api/payment").hasIpAddress("XXX.XXX.X.XX")
.anyRequest().authenticated()
.and()
.csrf().requireCsrfProtectionMatcher(new CsrfRequestMatcher())
.and()
.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/authentication/login")
.successHandler(authSuccessHandler)
.failureHandler(authFailureHandler)
.and()
.logout()
.logoutUrl("/authentication/logout")
.logoutSuccessHandler(logoutSuccessHandler)
.deleteCookies(JSESSIONID_COOKIE, CSRF_COOKIE)
.invalidateHttpSession(true)
.permitAll();
</code></pre>
<p>Which now just redirects me to the login page when I am trying to make a post from the given Ip Address</p>
| <p>So as I turned out, I was receiving the request via proxy from nginx, which wasn't passing the original IP address of a requester. I had to add some additional nginx configuration, and now, I can verify IP address like this:</p>
<pre><code>@RequestMapping(value = "/payment", method = POST)
public String saveOrder(PaymentDto paymentDto, HttpServletRequest request) {
if (request.getHeader("X-Forwarded-For").equals("XXX.XXX.X.XX")){
DO STUFF
}
}
</code></pre>
|
Android Bluetooth Low Energy: Not hearing advertisements on some devices <p>I have a device that is emitting Bluetooth Low Energy (BLE) advertisements and a Nexus 7 (2013) Android tablet that should hear those advertisements. However, it cannot hear the BLE advertisements from my device and appears not to hear any BLE advertisements (there are some BLE beacons in the area). The same goes with a ca. 2014 Moto G phone I tried.</p>
<p>However, an LG G4, a Samsung S4 and a Samsung S5 will pick upp precisely those advertisements.</p>
<p>Is there potentially some configuration I can modify for the Nexus 7 2013 device so it can hear those BLE advertisements? My internet survey suggests that the Nexus 7 2013 is BLE capable (as opposed to the Nexus 7 2012 which isn't).</p>
<p>Is there some way to detect (e.g. via some API) whether a given device can listen to BLE advertisements?</p>
<p>EDIT:
Tried this on a different Nexus 7 and it worked there. For reference I'm using this app to search for BLE advertisements: <a href="https://github.com/gardarh/android-blescanner" rel="nofollow">https://github.com/gardarh/android-blescanner</a></p>
| <p>You need to activate location in the settings to receive ble scan results on Android 6+</p>
|
Insert data row-wise instead of column-wise and 1 blank row after each record <p>Here is my code:</p>
<pre><code>wb = Workbook()
dest_filename = 'book.xlsx'
th_list = ["this", "that", "what", "is", "this"]
ws1 = wb.active
ws1.title = 'what'
for row in range(1, 2):
for col in range(1, len(th_list)):
_ = ws1.cell(column=col, row=row, value="{0}".format(th_list[col].encode('utf-8')))
wb.save(filename = dest_filename)
</code></pre>
<p>After running the py file I get the data this way:</p>
<pre><code> A B C D E
1 this that what is this
</code></pre>
<p>While I want the data this way:</p>
<pre><code> A
1 this
2 that
3 what
4 is
5 this
</code></pre>
<p>and also insert 1 empty row between each row like this:</p>
<pre><code> A
1 this
2
3 that
4
5 what
6
7 is
8
9 this
</code></pre>
<p>I am trying to change my code to fulfill the requirement. I will also post my code as answer if I find the solution.</p>
<p><strong>EDIT:</strong> Okay I have successfully converted data from row-wise into column-wise with modifying for loops. But still unable to add empty rows after each record. Here is the code:</p>
<pre><code>wb = Workbook()
dest_filename = 'book.xlsx'
th_list = ["this", "that", "what", "is", "this"]
ws1 = wb.active
ws1.title = 'what'
for col in range(1, 2):
for row in range(1, len(th_list)+1):
_ = ws1.cell(column=col, row=row, value="{0}".format(th_list[row-1].encode('utf-8')))
wb.save(filename = dest_filename)
</code></pre>
| <p>Why are you writing something so incredibly complicated?</p>
<pre><code>for v in th_list:
ws.append([v]) # pad as necessary, never encode
ws.append() # blank row
</code></pre>
|
Default values are incorrect in html angular application <p>In this angularjs application I have a login page initially where the user types Username and Password. Once in the application, they can chose another page that requires a different username and password for database access. I want the database username to default to a different value than the login and the password to be blank with a placeholder of <code>Enter a password</code>. However, the defaults in the database page are using the initial login values.<br>
This is the html of the login page:</p>
<pre><code><div class="form-group">
<label for="username" class="col-sm-2 control-label">Username</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="username" name="username" placeholder="Username" style="width: 80%" autofocus ng-model="credentials.username" />
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="password" name="password" placeholder="Password" style="width: 80%" ng-model="credentials.password" />
</div>
</div>
</code></pre>
<p>This is the html of the database login:</p>
<pre><code><div class="row" style="margin-top: 10px; margin-bottom: 10px;">
<label id="inputDBUserNameLabel" style="margin-left: 10px;" >User Name: </label>
<input id="inputDBUserNameText" type="text" ng-model="inputUserName" class="form-control demoInput" value="test" style="margin-left: 5px; width: 25%;"/>
</div>
<div class="row" style="margin-top: 10px; margin-bottom: 10px;">
<label id="inputDBPasswordLabel" style="margin-left: 10px;" >Password: </label>
<input id="inputDBPasswordText" type="password" ng-model="inputPassword" class="form-control demoInput" placeholder="Enter a password" style="margin-left: 5px; width: 25%;"/>
</div>
</code></pre>
<p>What am I doing wrong?</p>
<p><strong>UPDATE</strong>
Below is the code to my controller when connecting to the the database.<br>
When entering the correct username and password it works:</p>
<pre><code>'use strict';
angular.module('vow-administration-ui')
.controller('UpgradeCtrl', ['$scope', 'UpgradeDB',
function($scope, upgradeDB) {
$scope.title = "Upgrade Database";
$scope.inputServerName = '';
$scope.inputDatabaseName = '';
$scope.inputUserName = '';
$scope.inputPassword = '';
$scope.outputServerName = '';
$scope.outputDatabaseName = '';
$scope.outputUserName = '';
$scope.outputPassword = '';
$scope.UpgradeDatabase = function(){
upgradeDB.save({
inputServerName: $scope.inputServerName,
inputDatabaseName: $scope.inputDatabaseName,
inputUserName: $scope.inputUserName,
inputPassword: $scope.inputPassword,
outputServerName: $scope.outputServerName,
outputDatabaseName: $scope.outputDatabaseName,
outputUserName: $scope.outputUserName,
outputPassword: $scope.outputPassword
}).$promise.then(function(response) {
var responseText = response;
console.log(responseText);
});
};
}]);
</code></pre>
<p><strong>UPDATE</strong>
I removed the <code>ng-model=inputUserName</code> and both the UserName and Password fields were changed to the expected values. That is the UserName field had the default of <code>test</code> and the Password field had the placeholder of <code>Enter a password</code> even though I did NOT remove the <code>ng-model</code> attribute from the password field.</p>
<p><strong>UPDATE</strong>
Login Controller:</p>
<pre><code>angular.module('vow-administration-ui')
.controller('LoginCtrl', function($scope, $rootScope, $location, AUTH_EVENTS, AuthService) {
$scope.isProcessing = false;
$scope.credentials = {
domain: '',
username: '',
password: ''
};
$scope.login = function() {
AuthService.authenticateAdministrator($scope.credentials).then(function() {
$scope.errorMessage = '';
$scope.errorState = false;
$location.path('/launch').replace();
},
function(error) {
AuthService.destroyToken();
$scope.errorMessage = 'Failed to authorize. ' + error.data.ExceptionMessage;
$scope.errorState = true;
});
};
});
</code></pre>
| <p>Corrected the problem...
It is Google Chrome that was the problem.
Apparently, when you use ids that are a form of 'username' and 'password' Chrome tries to 'help' by inserting the previous text that was used as a username and password.</p>
<p>To fix the problem, I changed my ng-model names to variations of UsrNm and Pwd.</p>
<p>It works now.</p>
|
How can I create a variable in a service that gets its data from a promise yet is shared between two components? <p>I have a service in an Angular 2 using TypeScript. I want to be able to share an array of values that I get from that service. when one component makes a change to the array I need it to be reflected in another component. </p>
<p>This is the basics of my service and the object it uses</p>
<pre><code>export class deviceObj {
device_Id:number;
deviceGroup_Id:number;
name:string;
favoriteFlag:boolean;
visibleFlag:boolean;
}
export class Favorite {
favorite_Id: number;
device: deviceObj;
constructor(){this.device = new deviceObj()};
}
@Injectable()
export class FavoriteService {
private headers = new Headers({'Content-Type': 'application/json'});
private favoritesURL = 'URL THAT FEETCHES DATA';
favorites: Favorite[];
constructor(private http: Http) {
this.getFavorites().then(favorites => this.favorites = favorites);
}
getFavorites(): Promise<Favorite[]> {
return this.http.get(this.favoritesURL).toPromise().then(response => response.json() as Favorite[]).catch(this.handleError);
}
protected handleError2(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'server error');
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); //
return Promise.reject(error.message || error);
}
}
</code></pre>
<p>And here is one of the components that gets the array of favorites.</p>
<pre><code> import {FavoriteService} from'../../services/favorite/favorite.service';
declare var jQuery: any;
@Component({
selector: '[sidebar]',
directives: [
ROUTER_DIRECTIVES,
SlimScroll
],
template: require('./sidebar.html')
})
export class Sidebar implements OnInit {
constructor(config: ConfigService, el: ElementRef, router: Router, location: Location,
private favoriteService:FavoriteService) {
}
getFavorites(): void{
this.favoriteService
.getFavorites()
.then(favorites => this.favorites = favorites);
}
</code></pre>
<p>In each component that uses the service it has its own favorites array that gets assigned on load. However I want a singleton variable in the service where changes can be reflected in two components. I'm not sure how to do this with promises. I am happy to clarify further if needed. Any help would greatly be apreciated.</p>
| <p>@Krenom's answer was corrrect. with one import needing to be changed on my setup.</p>
<p>I needed <code>import { Observable, Observer } from 'rxjs/Rx';import { Observable, Observer } from 'rxjs/Rx';</code></p>
|
Select folder path with writefile() <p>I success to extract the content (blob) into a file.
However, how to change the file destination to another folder ?</p>
<pre><code>Attach database 'serverFilesDatabase.db' as db1;
Attach database 'ServerDatabase.db' as db2;
Select writefile((b.filename),(data)) from db1.files a inner join db2.filesTable b on a.fileId= b.fileId Limit 1;
</code></pre>
| <p>My colleague, find the solution for this problem under Windows :</p>
<pre><code>Select writefile(( "C:\\MyPath\\" || b.filename),(data)) from db1.files a inner join db2.filesTable b on a.fileId= b.fileId Limit 1;
</code></pre>
|
Why is Burn elevating? <p>Why is my <code>perUser</code> bundle elevating?</p>
<p>I have 3 packages in my chain. Here's a log snippet:</p>
<pre><code>[0BD8:0324][2016-10-06T15:23:57]i201: Planned package: NetFx461Web, state: Present, default requested: Present, ba requested: Present, execute: None, rollback: None, cache: No, uncache: No, dependency: None
[0BD8:0324][2016-10-06T15:23:57]i201: Planned package: ClientMSI, state: Absent, default requested: Present, ba requested: Present, execute: Install, rollback: Uninstall, cache: Yes, uncache: No, dependency: None
[0BD8:0324][2016-10-06T15:23:57]i201: Planned package: Dummy, state: Absent, default requested: Present, ba requested: None, execute: None, rollback: None, cache: No, uncache: No, dependency: None
[0BD8:0324][2016-10-06T15:23:57]i299: Plan complete, result: 0x0
[0BD8:0324][2016-10-06T15:23:57]i300: Apply begin
[0BD8:0324][2016-10-06T15:23:57]i010: Launching elevated engine process.
[0BD8:0324][2016-10-06T15:24:03]i011: Launched elevated engine process.
[0BD8:0324][2016-10-06T15:24:04]i012: Connected to elevated engine.
[00B4:0B98][2016-10-06T15:24:04]i358: Pausing automatic updates.
</code></pre>
<p>As you can see in the log, just the ClientMSI package should be installed. It's a <code>dual purpose package</code>:</p>
<pre><code><Property Id="ALLUSERS" Value="2" />
<Property Id="MSIINSTALLPERUSER" Value="1" />
</code></pre>
<p>The user can select in my custom Burn UI (WPF) If he wants the msi installation to be <code>perUser</code> or <code>perMachine</code>. According to the selection of the user, I do this:</p>
<pre><code><MsiProperty Name='MSIINSTALLPERUSER' Value='1' /> <!--perUser-->
<MsiProperty Name='MSIINSTALLPERUSER' Value='' /> <!--perMachine-->
</code></pre>
<p>The bundle always gets installed <code>perUser</code> (I forced this by adding a dummy msi package in which I have set <code>InstallScope="perUser"</code>. This makes the bundle <code>perUser</code> at compile time.</p>
<p>If the user selects <code>perUser</code> installation, there is one package which gets installed (ClientMSI) which is <code>perUser</code>, and the bundle also gets installed <code>perUser</code>. There is no reason for elevation!</p>
<p>My guess is that burn assumes, ClientMSI is an <code>perMachine</code> package, because <code>ALLUSERS</code> is set to <code>2</code> and this confuses burn. Can somebody confirm that?</p>
<p>Thanks for your help in advance!</p>
| <p>You should be getting a warning like this while compiling the bundle:</p>
<blockquote>
<p>Bundles require a package to be either per-machine or per-user. The MSI '{0}' ALLUSERS Property is set to '2' which may change from per-user to per-machine at install time. The Bundle will assume the package is per-{1} and will not work correctly if that changes. If possible, remove the Property with Id='ALLUSERS' and use Package/@InstallScope attribute instead.</p>
</blockquote>
<p>WiX currently decides the scope of the MSI at compile time, so WiX probably decided that it would be per-machine.</p>
|
get select option value using onchange function in jQuery from multiple dynamic record? <p>Here is my code </p>
<pre><code>foreach($test as $val){
<select name="change" onchange="Change()" id="change-<?=$val['id']?>" data-id="<?php echo $val['id'];?>">
<option value="1">one</option>
<option value="20">two</option>
<option value="21">three</option>
</select>
}
</code></pre>
<p>jQuery function</p>
<pre><code> function Change(){
alert($(this).val());
}
</code></pre>
<p>In this code I want different time different value with id.</p>
| <p>Replace <code>onchange="Change()"</code> with <code>onchange="Change(this)"</code> In HTML part.</p>
<p>And function should be as below.</p>
<pre><code>function Change(el){
alert("value : "+el.value+" and Id : "+el.id+' and data-id : '+el.getAttribute("data-id"));
}
</code></pre>
<p><strong>Please check Working snippet :</strong> </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function Change(el){
alert("value : "+el.value+" and Id : "+el.id+' and data-id : '+el.getAttribute("data-id"));
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><select name="change" onchange="Change(this)" id="change-1" data-id="1">
<option value="1">one</option>
<option value="20">two</option>
<option value="21">three</option>
</select></code></pre>
</div>
</div>
</p>
|
How to avoid side effects while using Binding in JavaFX between model and view? <p>Let me explain my problem with the following vehicle example:</p>
<p>I've got:</p>
<ul>
<li>IntegerProperty: <strong>speed</strong></li>
<li>BooleanProperty: <strong>crash</strong></li>
<li>JavaFX slider element: <strong>speed_slider</strong>. (where I can set a speed from 0-50.)</li>
<li>JavaFX button element: <strong>crash_button</strong>.</li>
</ul>
<p>I've successfully done:</p>
<p>Bound <strong>speed</strong> to the value of <strong>speed_slider</strong>.
That works. When I'm changing the value of the <strong>speed_slider</strong>, the <strong>speed</strong> changes. </p>
<p>But now I want to expand this. I tried the following:</p>
<p>Bound <strong>crash</strong> to the selectedValue of <strong>crash_button</strong>.
Bound <strong>speed</strong> to: if <strong>crash</strong> false, then value of <strong>speed_slider</strong>, else value 0.</p>
<p>Up here it works: Whenever <strong>crash</strong> is true, <strong>speed</strong> turns 0. If <strong>crash</strong> is false, it takes the value of <strong>speed_slider</strong>. And here is the problem:
I want the <strong>speed_slider</strong> value is automatically changes to 0, when <strong>speed</strong> does change to 0 due to <strong>crash</strong>. When I try to bind the value of <strong>speed_slider</strong> to <strong>speed</strong> it does not work, it causes an endless loop and fails- how to solve that problem without using listeners? </p>
| <p>I think the solution is simple, instead of unidirectional bindings, use bidirectional:</p>
<pre><code>speed.bindBidirectional(speed_slider.valueProperty());
</code></pre>
<p>Then you can still do a unidirectional binding with the crash and others etc. All this does is make sure the slider is always in sync with the speed, no matter which of these change.</p>
|
Ajax receiving the incorrect error from PHP <p>I am attempting to set up modal for a project in which a client would be able to update their favorite team, city of birth and their size. Upon not entering some of the information I would like an error message to be returned to them but the only error message being echoed is "City was not updated as there was not new information submitted."</p>
<p>the modal code is as follows:</p>
<pre><code><!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria- labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="city">You were born in:</label>
<input type="text" class="form-control" id="city" placeholder="city">
</div>
<div class="form-group">
<label for="favorite_team">Favorite team:</label>
<input type="text" class="form-control" id="favoriteTeam" placeholder="favorite team">
</div>
<div class="form-group">
<label for="size">size:</label>
<input type="text" class="form-control" id="size" placeholder="size">
</div>
<div class="alert alert-success" id="successAlert" role="alert" style="display: none"></div>
<div class="alert alert-danger" id="updateFail" style="display:none" > </div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal" >Close</button>
<button type="button" class="btn btn-primary" id="saveBtn" onClick="Changes()">Save changes</button>
</div>
</div>
</div>
</div>
</code></pre>
<p>my ajax code is:</p>
<pre><code> function Changes(){
$.ajax({
type: "POST",
url: "../php_parsers/update_parse.php",
data: "city=" + $("#city").val() + "&favoriteTeam=" + $("#favoriteTeam").val() + "&size=" + $("#size").val(),
success: function(result) {
if (result == "success") {
$("#successAlert").html(result).show();
} else {
$("#updateFail").html(result).show();
}
}
})
}
</code></pre>
<p>my php code is update_parse.php:</p>
<pre><code><?php
// AJAX CALLS THIS UPDATE CODE TO EXECUTE
$error = "";
$success = "";
if(!$_POST['city']){
$error .= "City was not updated as there was not new information submitted.";
} else if(!$_POST['team']){
$error .= "Team was not updated as there was not new information submitted.";
} else if(!$_POST['size']){
$error.= "size was not updated as there was not new information submitted.";
}
if($error == ""){
echo $error;
}else {
$success = "update successful so far";
echo $success;
}
?>
</code></pre>
<p>All feed back is welcomed.</p>
| <p>You are using <code>if else if</code> construct for you checks which will only report at most one error. Change it to independent if statements</p>
<pre><code>if(!$_POST['city']){
$error .= "City was not updated as there was not new information submitted.";
}
if(!$_POST['team']){
$error .= "Team was not updated as there was not new information submitted.";
}
if(!$_POST['size']){
$error.= "size was not updated as there was not new information submitted.";
}
</code></pre>
|
laravel 5 reletionship hasMany on two columns <p>I'm trying to implement relationship on two columns, record_id and table_name, </p>
<p>here is what I got so far, Model name BatteryAssets: </p>
<pre><code>public function Attachments()
{
return $this->hasMany('App\Attachments','record_id','id')->where('tabel_name','`battery_assets`');
}
</code></pre>
<p>please note that 'battery_asstes' is a string, so it's not dynamic, I'm trying to make it as a string, but get the following error : </p>
<pre><code>QueryException in Connection.php line 761:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tabel_name' in 'where clause' (SQL: select * from `attachments` where `attachments`.`record_id` = 1 and `attachments`.`record_id` is not null and `tabel_name` = `battery_assets`)
</code></pre>
<p>as you see I'm I have tried to put battery_assets into `` and also I've tried to put them into double quotes ' "battery_assets" ' and also no quotes</p>
<p>and also please not that BatteryAssets table does not have table_name column, I'm only want to use it as a static value in the where clause, also I've tryied to do </p>
<pre><code>->where('attachments.tabel_name','"battery_assets"');
</code></pre>
<p>but It gives the same error</p>
| <p>The error says Colomn not found, the column name you are trying to 'call' is called 'tabel_name'. Are you sure the column name isn't 'table_name'? (table in english and not dutch, atleast I think you are dutch)</p>
<p>So it should be:</p>
<pre><code>public function Attachments()
{
return $this->hasMany('App\Attachments','record_id','id')->where('table_name','`battery_assets`');
}
</code></pre>
<p>If your column is called 'tabel_name' in your database. I would recommend using English naming, since 'name' is English.</p>
|
rspec error michael hartl lesson 3 <p>while executing the command</p>
<p>$ bundle exec rspec spec/requests/static_pages_spec.rb</p>
<p>i get this error
/home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.0.8/lib/active_support/dependencies.rb:229:in <code>require': cannot load such file -- test/unit/assertions (LoadError)
from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.0.8/lib/active_support/dependencies.rb:229:in</code>block in require'
from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.0.8/lib/active_support/dependencies.rb:214:in <code>load_dependency'
from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.0.8/lib/active_support/dependencies.rb:229:in</code>require'
from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rspec-rails-2.13.1/lib/rspec/rails/adapters.rb:3:in <code><top (required)>'
from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.0.8/lib/active_support/dependencies.rb:229:in</code>require'
from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.0.8/lib/active_support/dependencies.rb:229:in <code>block in require'
from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.0.8/lib/active_support/dependencies.rb:214:in</code>load_dependency'
from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.0.8/lib/active_support/dependencies.rb:229:in <code>require'
from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rspec-rails-2.13.1/lib/rspec/rails.rb:11:in</code>'
from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.0.8/lib/active_support/dependencies.rb:229:in <code>require'
from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.0.8/lib/active_support/dependencies.rb:229:in</code>block in require'
from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.0.8/lib/active_support/dependencies.rb:214:in <code>load_dependency'
from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.0.8/lib/active_support/dependencies.rb:229:in</code>require'
from /home/sarfraz/Desktop/Rails Apps/sample_app/spec/spec_helper.rb:4:in <code><top (required)>'
from /home/sarfraz/Desktop/Rails Apps/sample_app/spec/requests/static_pages_spec.rb:1:in</code>require'
from /home/sarfraz/Desktop/Rails Apps/sample_app/spec/requests/static_pages_spec.rb:1:in <code><top (required)>'
from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rspec-core-2.13.1/lib/rspec/core/configuration.rb:819:in</code>load'
from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rspec-core-2.13.1/lib/rspec/core/configuration.rb:819:in <code>block in load_spec_files'
from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rspec-core-2.13.1/lib/rspec/core/configuration.rb:819:in</code>each'
from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rspec-core-2.13.1/lib/rspec/core/configuration.rb:819:in <code>load_spec_files'
from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rspec-core-2.13.1/lib/rspec/core/command_line.rb:22:in</code>run'
from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rspec-core-2.13.1/lib/rspec/core/runner.rb:80:in <code>run'
from /home/sarfraz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rspec-core-2.13.1/lib/rspec/core/runner.rb:17:in</code>block in autorun'</p>
<p>this is my gemfile:
source '<a href="https://rubygems.org" rel="nofollow">https://rubygems.org</a>'</p>
<h1>Bundle edge Rails instead: gem 'rails', github: 'rails/rails'</h1>
<p>gem 'rails', '4.0.8'</p>
<h1>Use sqlite3 as the database for Active Record</h1>
<p>group :development, :test do
gem 'sqlite3'
gem 'rspec-rails', '2.13.1'
end</p>
<p>group :test do
gem 'selenium-webdriver', '2.35.1'
gem 'capybara', '2.1.0'
end</p>
<h1>Use SCSS for stylesheets</h1>
<p>gem 'sass-rails', '~> 4.0.2'</p>
<h1>Use Uglifier as compressor for JavaScript assets</h1>
<p>gem 'uglifier', '>= 1.3.0'</p>
<h1>Use CoffeeScript for .js.coffee assets and views</h1>
<p>gem 'coffee-rails', '~> 4.0.0'</p>
<h1>gem 'therubyracer', platforms: :ruby</h1>
<h1>Use jquery as the JavaScript library</h1>
<p>gem 'jquery-rails'</p>
<p>gem 'turbolinks'</p>
<p>gem 'jbuilder', '~> 1.2'</p>
<p>group :doc do
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', require: false
end</p>
<p>group :production do
gem 'pg', '0.15.1'
gem 'rails_12factor', '0.0.2'
end</p>
<h1>Use ActiveModel has_secure_password</h1>
<h1>gem 'bcrypt', '~> 3.1.7'</h1>
<h1>Use unicorn as the app server</h1>
<h1>gem 'unicorn'</h1>
<h1>Use Capistrano for deployment</h1>
<h1>gem 'capistrano', group: :development</h1>
<h1>Use debugger</h1>
<h1>gem 'debugger', group: [:development, :test]</h1>
<p>please help i cannot proceed totally stuck..
Thanks in advance</p>
| <p>It seems the test/unit libraries are being loaded instead of the RSpec libraries. Review the contents of spec/spec_helper.rb and spec/rails_helper.rb, and the 'require' statements in the spec files to ensure that they match the instructions in the Hartl tutorial. Also, make sure you are using the current tutorial, and the recommended Ruby and Rails versions.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.