text:
Q: Bootstrap 4, how to auto-scroll to opened tab content? When viewing my page on a mobile phone, the user clicks on a tab and has no way to know it opened since it is down below and requires scrolling to see it.
When a user clicks the tab, I would like it to auto-scroll to the open content.
I've tried following the solution here but am unable to get it to work for my specific page:
Bootstrap tabs scroll effect to content when clicked
Any help will be greatly appreciated!
Thanks,
Tim

jQuery(document).ready(function($) {

  $('.nav a').click(function(e) {
    e.preventDefault()
    $(this).tab('show')
  })

  $('a.scroll').on('click', function(e) {
    var href = $(this).attr('href');
    $('html, body').animate({
      scrollTop: $(href).offset().top
    }, 'slow');
    e.preventDefault();
  });

});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

            Tuesday Muay Thai & Mixed Martial Arts
            Wednesday Muay Thai & Mixed Martial Arts
            Thursday Muay Thai, Mixed Martial Arts & Boxing
            Saturday Muay Thai

Click to see the schedule

                  6:45PM - 7:30PM

Muay Thai Kickboxing

In attition to learning brutally effective kicking, punching, elbow and knee techniques, you can expect a great workout from this fun class.

— Tim Mousel Muay Thai Instructor

                  7:30PM - 8:15PM

Mixed Martial Arts (MMA)

This comprehensive class teaches the fundamentals as well as the advanced techniques of MMA.

 Erik Paulson's Combat Submission Wrestling (CSW) will also be taught.

Beginner to Professional levels are welcome.

— Tim Mousel MMA Coach

                  6:45PM - 7:30PM

Muay Thai Kickboxing

In attition to learning brutally effective kicking, punching, elbow and knee techniques, you can expect a great workout from this fun class.

— Roy Eubank Muay Thai Instructor

                  7:30PM - 8:15PM

Mixed Martial Arts (MMA)

This comprehensive class teaches the fundamentals as well as the advanced techniques of MMA.

Erik Paulson's Combat Submission Wrestling (CSW) will also be taught.

Beginner to Professional levels are welcome.

— Roy Eubank MMA Coach

                  6:45PM - 7:30PM

Muay Thai Kickboxing

In attition to learning brutally effective kicking, punching, elbow and knee techniques, you can expect a great workout from this fun class.

— Tim Mousel Muay Thai Instructor

                  7:30PM - 8:15PM

Mixed Martial Arts (MMA)

This comprehensive class teaches the fundamentals as well as the advanced techniques of MMA.

Erik Paulson's Combat Submission Wrestling (CSW) will also be taught.

Beginner to Professional levels are welcome.

— Tim Mousel MMA Coach

                  7:15PM - 8:15PM

Boxing

All experience levels are welcome to attend this class taught by professional boxer, Pat Swan.

— Pat Swan Boxing Coach

                  12:00PM - 12:45PM

Muay Thai Kickboxing

In addition to learning brutally effective kicking, punching, elbow and knee techniques, you can expect a great workout from this fun class.

— Tim Mousel Muay Thai Instructor

A: Use shown.bs.tab event

This event fires on tab show after a tab has been shown. Use
  event.target and event.relatedTarget to target the active tab and the
  previous active tab (if available) respectively.

$('a.nav-link').on('shown.bs.tab', function(e) {
  var href = $(this).attr('href');
  $('html, body').animate({
    scrollTop: $(href).offset().top
  }, 'slow');
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

            Tuesday Muay Thai & Mixed Martial Arts
            Wednesday Muay Thai & Mixed Martial Arts
            Thursday Muay Thai, Mixed Martial Arts & Boxing
            Saturday Muay Thai

Click to see the schedule

                  6:45PM - 7:30PM

Muay Thai Kickboxing

In attition to learning brutally effective kicking, punching, elbow and knee techniques, you can expect a great workout from this fun class.

— Tim Mousel Muay Thai Instructor

                  7:30PM - 8:15PM

Mixed Martial Arts (MMA)

This comprehensive class teaches the fundamentals as well as the advanced techniques of MMA.

 Erik Paulson's Combat Submission Wrestling (CSW) will also be taught.

Beginner to Professional levels are welcome.

— Tim Mousel MMA Coach

                  6:45PM - 7:30PM

Muay Thai Kickboxing

In attition to learning brutally effective kicking, punching, elbow and knee techniques, you can expect a great workout from this fun class.

— Roy Eubank Muay Thai Instructor

                  7:30PM - 8:15PM

Mixed Martial Arts (MMA)

This comprehensive class teaches the fundamentals as well as the advanced techniques of MMA.

Erik Paulson's Combat Submission Wrestling (CSW) will also be taught.

Beginner to Professional levels are welcome.

— Roy Eubank MMA Coach

                  6:45PM - 7:30PM

Muay Thai Kickboxing

In attition to learning brutally effective kicking, punching, elbow and knee techniques, you can expect a great workout from this fun class.

— Tim Mousel Muay Thai Instructor

                  7:30PM - 8:15PM

Mixed Martial Arts (MMA)

This comprehensive class teaches the fundamentals as well as the advanced techniques of MMA.

Erik Paulson's Combat Submission Wrestling (CSW) will also be taught.

Beginner to Professional levels are welcome.

— Tim Mousel MMA Coach

                  7:15PM - 8:15PM

Boxing

All experience levels are welcome to attend this class taught by professional boxer, Pat Swan.

— Pat Swan Boxing Coach

                  12:00PM - 12:45PM

Muay Thai Kickboxing

In addition to learning brutally effective kicking, punching, elbow and knee techniques, you can expect a great workout from this fun class.

— Tim Mousel Muay Thai Instructor

A: Try to add scroll animation inside a setTimeout and click on a.nav-link instead of a.scroll.

jQuery(document).ready(function($) {

  $('.nav a').click(function(e) {
    e.preventDefault()
    $(this).tab('show')
  })

  $('a.nav-link').on('click', function(e) {
    var href = $(this).attr('href');
    setTimeout(() => {
      $('html, body').animate({
        scrollTop: $(href + '.active').offset().top
      }, 'slow');
    }, 500);
    e.preventDefault();
  });
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

            Tuesday Muay Thai & Mixed Martial Arts
            Wednesday Muay Thai & Mixed Martial Arts
            Thursday Muay Thai, Mixed Martial Arts & Boxing
            Saturday Muay Thai

Click to see the schedule

                  6:45PM - 7:30PM

Muay Thai Kickboxing

In attition to learning brutally effective kicking, punching, elbow and knee techniques, you can expect a great workout from this fun class.

— Tim Mousel Muay Thai Instructor

                  7:30PM - 8:15PM

Mixed Martial Arts (MMA)

This comprehensive class teaches the fundamentals as well as the advanced techniques of MMA.

 Erik Paulson's Combat Submission Wrestling (CSW) will also be taught.

Beginner to Professional levels are welcome.

— Tim Mousel MMA Coach

                  6:45PM - 7:30PM

Muay Thai Kickboxing

In attition to learning brutally effective kicking, punching, elbow and knee techniques, you can expect a great workout from this fun class.

— Roy Eubank Muay Thai Instructor

                  7:30PM - 8:15PM

Mixed Martial Arts (MMA)

This comprehensive class teaches the fundamentals as well as the advanced techniques of MMA.

Erik Paulson's Combat Submission Wrestling (CSW) will also be taught.

Beginner to Professional levels are welcome.

— Roy Eubank MMA Coach

                  6:45PM - 7:30PM

Muay Thai Kickboxing

In attition to learning brutally effective kicking, punching, elbow and knee techniques, you can expect a great workout from this fun class.

— Tim Mousel Muay Thai Instructor

                  7:30PM - 8:15PM

Mixed Martial Arts (MMA)

This comprehensive class teaches the fundamentals as well as the advanced techniques of MMA.

Erik Paulson's Combat Submission Wrestling (CSW) will also be taught.

Beginner to Professional levels are welcome.

— Tim Mousel MMA Coach

                  7:15PM - 8:15PM

Boxing

All experience levels are welcome to attend this class taught by professional boxer, Pat Swan.

— Pat Swan Boxing Coach

                  12:00PM - 12:45PM

Muay Thai Kickboxing

In addition to learning brutally effective kicking, punching, elbow and knee techniques, you can expect a great workout from this fun class.

— Tim Mousel Muay Thai Instructor


text:
Q: NotificationListenerService как проверить установлен ли звук на уведомление public class NotifGetService extends NotificationListenerService {

    @Override
        public void onNotificationPosted(StatusBarNotification sbn) {

            sbn.getNotification().sound //всегда null
        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: request google speech to text API using android volley I'm working on an Android Application that record a speech using the mic of the android device, after that i  encode the recorded speech into base64 format. to transform the speech into a text i use google speech cloud api and  android Volley to send request to google Api. the probleme is when i call the methode for requesting i got this error  ==>
E/Volley: [5921] BasicNetwork.performRequest: Unexpected response code 400 for https://speech.googleapis.com/v1/speech:recognize?key={mykey}
Here is My Code :
    public class SpeechService {

    private String Url ="https://speech.googleapis.com/v1/speech:recognize?key=${mykey}";

        private RequestQueue requestQueue ;
        private AppCompatActivity app ;
        String savedata ;

        public SpeechService(AppCompatActivity app){

            this.app = app ;
            requestQueue = Volley.newRequestQueue(app.getApplicationContext());
        }

    public void getTextFromGSpeech1(String EncodedSpeech){

        JSONObject jsonObject = new JSONObject();
        JSONObject config = new JSONObject() ;
        JSONObject audio = new JSONObject() ;

        try {

            config.put("encoding", MediaRecorder.OutputFormat.AMR_WB);
            config.put("SampleRateHertz","rba9 rba9");
            config.put("languageCode","fr-FR");
            audio.put("content",EncodedSpeech);

            jsonObject.put("audio", audio );
            jsonObject.put("config", config);

        } catch (JSONException e) {
            e.printStackTrace();
        }

        JsonObjectRequest JObjectREQUEST = new JsonObjectRequest(Request.Method.POST , Url  , jsonObject ,new Response.Listener<JSONObject>(){

            @Override
            public void onResponse(JSONObject response) {

                System.out.println("JSON response is  ============> ");
                System.out.println(response);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                System.out.println("failed ...............;");

            }
        }){

            @Override
            public String getBodyContentType() {
                return "application/json; charset=utf-8";
            }

        };

        requestQueue.add(JObjectREQUEST);

    }
}

and the Json object format must be like this
 {   "audio": {
            "content": ""
          }
            ,
          "config": {
            "encoding": "ENCODING_UNSPECIFIED",
            "languageCode": "fr-FR",
            "sampleRateHertz": 1600
          }
        }

A: It should be RecognitionConfig.AudioEncoding.AMR_WB, not MediaRecorder.OutputFormat.AMR_WB. Sample rate is also wrong.


text:
Q: Want to add cross icon or close button in modal/popup body to close the modal Here this is my code:-
<button type="button" class="popupvideo" data-toggle="modal" data-target="#myModal"></button>

  <button type="button"></button>

and i have added this also
<button type="button" class="btn btn-danger" data-dismiss="modal"></button>

but it is showing outside the Modal.


text:
Q: Pandas-Dataframe Parallel Apply (Swifter, TQDM::process_map) Freezes? when called I have a dataframe with ~15k paths to audio files with on which I want to perform an operation (artificially add noise). Generally the whole thing works, but takes a long time even with less (16) records. The problem is not the execution time of the function but the time until all is initialized.
start = time.time()
data_augmented = data_augmented.swifter.progress_bar(True, desc="Merge Sounds") \
        .apply(merge_sounds(**settings), axis=1)
print(f"{time.time-(start)} - Map Timer")

Merge Sounds: 100%|█████████████████████████████| 16/16 [00:07<00:00,  2.09it/s]
26.973325729370117 - Map Timer

As you can see here, the initialization takes almost 4 times as long as the runtime of the Lambda Function (merge_sounds). With initialization-time im referring to elapsed_time_measured_by_myself - elapsed_time_measured_by_tqdm so in this case 26.97.. - 7 = 19.97

    start = time.time()
    lambda_fn = merge_sounds(**settings) #doesnt work if i put it in the line below.
    data_augmented = process_map(lambda_fn, data_augmented, max_workers=threads,
                                     desc=f"Merge_sounds [{threads} Threads]")
    print(f"{time.time-(start)} - Map Timer")

is stuck at:
Merge_sounds [16 Threads]:   0%|                         | 0/16 [00:00<?, ?it/s]

    with Pool(processes=16) as pool:
        data_augmented = pool.map(merge_sounds(**settings), tqdm(data_augmented, desc=f"Merge Sounds: {16} Threads"))

is stuck at:
Merge Sounds: 16 Threads:  38%|██████          | 6/16 [00:00<00:00, 4697.75it/s]

I know that parallelization doesn't make sense for smaller datasets, I'm just puzzled why I can easily parallelize everything everywhere in the code and I just can't get ahead here. I later run this code on alot of data so if parallelism would work, i would be very happy.
The Function used within Map is:
def merge_sounds(**settings):
    _range = settings.get("snr_range", (0.15, 0.65))
    assert len(_range), "snr_range -> e.g. (0.15, 0.75)"
    target_sample_rate = settings.get("target_sample_rate", "16000")

    if "target_path" not in settings.keys():
        raise Exception("please Specify target_path in Settings-Dict")
    target_path = Path(settings["target_path"])
    target_path.mkdir(parents=True, exist_ok=True)

    def __call__(item):
        _target_path = item["path_augmented"]

        snr = round(uniform(_range[0], _range[1]), 4)
        pad_idx = item.name

        yp, _ = IO.load(item["path"], sample_rate=target_sample_rate)
        yn, _ = IO.load(item["path_noise"], sample_rate=target_sample_rate)
        item["snr"] = snr

        y_augmented = Effect.add_noise(yp, yn, snr=snr, pad_idx=pad_idx)
        IO.save_wav(y_augmented, _target_path, target_sample_rate)
        return item

    return __call__

Is there anything im Forghetting to Parallelise the Map Function (seems to work with one of this variations everywhere else in my code just as excpected)
Ty in advanced.

A: If fixed this Issue by Bypassing TQDM. I zipped the Columns i needed something like this
    _paths_in = _df["path_input"]
    _paths_out = _df["path_output"]
    _path_noise = _df["path_noise"]
    job = zip(_paths_in, _path_noise, _paths_out, _filter_jobs)

and then i just passed this to MultiProcessor Function.
    jobs = list(enumerate((zip_jobs(df))))

    with Pool(processes=_threads) as pool:
        data_augmented = pool.map(execute_job, tqdm(jobs, desc=f"Audio-Augmentation: {_threads} Threads"))

merge_sounds and the new execute_jobare similar, it just changed, what parameter the function needs.


text:
Q: How can I MERGE multiple folders and Files to a new single folder? I Have A folder named "SCENERY" on Drive F (F:\SCENERY)
SCENERY contains several folders: A,B,C... etc
I would like to MERGE the contents of A,B,C... etc to another folder on Drive F named "BASEFILES" (F:\BASEFILES)
Is this possible?
Question Edited:
Powershell script used & Output:

PS C:\Windows\system32> (Get-ChildItem 'F:\Scenery*' -Directory).FullName |
ForEach-Object { Join-Path $_ '*' } |
Copy-Item -Destination 'F:\BaseFiles' -WhatIf
What if: Performing the operation "Copy Directory" on target "Item: F:\Scenery\XP11_HD_Mesh_V4\XP11_HD_Mesh_V4_+60-020-Europe Destination: F:\BaseFiles\XP11_HD_Mesh_V4_+60-020-Europe".
What if: Performing the operation "Copy Directory" on target "Item: F:\Scenery\XP11_HD_Mesh_V4\XP11_HD_Mesh_V4_+70+020-Europe Destination: F:\BaseFiles\XP11_HD_Mesh_V4_+70+020-Europe".
PS C:\Windows\system32>

A: If you want all the subfolders of F:\SCENERY, this PowerShell would work:

*

*The destination folder, F:\BaseFiles, should be created prior to
running this command.

(Get-ChildItem 'F:\Scenery\*' -Directory).FullName |
     ForEach-Object { Join-Path $_ '*' } |
         Copy-Item -Destination 'F:\BaseFiles' -Recurse

Edit:
Don't copy line-by-line, it's a single pipeline:
(Get-ChildItem 'F:\Scenery\*' -Directory).FullName | ForEach-Object { Join-Path $_ '*' } | Copy-Item -Destination 'F:\BaseFiles' -Recurse

*

*To verify what will happen, run this version first:

(Get-ChildItem 'F:\Scenery\*' -Directory).FullName |
     ForEach-Object { Join-Path $_ '*' } |
         Copy-Item -Destination 'F:\BaseFiles' -Recurse -WhatIf

*

*The -WhatIf parameter previews the operation without performing it.

Using aliases, the first command reduces to:
(gci 'F:\Scenery\*' -ad).FullName |
     % { Join-Path $_ '*' } |
         Copy -s 'F:\BaseFiles'


text:
Q: Error de dependencias en Java con SpringBoot (bean) estoy intentado crear una aplicación para aprender, pero al ejecutarla me encuentro con el siguiente error:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'authController': Unsatisfied dependency expressed through field 'rolService';
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'rolService': Unsatisfied dependency expressed through field 'rolRepository';
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'rolRepository' defined in com.porfolioDanielLlanes.demo.Security.Repository.RolRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException:
Could not create query for public abstract java.util.Optional com.porfolioDanielLlanes.demo.Security.Repository.RolRepository.finByRolNombre(com.porfolioDanielLlanes.demo.Security.Enums.RolNombre); Reason: Failed to create query for method public abstract java.util.Optional com.porfolioDanielLlanes.demo.Security.Repository.RolRepository.finByRolNombre(com.porfolioDanielLlanes.demo.Security.Enums.RolNombre)! No property 'finByRolNombre' found for type 'Rol'; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.Optional com.porfolioDanielLlanes.demo.Security.Repository.RolRepository.finByRolNombre(com.porfolioDanielLlanes.demo.Security.Enums.RolNombre)! No property 'finByRolNombre' found for type 'Rol'

La clase principal
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

la clase rolService

package com.porfolioDanielLlanes.demo.Security.Service;

import com.porfolioDanielLlanes.demo.Security.Entity.Rol;
import com.porfolioDanielLlanes.demo.Security.Enums.RolNombre;
import com.porfolioDanielLlanes.demo.Security.Repository.RolRepository;
import java.util.Optional;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Transactional
public class RolService {
    @Autowired
    RolRepository rolRepository;

    public Optional<Rol> getByRolNombre(RolNombre rolNombre){
        return rolRepository.finByRolNombre(rolNombre);
    }

    public void  save(Rol rol){
        rolRepository.save(rol);
    }
}

La clase RolRepository
package com.porfolioDanielLlanes.demo.Security.Repository;

import com.porfolioDanielLlanes.demo.Security.Entity.Rol;
import com.porfolioDanielLlanes.demo.Security.Enums.RolNombre;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface RolRepository extends JpaRepository<Rol, Integer>{
    Optional<Rol> finByRolNombre(RolNombre rolNombre);
}

El proyecto importa mas clases en el controlador, pero creo que el problema radica en alguna dependecia de la clase RolService o RolRepository que hace que los métodos no puedan ser ejecutados


text:
Q: C++ STL: Trouble with iterators I'm having a beginner problem:
bool _isPalindrome(const string& str)
{
    return _isPalindrome(str.begin(), str.end()); // won't compile
}

bool _isPalindrome(string::iterator begin, string::iterator end)
{
    return begin == end || *begin == *end && _isPalindrome(++begin, --end);
}

What am I doing wrong here? Why doesn't str.begin() get type checked to be a string::iterator?
Update: Better version:
bool BrittlePalindrome::_isPalindrome(string::const_iterator begin, string::const_iterator end)
{
    return begin >= end || *begin == *(end - 1) && _isPalindrome(++begin, --end);
}

A: str.begin() is non-const, while the argument str is const.
You can either change the iterator-accepting method to accept const_iterators, or you can change the string-accepting method to accept a non-const string.
Or you could cast away str's const-ness, but that would be a patent Bad Idea TM.
(I would also parenthesize your return statement on the iterator-accepting method to make your intent more clear, but that's neither here nor there.)

A: Assuming that you have a declaration of the second function before the first function, the main issue is that you are passing the strings by const reference.
This means that the only overloads of begin() and end() that you have access to are the const versions which return std::string::const_iterator and not std::string::iterator.
The convention for iterators is that the end iterator points one beyond the end of a range and is not dereferencable - certainly if you pass str.end() as the end parameter. This means that *begin == *end is not valid, you need to decrement end once first. You are also going to have an issue with ranges with odd numbers of elements. By doing ++begin and --end with no further checking your iterators may cross over in the recursion rather than triggering the begin == end condition.
Also note that for maximum portability, global identifiers shouldn't start with an underscore.

A: As previously mentioned your iterators need to be constant iterators, but there's something else wrong with your algorithm. It works fine if you have a string of odd length, but do you see what happens when your string is even length? Consider the palindrome:
aa
Your algorithm will pass in an iterator pointing to the front and to the end. All's good, then it will go to the next level, and all will still be good, but it won't end. Because your first condition will never be true. You need to check not only if begin==end but if begin+1==end or begin==end-1 if you prefer. Otherwise you're iterators are going to be upset.

A: What error are you getting?
Have you tried this?
bool _isPalindrome(string::const_iterator begin, string::const_iterator end)

A: *

*replace iterator by const_iterator

*swap function definitions

*decrement end
Code:
bool isPalindrome(string::const_iterator begin, string::const_iterator end)
{
  return (begin == end || begin == --end ||
          *begin == *end && isPalindrome(++begin, end));
}

bool isPalindrome(const string& str)
{
    return isPalindrome(str.begin(), str.end());
}

A: You haven't declared the second function before calling it in the first function. The compiler can't find it and thus tries to convert str.begin() (string::iterator) into a const string &. You can move the first function behind the second function.


text:
Q: get data from local Json file ionic 3 I start a dummy project in Ionic. I try to get data from a local Json file but I have this error :

I don't understand why there is no provider for HttpClient.
For further details, I actually tried to follow this tutorial : https://www.youtube.com/watch?v=vuc4dp0qHSc
How can I fix this error and get the data ?
Versions
Ionic 3.18.0
Angular 5.0.1
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { FirstPage } from '../pages/first/first';
import { CardsDataProvider } from '../providers/cards-data/cards-data';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    FirstPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    FirstPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    CardsDataProvider,

  ]
})
export class AppModule {}

cards-data.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';

/*
  Generated class for the CardsDataProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class CardsDataProvider {

  constructor(public http: HttpClient) {
    console.log('Hello CardsDataProvider Provider');
  }

  getLocalData() {
  this.http.get('../assets/data/cards.json').map(res => res.json()).subscribe(data =>
  {
    console.log(data);
  });
}
}

home.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { FirstPage } from '../first/first';
import { CardsDataProvider } from '../../providers/cards-data/cards-data';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController, public CardsService: CardsDataProvider) {

  }
  openFirstPage() {
    this.navCtrl.push(FirstPage);
  }

  ionViewDidLoad() {
    this.CardsService.getLocalData();
  }
}

Any help will be appreciated.

A: You are following an Ionic2 tutorial while using Ionic3 with Angular5.
For Http to work since Ionic 3.0, you need to include HttpClientModule in your imports in app.module.ts.
import {HttpClientModule} from '@angular/common/http';//import

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    FirstPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    HttpClientModule//include here
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    FirstPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    CardsDataProvider,

  ]
})
export class AppModule {}

Also, in your cards-data.ts,
import {Http} from '@angular/common/http';

@Injectable()
export class CardsDataProvider {

  constructor(public http: HttpClient) { //change here
    console.log('Hello CardsDataProvider Provider');
  }

For further changes to go from Ionic 2 to 3 check here. For changes required to go to Angular 5 check here.
A simpler way is to find a more recent tutorial.


text:
Q: Redux + Typescript + funtional component: imported component requires props that come from Redux I have a component that looks something like this:

*

*it has an interface with "alerts" property

*it is connected to Redux and gets "alerts" from props.

interface IAlert {
  alerts: { id: string; type: string; msg: string }[];
}

const Alert: FC<IAlert> = ({ alerts }) => {
  return (
    //does something with alerts
  );
};

Alert.propTypes = {
  alerts: PropTypes.array.isRequired
};

const mapStateToProps = (state: any): object => ({
  alerts: state.alerts
});

export default connect(mapStateToProps, {})(Alert);

The Problem is:
When I import this component (that creates the Alerts) into another components I get this:
Property 'alerts' is missing in type '{}' but required in type 'Pick<IAlert, "alerts">'.ts(2741)

I don't want to pass "alerts" into the imported elemnt but just get it from Redux.
Thanks for the help!

A: It's a lot easier to get typescript support by using the useSelector hook like in @Jannis's answer.
You can get proper typing with connect.  The reason that you aren't getting it here is because the types of your mapStateToProps function are incorrect.
const mapStateToProps = (state: any): object => ({
  alerts: state.alerts
});

connect makes it so that the connected version of the component no longer requires the props which are added by mapStateToProps or mapDispatchToProps.  But what props are those?.  The type definition for your mapStateToProps doesn't say that it returns a prop alerts.  It just returns object.
Returning IAlert makes your error go away because now connect knows that the alerts prop has already been provided.
const mapStateToProps = (state: any): IAlert => ({
  alerts: state.alerts
});

If you have a proper type for your state instead of any then you shouldn't need any return type at all.  For this particular component, your IAlert props type actually describes both the required state and the return.
const mapStateToProps = (state: IAlert) => ({
  alerts: state.alerts
});

But generally you want to get the state type from your store or reducer as described here.
export type RootState = ReturnType<typeof rootReducer>

export type RootState = ReturnType<typeof store.getState>

You'll need to use that RootState in useSelector, but there's a helpful shortcut so that don't need to assign the type every time that you use it.  You can create your own typed version of the useSelector hook as explained here.
import { TypedUseSelectorHook, useSelector } from 'react-redux'
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector

So now your component doesn't need any props, and the type of the alerts variable is known based on the type of the state
export default () => {

  const alerts = useAppSelector(state => state.alerts);

  return (
    //does something with alerts
  );
};


text:
Q: erf() not defined when solving NL optimization problem with JuMP I'm solving a non-linear optimization problem with JuMP in Julia, there is an erf() called in my objective function. My code throws an error saying that erf() function is not defined.
I have called Pkg.update(), loaded the SpecialFunction package and swtiched among different solvers (NLopt, Itopt) but none of them worked.
Here follows the environment and the minimized code which I tested under Julia 1.0.3
julia> versioninfo()
Julia Version 1.0.3
Commit 099e826241 (2018-12-18 01:34 UTC)
Platform Info:
  OS: Windows (x86_64-w64-mingw32)
  CPU: Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz
  WORD_SIZE: 64
  LIBM: libopenlibm
  LLVM: libLLVM-6.0.0 (ORCJIT, nehalem)
Environment:
  JULIA_EDITOR = "C:\Users\binha\AppData\Local\atom\app-1.34.0\atom.exe" -a
  JULIA_NUM_THREADS = 4

julia> Pkg.installed()
Dict{String,Union{Nothing, VersionNumber}} with 25 entries:
"Statistics"          => nothing
"GR"                  => v"0.37.0"
"Distributions"       => v"0.16.4"
"Random"              => nothing
"Atom"                => v"0.7.14"
"UUIDs"               => nothing
"FastGaussQuadrature" => v"0.3.2"
"JuMP"                => v"0.18.5"
"Juno"                => v"0.5.4"
"LinearAlgebra"       => nothing
"Ipopt"               => v"0.5.1"
"NLopt"               => v"0.5.1"
"PyCall"              => v"1.18.5"
"LaTeXStrings"        => v"1.0.3"
"SymPy"               => v"0.8.3"
"StatsBase"           => v"0.27.0"
"Plots"               => v"0.22.5"
"PyPlot"              => v"2.7.0"
"ProgressMeter"       => v"0.9.0"
"QuadGK"              => v"2.0.3"
"NLsolve"             => v"3.0.1"
"SpecialFunctions"    => v"0.7.2"
"ECOS"                => v"0.9.4"
"PoissonRandom"       => v"0.4.0"
"PlotlyJS"            => v"0.12.2"

julia> using JuMP
julia> using NLopt
julia> using SpecialFunctions

julia> erf(1)
0.8427007929497149

julia> m=Model(solver=NLoptSolver(algorithm=:LD_MMA))
Feasibility problem with:
 * 0 linear constraints
 * 0 variables
Solver is NLopt

julia> @variable(m,x,start=0.0)
x

julia> @NLobjective(m,Min,erf(x))
JuMP.NonlinearExprData(ReverseDiffSparse.NodeData[NodeData(CALLUNIVAR, 53, -1), NodeData(VARIABLE, 1, 1)], Float64[])

julia> solve(m)
ERROR: UndefVarError: erf not defined
Stacktrace:
 [1] #forward_eval#7(::ReverseDiffSparse.UserOperatorRegistry, ::Function, ::Array{Float64,1}, ::Array{Float64,1}, ::Array{ReverseDiffSparse.NodeData,1}, ::SparseArrays.SparseMatrixCSC{Bool,Int64}, ::Array{Float64,1}, ::Array{Float64,1}, ::Array{Float64,1}, ::Array{Float64,1}, ::Array{Float64,1}, ::Array{Float64,1}) at C:\Users\binha\.julia\packages\ReverseDiffSparse\gvK2V\src\forward.jl:380
 [2] #forward_eval at .\none:0 [inlined]
 [3] forward_eval_all(::JuMP.NLPEvaluator, ::Array{Float64,1}) at C:\Users\binha\.julia\packages\JuMP\PbnIJ\src\nlp.jl:445
 [4] eval_grad_f(::JuMP.NLPEvaluator, ::Array{Float64,1}, ::Array{Float64,1}) at C:\Users\binha\.julia\packages\JuMP\PbnIJ\src\nlp.jl:496
 [5] initialize(::JuMP.NLPEvaluator, ::Array{Symbol,1}) at C:\Users\binha\.julia\packages\JuMP\PbnIJ\src\nlp.jl:403
 [6] loadproblem!(::NLopt.NLoptMathProgModel, ::Int64, ::Int64, ::Array{Float64,1}, ::Array{Float64,1}, ::Array{Float64,1}, ::Array{Float64,1}, ::Symbol, ::JuMP.NLPEvaluator) at C:\Users\binha\.julia\packages\NLopt\eqN9a\src\NLoptSolverInterface.jl:117
 [7] _buildInternalModel_nlp(::Model, ::JuMP.ProblemTraits) at C:\Users\binha\.julia\packages\JuMP\PbnIJ\src\nlp.jl:1244
 [8] #build#123(::Bool, ::Bool, ::JuMP.ProblemTraits, ::Function, ::Model) at C:\Users\binha\.julia\packages\JuMP\PbnIJ\src\solvers.jl:304
 [9] #build at .\none:0 [inlined]
 [10] #solve#120(::Bool, ::Bool, ::Bool, ::Base.Iterators.Pairs{Union{},Union{},Tuple{},NamedTuple{(),Tuple{}}}, ::Function, ::Model) at C:\Users\binha\.julia\packages\JuMP\PbnIJ\src\solvers.jl:168
 [11] solve(::Model) at C:\Users\binha\.julia\packages\JuMP\PbnIJ\src\solvers.jl:150
 [12] top-level scope at none:0

Is there any way to call erf() here with the solver?

A: Registering a custom function should help here:
julia> using JuMP, NLopt, SpecialFunctions

julia> f(x) = erf(x)
f (generic function with 1 method)

julia> m=Model(solver=NLoptSolver(algorithm=:LD_MMA))
Feasibility problem with:
 * 0 linear constraints
 * 0 variables
Solver is NLopt

julia> JuMP.register(m, :f, 1, f, autodiff=true)

julia> @variable(m,x,start=0.0)
x

julia> @NLobjective(m,Min,f(x))
JuMP.NonlinearExprData(ReverseDiffSparse.NodeData[NodeData(CALLUNIVAR, 73, -1), NodeData(VARIABLE, 1, 1)], Float64[])

julia> solve(m)
:Optimal

julia> getvalue(x)
-4.107514124511155


text:
Q: Custom listview item xml disabling onitemclicklistener i am using below xml for my ListView item layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:minHeight="?android:attr/listPreferredItemHeight"
android:padding="16dp">

<ImageView
    android:id="@+id/contact_item_icon"
    android:layout_width="50dp"
    android:layout_height="50dp"/>

<LinearLayout
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:orientation="vertical"
    android:paddingLeft="16dp">

    <TextView
        android:id="@+id/contact_item_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Feel The Light" />

    <TextView
        android:id="@+id/contact_item_number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Home" />

</LinearLayout>

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_user_audio_call_dark"
            android:id="@+id/btn_audio_call"/>

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_user_video_call_dark"
            android:id="@+id/btn_video_call"/>

    </LinearLayout>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:text="Invite"
        android:background="@drawable/selector_button_green_oval"
        android:textColor="@color/white"
        android:id="@+id/btn_invite"/>

</RelativeLayout>

</LinearLayout>

i know in this xml some views are overlapping each other but in my custom array adapter i make visibility to gone for some of them based on certain condition, but what this xml do is to disable my ListView onItemClickListener but if i exclude this from xml then onItemClickListener works fine but i want to make onItemClickListener work without removing xml
<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_user_audio_call_dark"
            android:id="@+id/btn_audio_call"/>

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_user_video_call_dark"
            android:id="@+id/btn_video_call"/>

    </LinearLayout>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:text="Invite"
        android:background="@drawable/selector_button_green_oval"
        android:textColor="@color/white"
        android:id="@+id/btn_invite"/>

</RelativeLayout>

A: In your adapter getView(), set onClickListener to each button.
button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             // Do something
        }
}

If you want to handle click event for entire list item then you need to set onClickListener to root LinearLayout of your listViewItem XML:
ListViewItem XML: Give an id to LinearLayout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:minHeight="?android:attr/listPreferredItemHeight"
android:padding="16dp"
android:id="@+id/container">

<ImageView
    android:id="@+id/contact_item_icon"
    android:layout_width="50dp"
    android:layout_height="50dp"/>

.................
...................

Adapter: Set OnClickListener to LinearLayout
@Override
public View getView(int position, View convertView, ViewGroup parent) {

    .............
    .................
    LinearLayout container = (LinearLayout) convertView.findViewById(R.id.container);

    container.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             // Do something
        }
    }
    .................
    ...................
}

Hope this will help!


text:
Q: Join with object from a collection array result I have 2 collections:
Users: uid, displayName.
Activities: documents that the user can create. It also contains userUid with their references to the Users collection
I get the activities like that:
this.activities = this.afs.collection<Activity>('activities')
 .snapshotChanges()
 .pipe(
   map((actions) => {
    return actions.map((a) => {
      const data = a.payload.doc.data();
      data.uid = a.payload.doc.id;
      return data;
    })
  }));

So, my question is how is the best way to join and get also the user data?
I tried like that:
actReference.snapshotChanges().pipe(
  map((actions) => {
    return actions.map((a) => {
      const actData = a.payload.doc.data();
      actData.uid = a.payload.doc.id;

      return this.userService.getUserDocById(actData.userUid).snapshotChanges()
        .pipe(
          map((userActions) => {
            const userData = userActions.payload.data();
            return { user: { uid: userData.uid, displayName: userData.displayName }, ...actData };
          }))
    })
  }));

But it returns me an
 Observable<Observable<Activity>[]>>

A: You need to apply rxjs pipe operator chaining.
actReference.snapshotChanges().pipe(
  map((actions) => {
    actions.map((a) => ({
      let actData = a.payload.doc.data();
      actData.uid = a.payload.doc.id;
      actData.displayName = a.payload.doc.name;
      return actData;
    });
  }),
  map((userData) => {
      return this.userService.getUserDocById(actData.userUid).snapshotChanges()
        .pipe(
          map((userActions) => {
            const userData = userActions.payload.data();
            return { user: { uid: userData.uid, displayName: userData.displayName }, ...actData };
          }))
    })
  }));

A: @suresh-kumar-ariya answer was not my final result but helped me a lot, I end up with this code:
 return actReference.snapshotChanges().pipe(
  map((actions) => {
    return actions.map((a) => {
      const actData = a.payload.doc.data();
      actData.uid = a.payload.doc.id;

      return this.userService.getUserDocById(actData.userUid).snapshotChanges()
        .pipe(
          map((userActions) => {
            const userData = userActions.payload.data();
            return { user: { uid: userData.uid, displayName: userData.displayName }, ...actData } as Activity;
          }))
    })
  }),
  mergeMap(obs => combineLatest(obs))
);


text:
Q: how to find active class data-id

Special

Deal

TDeal

my jquery code is
function addcls() {
        var current = $('.deal-menu li.active').removeClass('active'),
            next = current.next().length ? current.next() : current.siblings().filter(':first');
        next.addClass('active');
        var val = $(this).data("id");
        alert(val);
    };

 setInterval(function () {
        addcls();
       }, 3000);

i need to find the active class data-id value , its showing undefined value

A: use:
$('li.active').data('id')

A: var val = $('li.active').attr('data-id');
alert(val);

http://jsfiddle.net/MHdN9/

A: In your case you can also use:
var val = next.attr('data-id');

Because you assign the class active to the object 'next'

A: You already have your target inside a variable, so use it :
var val = next.addClass('active').data("id");

$(this) in your case is window since you're in a function called by a timeout.

A: try
alert($(".active").attr(" data-id"));


text:
Q: OpenCV similarity between two images using Euclidean distance Can we use the Euclidean distance to determine the similarity between two images

*

*Detect Keypoint image1, image2 using SUFT

*Compute Descriptor image1, image2 using SUFT

*double dif = norm(des1,des2,L2_norm)----> if dif is small -> can we tell that two images similar?

If yes, so what is the threshold to lead to these two images are similar.
And another question is when I compute descriptor for those images.
I see that the size of them is not equal. Ex: des1 is 64x96, des2 is 64x85
So the norm function throw an exception.
So is there any way for us to normalize the descriptor to fixed size in order to using Euclidean distance or not?
And I use OpenCV Java API to do these above stuffs currently.


text:
Q: How to normalize interaction terms? I'm training a classifier for a supervised classification problem. Some of my features interact, how should I normalize these interaction terms?
For example, if x1 and x2 interact, the interaction term is x1*x2. Should the values of x1*x2 be computed before x1 and x2 are normalized, and then normalized. Or should x1*x2 be computed from normalized values of x1 and x2?


text:
Q: cocos2d loaded size and total size during scene transition I'm doing a progress bar to show the current progress during transition time from scene 1 -> scene 2
simply my progress bar value will base on current loaded resource size and total resource size needed to load scene 2
But I don't know how to get these 2 values. Please help me. Thanks a lot.

A: What is a "resource size" to you?
If you consider an image file, then that image file has a size on disk which may or may not be compressed, with compression depending on file content. The image file gets loaded into a texture, which has an in-memory size. That too may be compressed (PVR) or not. Finally, the size of an image on disk, the compression, and the memory representation (bit depth etc) all factor into how long it takes to load that image.
If you extend that to other resource types like sound files, property lists, databases it gets extremely difficult to control a progress bar based on some arbitrary, hard to define "resource size".
Long story short: you can get a file's size. You can base your loading bar on that but it won't reflect the actual loading time at all.
You can also estimate or calculate the amount of memory a resource takes up, ie a 2048x2048x32bit texture is 16 MB - unless it is compressed even in memory (PVR textures). But this requires intimate knowledge of each asset's data structure. Plus, for example if you only load four of these textures your progress bar will jump to 25%, 50%, 75% and 100% after each texture - you have no way of knowing  "how far into loading the texture" the device is to make the progressbar progress smoothly in such cases.
Long story short:
Most progress bars simply consider how many resources are being loaded. This you know from the code you put into the scene, ie. which images, audio files, etc. you load. Unless you load your entire scene from a data file, for example if you use some kind of design tool, you won't know the number of resources at runtime until after they're loaded.
An alternative is to update your progress bar after each block of resources, so that you can divide the progressbar progress into few, concrete steps. This is particularly helpful if few resources take most of the time to load, and they are atomic chunks (ie 2048x2048 texture atlas) which take several fractions of a second to load without any chance of updating the progress bar.
Finally, unless you actually see a loading time of 3+ seconds a progressbar makes little sense. In that case you may better spend your time on optimizing loading times. For example a lot can be done by choosing the ideal texture format, by using texture atlases, by avoiding redundant asset loads, by deferring loading of certain assets or loading them in a separate thread.


text:
Q: Is there such a material that only emits, or "sends out" the same color light that was "taken in" (absorbed)? For example, glow-in-the-dark materials (photoluminescent) only emit a green hue regardless of the color of the light shone on the material.
Is there such a material that emits the color of the light received, or the combined colors? For example, if one were to shine a red light on the material, it would emit red, same with yellow, etc.
A mirror only reflects light and doesn't absorb or emit any light.

A: In some versions of cavity ring down spectroscopy a diffusely reflecting integrating sphere is used. The reflectivity of its "fumed silica" surface is about .999 over a broad spectral range. The material disperses the light very effectively. The light hits the surface and rattles around in the surface's microscopic nooks and crannies. This is effectively absorption and remission at the same wavelength.
https://www.osapublishing.org/ao/abstract.cfm?uri=ao-54-2-334

A: All materials can only emit light of wavelengths that they can also absorb. The same optical degrees of freedom are responsible for absorption and emission.


text:
Q: Incorrect bitmaps; how is this possible I am trying to analyze license plates with C++ code. The point is NOT how to get there fast, because I want to go to the process of creating this C++ code myself and learning how to.
Problem:
The bytes in the bitmap file don't add up! The bitmap file:

http://ictmdeklerk.nl/cor.bmp
Why they dont add up:
I am using 24 bit bitmap images (*.BMP files). I know the bitmap is constructed with the BMPFILEHEADER, and BMPINFOHEADER, which togehter consume 54 bytes.
Now, the image is 1350 pixels wide and 740 pixels high, which results in 999000 pixels.
Because the file is 24 bit, there are 3 bytes per pixel. 999000 * 3 = 2997000 bytes neccessary for the image. But the image size (biSizeImage) in the BMPINFOHEADER says the image is 2998480 bytes! The file size is 2.998.534 bytes - 54 header bytes = 2.998.480  indeed. So the header is still 54 bytes. No extra meta data there. When I divide 2.998.480 / 3 bytes per pixel I get 999493,33 pixels! It is not even a round number!
It is driving me insane. How does windows ever know how to show this image without shifting pixels or colors or anything?
Can anyone explain me where these extra pixels/bytes come from? And how to deal with them?
Thanks in advance!

A: BMP files pad each row to 4-byte boundaries.
Your image is
(1350px wide) x (3 bytes per pixel) = 4050 bytes per row.
4050 is not divisible by 4, but 4052 is so 2 bytes for every row (2 * 740 = 1480 bytes) are added as padding to your image.
The file size is therefore 2997000 image bytes + 54 bytes header + 1480 bytes row padding =  2998534 bytes, which is the actual file size.


text:
Q: How to override parent :nth-of-type in child element? I am using a stylesheet that looks a bit like this:
.base-slider {
    width: 100%;

    .ui-state-default {
        border: none;
    }

    .ui-state-default:nth-of-type(1) {
        background: url('left-end-arrow.png');
    }

    .ui-state-default:nth-of-type(2) {
        background: url('right-end-arrow.png');
    }

    /* loads of other style stuff */
}

.secondary-slider {
    .ui-state-default {
        background: url('single-point-arrow.png');
    }
}

Then in my html I have something like:

   X

The problem I have is that I am seeing the 'left-end-arrow.png' on my secondary-slider element rather than the 'single-point-arrow.png' which is what I was expecting
I am guessing that is because nth-of-type(1) makes the base-slider selector more specific than the child one. Is this correct? And if so, is there any CSS way to say "ignore any previously added pseudo-classes on this element"?

A: You could use :nth-of-type(n) to override the previous pseudo classe styles like this :
DEMO
 .secondary-slider .ui-state-default:nth-of-type(n) {
     background: url('single-point-arrow.png');
 }

OR
You can make the second CSS style more specific as you have two calsses on your container, you can use both like this :
DEMO
 .base-slider.secondary-slider .ui-state-default {
     background: url('single-point-arrow.png');
 }


text:
Q: what does the er here stands for? try:
    os.execvp('sqlite3', args)
except OSError, er:
    if er.errno == 2: #file not found
        raise OSError, _("sqlite3 executable not found. Is it installed?")
    else:
        raise
except:
    raise

In the above code, the except statement catches the OSError but what does the er variable stand for?
EDIT: this one only excepts OSError; is there a way to except any error and get the exception object for it?

A: As others have said, er is the instantiated form of the exception, OSError.
If it's helpful, here's an alternative, somewhat more explicit syntax, using the as keyword:
try:
    os.execvp('sqlite3', args)
except OSError as er:
    if er.errno == 2: #file not found
        raise OSError(_("sqlite3 executable not found. Is it installed?"))
    else:
        raise
except:
        raise

Which, to me, says that er will be an OSError.
As as er syntax was added in Python 2.6, by the way.

A: er is the actual exception object that got caught by the except clause.

A: er is the exception object itself.

A: looks like er is an exception object (of type OSError also looks like it holds the errors.
ER probably stands for error.


text:
Q: Is Opening Java FileOutputStream efficient? I'm writing a singleton logger for my program right now, and I was wondering whether it would be better to open and close it everytime I log something, or to open the stream at creation of the singleton and close it at the termination of the program? And if I were to do that, how would I close it at termination?

A: Do not close it, just flush, this is what Log4j FileAppender does by default.

A: The main advantage of opening the file once is performance. You save yourself the penalty of calling an open each time, and seek to the end of the file for appending; this get worse if the file is big (and some logs tend to be).
The cons are:

*

*You might not be able to read the last log line inmmediately, if there is some buffering in the writer (delayed writes). Howeever, this can be fixed by flushing after each write (you might lose some performance, but this is not usually relevant).

*You cannot simultaneously write to the same log from different processes. But you probably don't need this - and if you need it, the open-and-close solution still needs to deal with concurrency.

*Some external log processing (typically, log rotation with renaming) becomes problematic. To allow for this, you might need to implement some signalling that closes and reopens the file.
Typically, the advantage outweights the cons, so the general rule is to keep the log file open. But that depends on the scenario.
(As other answers point out, normally you'd prefer to use some standard logging library instead of implementing this on your own. But it's instructive to give it a try, or at least to think of all the issues involved).

A: You should open once (and close once). If you do nothing, Java will close it for you. You may prefer to explicitly override Object.finalize().


text:
Q: How can I compare an ntp server's time to my server's time? I have ntpd running on a box. I want to see how the time on the box compares to the time retrieved from ntp.ubuntu.com. Is there an easy way to do this?

A: You can use ntpdate to query a time server
ntpdate -q ntp.ubuntu.com

A: ntpq -p ntp.ubuntu.com
From man ntpq:
...
-p     Print  a list of the peers known to the server as well as a summary of their state. This is equivalent to the peers interactive command.
...

Edit:  The host is timing out right now.  ntpq -p pool.ntp.org will return a valid result.

A: Actually, the command ntpq -c "rv 0 clock" ntp.ubuntu.com will return the time of the server in standard format : this is the result from ca.pool.ntp.org :
clock=d1b5aa9c.b8f9697a  Wed, Jun 29 2011  9:43:56.722

A: There are a few different options for querying an ntp server now that ntpdate is deprecated. Which is preferred is often simply a matter of which is already installed (or easy to install) on your OS:
sntp
sntp is a tool from the ntp project, and is their recommended tool for querying remote servers:
$ sntp -K/dev/null ntp.ubuntu.com
2021-10-12 16:01:48.425034 (+0700) -0.175372 +/- 0.128998 secs

The -K/dev/null is optional, and disables persisting information about the requests to a file. Normal users typically won't have access to this file, so without that option it will print some errors but will otherwise work.
chronyd
chronyd is an alternative ntp implementation and the default time server in recent RHEL and Ubuntu distributions.
$ chronyd -Q "server ntp.ubunutu.com iburst"
2021-10-27T21:55:49Z chronyd version 3.5 starting (+CMDMON +NTP +REFCLOCK +RTC +PRIVDROP +SCFILTER +SIGND +ASYNCDNS +SECHASH +IPV6 +DEBUG)
2021-10-27T21:55:49Z Disabled control of system clock
2021-10-27T21:55:53Z System clock wrong by -0.233053 seconds (ignored)
2021-10-27T21:55:53Z chronyd exiting

The -Q tells it to query the server and print results without setting the time (capital is important - lowercase will set the time!). By default it will query the servers configured in it's config file, but you can also give a config line as done above. server is used to specify a single NTP server to query, but pool and refclock could also be used. iburst configures it get an initial result more quickly.


text:
Q: Derivation of equations of motion in Nordstrom's theory of scalar gravity? Nordstrom's theory of a particle moving in the presence of a scalar field $\varphi (x)$ is given by
$$
S = -m\int e^{\varphi (x)}\sqrt{\eta_{\alpha \beta}\frac{dx^{\alpha}}{d \lambda}\frac{dx^{\beta}}{d \lambda}}d\lambda ,
$$
where $\lambda$ is the parametrization of the worldline of the particle, ignoring the free field part $\int \eta_{\alpha \beta}\partial^{\alpha}\varphi \partial^{\beta} \varphi d^{4}x$.
How does one derive the equations of motion in terms of the parameter
$$d\tau = \sqrt{\eta_{\alpha \beta}\frac{dx^{\alpha}}{d \lambda}\frac{dx^{\beta}}{d \lambda}} d\lambda.
$$
$u^{\alpha} = \frac{dx^{\alpha}}{d\tau} \Rightarrow u_{\alpha}u_{\beta}\eta^{\alpha \beta} = 1$?
My attempt:
$$
\delta S = 0 \Rightarrow \int \left( \frac{\partial (e^{\varphi } \sqrt{...})}{\partial x^{\alpha}}\delta x^{\alpha} +\frac{\partial (e^{\varphi } \sqrt{...})}{\partial \left( \frac{d x^{\alpha}}{d \lambda } \right)}\frac{d}{d\lambda} \delta x^{\alpha} \right)d\lambda = |d\tau = \sqrt{...}d\lambda | =
$$
$$
= \int \left(\sqrt{...}e^{\varphi}\partial_{\alpha}\varphi - \frac{d}{d \lambda} \left(\frac{d x_{\alpha}}{d\tau}e^{\varphi}\right)  \right)\delta x^{\alpha}d \lambda  =
$$
$$
=\int \left( \partial_{\alpha}\varphi - \frac{d^{2}x_{\alpha}}{d \tau^{2}} - \frac{dx_{\alpha}}{d\tau} \frac{d \varphi }{d\tau }\right) \delta x^{\alpha} e^{\varphi} \sqrt{...}d\lambda =
$$
$$
=\int \left( \partial_{\alpha}\varphi - \frac{d u_{\alpha}}{d \tau} - u_{\alpha} u_{\beta} \partial^{\beta} \varphi \right)\delta x^{\alpha} e^{\varphi} \sqrt{...}d\lambda \Rightarrow
$$
$$
\partial_{\alpha}\varphi - \frac{d u_{\alpha}}{d \tau} - u_{\alpha} u_{\beta} \partial^{\beta} \varphi = 0 \Rightarrow \partial_{\alpha} \varphi = e^{-\varphi}\frac{d }{d \tau}\left( e^{\varphi } u_{\alpha}\right).
$$
Unfortunately, this equation doesn't look like the equation from Wikipedia,
$$
\frac{d (\varphi u_{\alpha})}{d \tau} = -\partial_{\alpha } \varphi.
$$
I can explain the part of differences by renaming the function, $e^{\varphi } \to \varphi $, in the expression for action (then my equation reduces to the form $ \partial_{\alpha} \varphi = \frac{d }{d \tau}\left( \varphi  u_{\alpha}\right)$), but I can't explain why my equation has the wrong sign.


text:
Q: show/hide categorized items with css So, I want to make a gallery on a website that does not allow Javascript, so I wasn't sure how to approach this.  Say I have four categories: Sketches, Lineart, Cell Shaded and Painted.  I want these four to be toggle buttons.
Then, I would code the gallery so that all my works initially showed, and once one of the toggles was clicked, everything other than the applicable works would show.
Sketch | Sketch | Cell | Lineart
Lineart | Sketch | Cell | Sketch
Click sketch, and then it would just have the four sketches showing side by side.  It would also be neat to be able to apply two different categories to work, in case I change the categories, so some assistance on how I could apply two things ( like, putting male and female as categories, and then tagging a picture with two+ people as both ) would be appreciated as well.
This was a good example of what I was going for, but it uses JS.

A: Here you go @Tasuya Suou. Hopefully this helps you. I used the general ~ selector. You can read more about it here. https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_selectors.

p {
  display: none;
}

input[value="fruit"]:checked~p.fruit,
input[value="veg"]:checked~p.veg,
input[value="nuts"]:checked~p.nuts,
input[value="drink"]:checked~p.drink {
  display: block;
}

input:checked+label {
  color: blue;
}

  <title>Parcel Sandbox</title>
  <meta charset="UTF-8" />
  <link rel="stylesheet" type="style/css" href="./index.css" />

  <input type="radio" id="fruit" name="product" value="fruit" />
  Fruit
  <input type="radio" id="veg" name="product" value="veg" checked />
  Veg
  <input type="radio" id="nuts" name="product" value="nuts" />
  Nuts
  <input type="radio" id="drink" name="product" value="drink" />
  Drink

Product 1

Product 2

Product 3

Product 4

https://codesandbox.io/s/48y9o68oz7


text:
Q: Gem methods not available inside Grape Api I'm currently building my first API with Grape and the Rails 5 api mode and it's going fairly well until now. I decided to install the Impressionist gem to be able to log the view counts of a certain model (future "popular" page) but I'm running into an issue where I feel I have setup the gem correctly but the impressionist method used to actually log the info in the database is undefined.
In my model, the gem is initialized like this is_impressionable :counter_cache => true
I then have in app/api/my_app/my_model.rb
module MyApp
  class MyModel < Grape::API
    # GET /api/v1/model/:slug
    desc "Returns a model record"
    params do
      requires :slug, type: String, desc: "Model slug", allow_blank: false
    end
    route_param :slug do
      get do
        my_model = MyModel.friendly.find(params[:slug])
        impressionist(my_model)
        present my_model, with: MyModelPresenter
      end
    end
  end
end

to log the activity but the impressionist method is undefined. I tried ImpressionistController::ClassMethods.impressionist as well without success. I have other gems like friendly_id and will_paginate which work perfectly out of the box with this setup. Do I have to require something specific ?

A: It seems that impressionist does not support Grape:
You can use it manually:
  imp = Impression.new
  imp.impressionable_type = object.class.to_s
  imp.impressionable_id = object.id
  imp.user_id = current_user.nil? ? 0 : current_user.id
  imp.controller_name = "topics"
  imp.action_name = "show"
  imp.request_hash = Digest::SHA2.hexdigest(Time.now.to_f.to_s+rand(10000).to_s)
  imp.ip_address = env['REMOTE_ADDR']
  imp.session_hash = request.session_options[:id]
  imp.referrer = request.referer
  imp.save

https://github.com/charlotte-ruby/impressionist/issues/172#issuecomment-62844576


text:
Q: Customer Login and Registration broken i have a problem with magento customerlogin and registration on frontend. If someone wants to login and enter his logininformation and submit this, magento redirects to index (or sometimes it remains on the loginform) and nothing happens. It's not possible to see the Customeraccount. Same with registration.
Back-End Login works
Anyone a solution for that?
Thanks.

A: Before looking further, make sure you clear browser cookies, delete sessions under /var/sessions, and clear the magento cache.
You can also try increasing the cookie timeout in ADMIN >> CONFIG >> WEB >> SESSION COOKIE MANAGEMENT.
If this is on a production site, be sure you want to remove sessions as there could be someone about to checkout.


text:
Q: Sum of values with in a time range is not working I have a dataset that returns some columns. I am writting a query that will show sum of some rows of two columns TotalQty and TotalValue within a datetime range for each row of another column buyer. That means Total number of rows will be the number of different buyer. But somehow my query is not summing the rows within the datetime range. It is showing all the values of each date. How can I solve this?
I tried this-
 Create PROCEDURE [dbo].[spRPTMonthWiseProductionSummaryFORATL]
@MonthName  Varchar(50)
-- Exec spRPTMonthWiseProductionSummaryFORATL 'Sep,2014'
AS BEGIN
Declare @FromDate datetime,
        @ToDate datetime,
        @FromDate2 datetime,
        @FromDate3 datetime,
        @FromDate4 datetime,
        @FromDate5 datetime,
        @FromDate6 datetime
Select @FromDate = Convert(Datetime,@MonthName),
       @ToDate = DateAdd(d,-1,DateAdd(m,1,Convert(Datetime,@MonthName)))
Select @FromDate2 = DATEADD(M,1,@FromDate)
Select @FromDate3 = DATEADD(M,1,@FromDate2)
Select @FromDate4 = DATEADD(M,1,@FromDate3)
Select @FromDate5 = DATEADD(M,1,@FromDate4)
Select @FromDate6 = DATEADD(M,1,@FromDate5)

Select B.Buyer,
**CASE WHEN UseDate>=@FromDate And UseDate< @FromDate2
     THEN SUM(TotalQty) END AS m1Qty,
CASE WHEN UseDate>=@FromDate And UseDate< @FromDate2
     THEN SUM(TotalValue) END AS m1Value,
CASE WHEN UseDate>=@FromDate2 And UseDate< @FromDate3
     THEN SUM(TotalQty) END AS m2Qty,
CASE WHEN UseDate>=@FromDate2 And UseDate< @FromDate3
     THEN SUM(TotalValue) END AS m2Value,
CASE WHEN UseDate>=@FromDate3 And UseDate< @FromDate4
     THEN SUM(TotalQty) END AS m3Qty,
CASE WHEN UseDate>=@FromDate3 And UseDate< @FromDate4
     THEN SUM(TotalValue) END AS m3Value,
CASE WHEN UseDate>=@FromDate4 And UseDate< @FromDate5
     THEN SUM(TotalQty) END AS m4Qty,
CASE WHEN UseDate>=@FromDate4 And UseDate< @FromDate5
     THEN SUM(TotalValue) END AS m4Value,
CASE WHEN UseDate>=@FromDate5 And UseDate< @FromDate6
     THEN SUM(TotalQty) END AS m5Qty,
CASE WHEN UseDate>=@FromDate5 And UseDate< @FromDate6
     THEN SUM(TotalValue) END AS m5Value**

from
(
Select Buyer,
       sum(Unit1Qty)Unit1_Qty ,
       sum(Unit2Qty)Unit2_Qty,
       sum(Unit3Qty)Unit3_Qty,
       sum(Unit1Qty*FOB) as Unit1_Value,
       sum(Unit2Qty*FOB) as Unit2_Value,
       sum(Unit3Qty*FOB) as Unit3_Value,
       sum(Unit1Qty*CM) as Unit1_CM,
       sum(Unit2Qty*CM) as Unit2_CM,
       sum(Unit3Qty*CM) as Unit3_CM,
       sum(Unit1Qty) +sum(Unit2Qty)+ sum(Unit3Qty) as TotalQty,
      sum(Unit1Qty*FOB)+sum(Unit2Qty*FOB) +sum(Unit3Qty*FOB) as TotalValue,
      sum(Unit1Qty*CM) +sum(Unit2Qty*CM) +sum(Unit3Qty*CM) as TotalCM,
      A.UseDate
from
(
Select C.Name as Buyer,
Unit1Qty = Case When PPC.factoryname ='Unit-1'
                then OM.OrderQty else 0 end,
Unit2Qty = Case When PPC.factoryname ='Unit-2'
                then OM.OrderQty else 0 end,
Unit3Qty = Case When PPC.factoryname ='Unit-3'
                then OM.OrderQty else 0 end,
FOB =
(Select Rate =
        Case When Sum(ISNULL(OrderQty,0)) <> 0
        Then Sum(ISNULL(rate,0)*ISNULL(OrderQty,0))/Sum(ISNULL(OrderQty,0))
        Else 0
   End From ExportOrder
 Where OrderRefID = OM.OrderRefID) ,
--FR.Rate  as FOB,
isnull(CM,0) as CM,LA.UseDate
from AmanProduction.dbo.OrderMaster OM
INNER JOIN AmanProduction.dbo.LineAllocation LA
ON LA.OrderRef=OM.OrderRefID
INNER JOIN FileRef FR
ON FR.FileRefID= OM.FileRefID
INNER JOIN SystemManager.dbo.ProductionProcessCostCenter PPC
ON PPC.CostCenter = LA.Line
INNER JOIN SystemManager.dbo.ProductionProcess PP
ON PP.ProcessID = PPC.ProcessId
INNER JOIN SystemManager.dbo.Contacts C
ON C.Code = Om.BuyerCode
LEFT JOIN(Select OC.OrderRefID,Rate as CM
from AmanProduction.dbo.OrderMasterCostBreakdown OC
INNER JOIN BOMItemGroups BG
ON BG.BOMItemGroupId = OC.BOMItemGroupId
Where BOMItemGroupDesc ='CM') CM
ON OM.OrderRefID=CM.OrderRefID
Where PP.ProcessName ='Sewing'
and LA.UseDate >=  @FromDate  ) A
Where Unit1Qty>0 or Unit2Qty>0  or Unit3Qty>0 Group by UseDate,Buyer
)B
Group by year(UseDate),month(UseDate),UseDate,Buyer

End

I am getting data like this

There are so many values for m1qty,m1value, and m2qty,m2value for buyer s.OLIVER. But there should be 1 value of m1qty,m1value and 1 value of m2qty,m2value of "s.Oliver" that is the summation of the date range i specified in case conditions.

A: Your procedure is rather large and it would take some time to understand the complete logic. However, there is one thing that seems likely to be the issue and it is your CASE expressions. They probably should be inside the aggregate function. What I mean is, instead of writing them like this:
CASE WHEN UseDate>=@FromDate And UseDate< @FromDate2 THEN SUM(TotalQty) END

you should (probably) write them like this:
SUM(CASE WHEN UseDate>=@FromDate And UseDate< @FromDate2 THEN TotalQty END)

and then you should also remove UseDate from the GROUP BY (but probably keep both year(UseDate) and month(UseDate) – again, hard to say without digging deep into the logic).

A: If I grossly simplify your query, I see something strange in your group by.
 SELECT B.Buyer
   FROM
  (
   SELECT Buyer
     FROM
    (
     SELECT C.Name as Buyer
     FROM ....
    )
  ) B
GROUP BY year(UseDate),month(UseDate),UseDate,Buyer

If you want one line per Buyer, why do you not group on Buyer as the highest level?
You would get one line per Buyer if you change your group by to
GROUP BY Buyer

Grouping ion the dates as well will give you several lines per buyer, namely one line per grouped date. Your query seems to want to spread results for different dates over different columns, so no need to group on those.
Actually, you might want to group by Buyer earlier on, in one of the inner queries.


text:
Q: MySQL- How to implement event scheduler everyday + start from 8am to 10 pm+ every 15 min I would like to insert the statistic into table 1 every 15 min start from 8am to 10pm everyday
How to use MySQL event scheduler to do it?
delimiter ||
    CREATE EVENT STOCK_UPDATER
        ON SCHEDULE EVERY 15 MINUTE
            DO BEGIN
                [INSERT CODE THAT I HAVE MADE]
    END ||
delimiter ;

======================================
Thz @Saharsh Shah, I finally solve it, here are my final result:
create table ABC (value int(10));

DELIMITER $$

CREATE EVENT ABCevents
   ON SCHEDULE EVERY 15 SECOND
        DO BEGIN
                IF (HOUR(SYSDATE()) BETWEEN 14 AND 15) THEN
                    insert ABC value(123);
                END IF;
        END $$
DELIMITER ;

A: Try this:
DELIMITER $$

CREATE EVENT STOCK_UPDATER
   ON SCHEDULE EVERY 15 MINUTE
      STARTS '2013-11-27 12:00:00' ON COMPLETION NOT PRESERVE ENABLE
         DO BEGIN
    IF (HOUR(SYSDATE()) BETWEEN 8 AND 22) THEN
    BEGIN
         INSERT ABC VALUES (123);
    END IF;
END$$

DELIMITER ;


text:
Q: Slack API , Slash commands not updating I am building a custom Slack app. I am noticing a behavior that seems odd.
If a user installs the App they have available to them the slash commands bundled with the app. If I change or add slash commands to the app the user does not see the modified or changed slash commands unless they 'uninstall' and 'reinstall' the app.
How can I update my app without requiring users to reinstall?
Thanks!

A: According to Slack support, a user will always need to reauthorize new functionality so, the will need to reinstall.


text:
Q: Wordpress Custom Post Type (CPT) Archive Grid on Homepage with Genesis Framework I am trying to get a custom-post-type grid to display on my homepage. I am using the genesis framework within WordPress. I have the CPT archive grid working correctly on the archive page but its not displaying any of the posts when I use the code on my home page.
<?php
/*** This file handles the output on the homepage.*/
/***************** Start Project Filter  ********************/
// Force full width content (optional)
add_filter( 'genesis_pre_get_option_site_layout', '__genesis_return_full_width_content' );
//remove standard loop (optional)
remove_action( 'genesis_loop', 'genesis_do_loop' );
// Add our custom loop
add_action( 'genesis_loop', 'lp_filterable_portfolio' );
// Enqueue javascript
wp_enqueue_script('isotope', get_stylesheet_directory_uri() . '/js/isotope.pkgd.min.js', array('jquery'), '1.5.25', true);
wp_enqueue_script('isotope_init', get_stylesheet_directory_uri() . '/js/isotopes_init.js', array('isotope'), '', true);

/*** Get Excerpt. */
function the_excerpt_max_charlength($charlength) {
 $excerpt = get_the_excerpt();
 $charlength++;
 if ( mb_strlen( $excerpt ) > $charlength ) {
 $subex = mb_substr( $excerpt, 0, $charlength - 5 );
 $exwords = explode( ' ', $subex );
 $excut = - ( mb_strlen( $exwords[ count( $exwords ) - 1 ] ) );
 if ( $excut < 0 ) {
 echo mb_substr( $subex, 0, $excut );
 } else {
 echo $subex;
 }
 echo '[...]';
 } else {
 echo $excerpt;
 }
}
/**
* Output filterable items. */
function lp_filterable_portfolio( ){

 $args = array(
 'post_per_page' => 9999
 );
 $loop = new WP_Query( $args );
 $terms = get_terms( 'my_taxonomy' );
 $count=0;
 ?>

 <?php if( $terms ) { ?>

<?php _e('All', 'lp'); ?>

 <?php
 foreach( $terms as $term ){
 echo "
slug'>$term->name
";
 }
 ?>

 <?php } ?>
 <?php if( have_posts() ) { ?>

 <?php while( have_posts() ): the_post(); ?>
 <?php $count++; ?>
 <?php $terms = get_the_terms( get_the_ID(), 'my_taxonomy' ); ?>
 <?php if ( has_post_thumbnail($post->ID) ) { ?>
 <article class="portfolio-item col-<?php echo $count; ?> <?php if( $terms ) foreach ( $terms as $term ) { echo $term->slug .' '; }; ?>">
 <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php echo genesis_get_image( array( size => 'lp-portfolio' ) ); ?>

<?php the_title(); ?>

<?php the_excerpt_max_charlength(50);?>

 <?php } ?>
 <?php endwhile; ?>

 <?php } ?>
 <?php wp_reset_postdata(); ?>

<?php
 wp_reset_postdata();
}

genesis();

Any help would be greatly appreciated.
Thanks

A: Answering my own question... MUHAHAHAHAHA
By adding 'post_type' => 'projects' to my $args = arrray and changing while( have_posts() ): the_post(); to while ( $loop->have_posts() ): $loop->the_post(); as refrenced in section "Querying by Post Type" on the WordPress Post Types page I was able to get all the custom post types pulling and filtering on the home page.
Hope this helps anyone else looking to answer the same question.
Full Working Code:
<?php
/**
 * Home
 */
// Force full width content (optional)
add_filter( 'genesis_pre_get_option_site_layout', '__genesis_return_full_width_content' );
//remove standard loop (optional)
remove_action( 'genesis_loop', 'genesis_do_loop' );
// Add our custom loop
add_action( 'genesis_loop', 'lp_filterable_portfolio' );
// Enqueue javascript
wp_enqueue_script( 'isotope', get_stylesheet_directory_uri() . '/js/isotope.pkgd.min.js', array( 'jquery' ), '1.5.25', true );
wp_enqueue_script( 'isotope_init', get_stylesheet_directory_uri() . '/js/isotopes_init.js', array( 'isotope' ), '', true );
/**
 * Get Excerpt.
 *
 * @since 1.0
 *
 */
function the_excerpt_max_charlength( $charlength ) {
    $excerpt = get_the_excerpt();
    $charlength++;
    if ( mb_strlen( $excerpt ) > $charlength ) {
        $subex = mb_substr( $excerpt, 0, $charlength - 5 );
        $exwords = explode( ' ', $subex );
        $excut = -( mb_strlen( $exwords[ count( $exwords ) - 1 ] ) );
        if ( $excut < 0 ) {
            echo mb_substr( $subex, 0, $excut );
        } else {
            echo $subex;
        }
        echo '[...]';
    } else {
        echo $excerpt;
    }
}
/**
 * Output filterable portfolio items.
 *
 * @since 1.0
 *
 */
function lp_filterable_portfolio() {
    $args = array(
        'post_type' => 'your_post_type', //Add your custom post type
        'post_per_page' => 9999
    );
    $loop = new WP_Query( $args );
    $terms = get_terms( 'your_taxonomy' ); // Add your custom taxonomy
    $count = 0;
    ?>

        <?php if( $terms ) { ?>

<?php _e('All', 'lp'); ?>

            <?php
            foreach ( $terms as $term ) {
                echo "
slug'>$term->name
";
            }
            ?>

        <?php } ?>
        <?php if( have_posts() ) { ?>

                <?php while ( $loop->have_posts() ): $loop->the_post(); ?>
                <?php $count++; ?>
                <?php $terms = get_the_terms( get_the_ID(), 'your_taxonomy' ); // Add your custom taxonomy ?>
                <?php if ( has_post_thumbnail($post->ID) ) { ?>
                <article class="portfolio-item col-<?php echo $count; ?> <?php if( $terms ) foreach ( $terms as $term ) { echo $term->slug .' '; }; ?>">
                    <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>">
                        <?php echo genesis_get_image( array( size => 'lp-portfolio' ) ); ?>

                                <?php the_title(); ?>

                                <?php the_excerpt_max_charlength(50);?>

                <?php } ?>
                <?php endwhile; ?>

        <?php } ?>
        <?php wp_reset_postdata(); ?>

    <?php
    wp_reset_postdata();

}
genesis();


text:
Q: Download everything from a YouTube video using youtube-dl I want to download everything (subtitles, cards, tags, annotations, thumbnails, etc. (and obviously the video w/ audio)) from a YouTube video (for example, this one).
I'm using youtube-dl and, with the overwhelming amount of switches to use, I can't seem to find anything to fit my needs. I also want to download the video/audio in the highest quality possible, with no quality loss. Even though it's not YouTube, I did also want to download some of my udemy courses I've bought so I can watch them while I'm on a long road trip.
I have ffmpeg installed, and I heard that you need this for lossless downloads from YouTube, but I'm not sure how to link it with youtube-dl.
This is my first time using youtube-dl, so any help is appreciated.

A: @leetbacoon see comment response at very bottom. (low rep still sry)
Note: I will be using the longer switch names to avoid confusion. Many of the switches used have shorter versions. See Docs: Options.
Note:
 - for visual convenience \ is used to display switches separately; all \ can be omitted; if using \ make sure there is no space character after \.

Synopsis:
A ytdl command to download a single video file of highest available video and audio quality. Saves the video into its own directory (specified by you). Downloads all available metadata, writes each to respective file formats and saves in same directory.
Adds video metadata to video output file.
Substitute with your own:

*

*replace /archive/videos/TED_Archive/ in the switches --download-archive and --output with a directory path of your choice.

*example storage path /archive/videos

*example video link: https://www.youtube.com/watch?v=0bFs6ZiynSU

*example channel directory /TED_Archive

====
youtube-dl \
--limit-rate '0.25M' \
--retries '3' \
--no-overwrites \
--call-home \
--write-info-json \
--write-description \
--write-thumbnail \
--all-subs \
--convert-subs 'srt' \
--write-annotations \
--add-metadata \
--embed-subs \
--download-archive '/archive/videos/TED_Archive/TED_Archive.ytdlarchive' \
--format 'bestvideo+bestaudio/best' \
--merge-output-format 'mkv' \
--output '/archive/videos/TED_Archive/%(upload_date)s_%(id)s/TED_Archive_%(upload_date)s_%(id)s_%(title)s.%(ext)s' \
'https://www.youtube.com/watch?v=0bFs6ZiynSU' ;

Note: Enclose all arguments with '   ' for parsing safety.

Explanation of recommended switches:

*

*--limit-rate '0.25M' is used to limit the available maximum download speed of every youtube-dl instance in B/s (bytes per second).
Arguments: any positive integer with a capitalized unit suffix.
Unit Suffixes: K for Kilobyte; M for Megabyte; Unclear if Gigabyte is supported.
Addition:
1. avoid internet connection blockage.
    2. helpful when managing download speeds of multiple concurrent ytdl instances.
Ommission:
1. clogs up internet; unable to browse, lagging youtube video play.
    2. will download video as fast as possible.
Note: You can run multiple youtube-dl instances concurrently.

*--retries '5' is used to auto-retry the download of a video if it fails. Useful when downloading a playlist or an entire channel (which is, in Youtube terms, also a playlist (of that specific channel)).
Values: Choose any positive integer. Default is 10. Max is infinite (enter as literal string).

*--continue
Arguments: none
Addition:
1. will force resume downalod of partial files
    Note: ytdl downloads videos in chunks; chunks are preserved if ytdl unexpectedly terminates during download.
Ommission:
1. By default ytdl will resume downloads, if possible.

*--no-overwrites
Arguments: none
Addition: will not overwrite existing metadata files with same names.
Ommission: will overwrite existing metadata files with same names, but not the video file.

*

*--call-home used to contact the ytdl server for debugging.

"If your server has multiple IPs or you suspect censorship, adding --call-home may be a good idea to get more diagnostics." –  Docs: Bugs, retrieved 20180408,

*--write-info-json
Arguments: none
Output Format: json;
Information Content: view count, likes, upload date, video and audio quality information, etc. (but not video text description (posted below video by uploader (2018 youtube layout)))
Addition: writes video metadata into a separate .info.json file. Saved in same folder as video file.
Ommission: does not affect --add-metadata which will still write video metadata to the video output file.

*--write-description
Arguments: none
Output Format: plain text;
Addition: writes text posted by video uploader in the description section of a video (below the video (2018 youtube layout)) into a separate Write .description file. Saved in same folder as video file.

*--write-thumbnail writes highest resolution thumbnail available (called maxresdefault.jpg by youtube) to .jpg file. Renamed according to template specified with --output. Saved in same directory as video file.
Arguments: none
Output Format: only JPEG;
Note: Use youtube-dl --list-thumbnails '<video_url>' to investigate available thumbnails of a specific video (does not work on playlist links); Ex.: youtube-dl --list-thumbnails 'https://www.youtube.com/watch?v=odwfHu6MDuU'

*--write-annotations writes video annotations to .annotations.xml file. Renamed according to template specified with --output. Saved in same directory as video file.
Arguments: none
Output Format: .xml;

*--all-subs writes all custom created available subtitles for a video to their respective files (ex.: subtitles.en.vtt, subtitles.fr.vtt, subtitles.es.vtt)
Arguments: none
Output Format: Default .vtt; can specify other formats with --sub-format
Error Messages:  If there are no subtitles available a WARNING message will be printed to stdout - format: WARNING: video doesn't have subtitles
Useful Command:
Note: Use youtube-dl --list-subs '<video_url>' to investigate available thumbnails of a specific video (does not work on playlist links);
Ex.: youtube-dl --list-subs 'https://www.youtube.com/watch?v=odwfHu6MDuU'

*

*--convert-subs 'srt'
Arguments: String : format extension ass, srt or best
Output Format: Default .vtt; or according to specification
Addition: writes subtitles to specified file format (ex.: .srt). Saved in same folder as video file.
Ommission: subtitles will be written as .vtt
Error Messages: If there are no subtitles available an INFO message will be printed to stdout - format: [ffmpeg] There aren't any subtitles to convert
Note: conversion will be executed as a post-processing step on the .vtt file after download. If ytdl execution is terminated unexpectedly some subtitle files might not be converted (in this case execute command again).

*--add-metadata
Arguments: none
Behavior: writes metadata to video output file.
Note: does not require a .info.json generated by --write-info-json

*--embed-subs
Arguments: none
Behavior:
1. writes subtitles to video output file;
    2. only for mp4, webm and mkv videos
Error Messages:  If there are no subtitles available a INFO message will be printed to stdout - format: [ffmpeg] There aren't any subtitles to embed
Note: does not require a .vtt generated by --write-sub,
--write-auto-sub or --all-sub

*--download-archive '<archive_path>/<channel_name>/<channel_name>.ytdlarchive'
Behavior: is used to create a text file containing links of previously downloaded videos. Allows skipping these videos when downloading an entire channel. Not necessary when downloading single videos only.
Arguments: String : composite of the path to your video archive, directory named after channel. File name consists of channel name with .ytdlarchive file extension. (could also be .txt; but unique format allows for easy differentiation)
Output Format: plain text; one videoID per line
Addition:
1. ytdl reads this file, ignores and skips all videos listed with their videoID in it, even if no downloaded yet.
    2. automatically adds the videoID of the last downloaded video to this file
Ommission: if video file and metadata files exist ytdl will download them again.

*--format ''
Arguments: Recommended String : bestvideo+bestaudio/best to ensure highest video and audio quality combination.
Addition: full control over video quality and audio quality and their combinations, as well as fallback qualities
Ommission: Default youtube-dl will guess it for you by default – Docs
Note: See Docs: Format Selection Examples

*--merge-output-format '<video_format>'
Arguments: video file format. (ex.: mp4, mkv, 3gp, etc.)
Addition: can specify video file format
Ommission: Default youtube-dl will guess it for you by default – Docs
Note: See Docs: Format Selection
Useful Command:
Note: Use youtube-dl --list-formats '<video_url>' to investigate available video and audio qualities and formats of a specific video (does not work on playlist links);
Ex.: youtube-dl --list-formats 'https://www.youtube.com/watch?v=odwfHu6MDuU'

*

*--output '<template>'
Arguments:
1. video file format. (ex.: mp4, mkv, 3gp, etc.);
    2. Recommended: %(upload_date)s_%(id)s_%(title)s.%(ext)s
Addition: influences file naming convention for video files and all metadata files
Ommission: By default the video title will be the file name. Default template: %(id)s.%(ext)s will output ex.: testvideo.mkv
Note: Do not forget the % prefix and s suffix (other suffices exist too.); Thee _ between template elements is just a separator and can be any other char. ex.: %(upload_date)s-%(id)s
Note: See Docs: Output Template

*'<video_url>'
Arguments: String : url to specific video
Error Message:
1. If no video url submitted ytdl will not execute and display help.
    2. If invalid video url submitted ERROR message will be printed to stdout - format: ERROR: u'' is not a valid URL. Set --default-search "ytsearch" (or run  youtube-dl "ytsearch:" ) to search YouTube

Storage Recommendations:

*

*make a misc directory in your video archive and store all single videos in there.

*when you download one or more videos from a channel make a dedicated directory for that channel. In this case, the channel name is TED Archive and the directory name will be TED_Archive. (I preemptively substitute all space characters with underscores for easier directory navigation and file I/O actions when using bash (or python) scripts).

Responding to your comment @leetbacoon

And just wondering, why is a 1080p copy considered the best if 1440p is available? And why is 2160p displayed? That option doesn't appear on my end (it caps at 1440p) – leetbacoon

From the Docs

You can also use a file extension (currently 3gp, aac, flv, m4a, mp3, mp4, ogg, wav, webm are supported) to download the best quality format of a particular file extension served as a single file
best: Select the best quality format represented by a single file with video and audio.
bestvideo: Select the best quality video-only format
I think when you select just best and you specify an output format youtube sends the format it thinks is the best video+audio combo for that format. This might be subject to some youtube internal balancing decisions (speculation).
In my usage experience, I have had to specifically specify bestvideo+bestaudio to get the HIGHEST quality available of video and audio respectively and then combine them in a .mkv container.
I use /best as a fallback argument just to be sure.

A: The relevant options you need:
# Filesystem
--write-annotations
--write-description
--write-info-json

# Thumbnail images
--write-all-thumbnails

# Video format
--format bestvideo+bestaudio/best
--merge-output-format mkv

# Subtitle
--all-subs
--write-auto-sub
--write-sub

# Post-processing
--add-metadata
--embed-subs

Copy that to your config file (either /etc/youtube-dl.conf or ~/.config/youtube-dl/config).
Using that configuration, I downloaded this video and youtube-dl wrote the following files:
$ ls
The Problem with Time & Timezones - Computerphile.annotations.xml
The Problem with Time & Timezones - Computerphile.description
The Problem with Time & Timezones - Computerphile.info.json
The Problem with Time & Timezones - Computerphile.jpg
The Problem with Time & Timezones - Computerphile.mkv

I can't post mediainfo's output here because it exceeds the characters limit, but you can see it in github.

I also want to download the video/audio in the highest quality possible, with no quality loss.

youtube-dl downloads videos at the highest quality possible by default, but you can force this behavior using --format bestvideo+bestaudio/best.

Even though it's not YouTube, I did also want to download some of my udemy courses I've bought so I can watch them while I'm on a long road trip.

Please read the article Can I Download a Course to my Computer?:

By default, complete courses are not downloadable from a computer. We do this out of concerns for piracy.
Please note that you can always save courses for offline viewing on the Udemy mobile app. For information on how to download video lectures to your iOS mobile device, please click here. For steps on how to download videos for offline viewing on an Android device, click here.

I have ffmpeg installed, and I heard that you need this for lossless downloads from YouTube, but I'm not sure how to link it with youtube-dl.

youtube-dl uses avconv by default, but --prefer-ffmpeg let you use ffmpeg instead. Anyway, this option is not needed for "lossless downloads". In the example I provided, youtube-dl only used ffmpeg to merge all the downloaded formats into a single mkv file.

A: To simply download the video, you can use this:
youtube-dl --all-subs "https://www.youtube.com/watch?v=KYBok-XGsKM"

To select the video quality, you should first use the -F option to list the available formats.
youtube-dl -F "https://www.youtube.com/watch?v=KYBok-XGsKM"

And this is the output for your video:
[youtube] KYBok-XGsKM: Downloading webpage
[youtube] KYBok-XGsKM: Downloading video info webpage
[youtube] KYBok-XGsKM: Extracting video information
WARNING: unable to extract uploader nickname
[info] Available formats for KYBok-XGsKM:
format code  extension  resolution note
249          webm       audio only DASH audio   52k , opus @ 50k,  4.19MiB
250          webm       audio only DASH audio   75k , opus @ 70k, 5.42MiB
140          m4a        audio only DASH audio  129k , m4a_dash container, mp4a.40.2@128k, 10.59MiB
171          webm       audio only DASH audio  131k , vorbis@128k, 7.66MiB
251          webm       audio only DASH audio  135k , opus @160k, 9.58MiB
278          webm       256x144    144p   98k , webm container, vp9, 30fps, video only, 6.59MiB
160          mp4        256x144    144p  114k , avc1.4d400c, 15fps, video only, 9.04MiB
242          webm       426x240    240p  205k , vp9, 30fps, video only, 11.47MiB
133          mp4        426x240    240p  265k , avc1.4d4015, 30fps, video only, 20.11MiB
243          webm       640x360    360p  362k , vp9, 30fps, video only, 21.93MiB
134          mp4        640x360    360p  602k , avc1.4d401e, 30fps, video only, 20.42MiB
244          webm       854x480    480p  662k , vp9, 30fps, video only, 37.82MiB
135          mp4        854x480    480p 1020k , avc1.4d401f, 30fps, video only, 42.62MiB
247          webm       1280x720   720p 1353k , vp9, 30fps, video only, 81.53MiB
136          mp4        1280x720   720p 2013k , avc1.4d401f, 30fps, video only, 84.69MiB
137          mp4        1920x1080  1080p 2438k , avc1.640028, 30fps, video only, 157.71MiB
248          webm       1920x1080  1080p 2593k , vp9, 30fps, video only, 162.48MiB
264          mp4        2560x1440  1440p 6973k , avc1.640032, 30fps, video only, 459.58MiB
271          webm       2560x1440  1440p 7523k , vp9, 30fps, video only, 485.66MiB
313          webm       3840x2160  2160p 19991k , vp9, 30fps, video only, 1.34GiB
36           3gp        320x?      small , mp4v.20.3,  mp4a.40.2
17           3gp        176x144    small , mp4v.20.3,  mp4a.40.2@ 24k
43           webm       640x360    medium , vp8.0,  vorbis@128k
18           mp4        640x360    medium , avc1.42001E,  mp4a.40.2@ 96k
22           mp4        1280x720   hd720 , avc1.64001F,  mp4a.40.2@192k (best)

Here are some useful options for subtitles:
   --write-sub
          Write subtitle file

   --write-auto-sub
          Write automatically generated subtitle file (YouTube only)

   --all-subs
          Download all the available subtitles of the video

   --list-subs
          List all available subtitles for the video

And for thumbnails:
   --write-thumbnail
          Write thumbnail image to disk

   --write-all-thumbnails
          Write all thumbnail image formats to disk

   --list-thumbnails
          Simulate and list all available thumbnail formats

You can also find more information about the quality of video here


text:
Q: Process Explorer: huge I/O bytes with small Network/Disk Bytes What does it means when process explorer show me a huge I/O Bytes pre second but mean while a low Network and Disk Bytes pre second?
I have a machine here that the process explorer (v14) showing me

*

*I/O Bytes: 130~600GB/s

*Network Bytes: up to 20MB/s

*Disk Bytes: less then 1MB/s


text: Q: React.js - converting JSX to raw HTML string I am currently thinking about making a CMS project and one of the features I want to add is making a HTML page by clicking on buttons then storing that HTML in a JSON, of course in a string format. The way I want to make this is pretty easy, on a certain button click it adds the JSX element and renders it real time so the user says what he is building. Lets say the user then has to click a button that will save that page to the json. Is there any way I can convert JSX elements to a raw HTML string so I can save it to json or do I manually have to keep on adding to a string when making JSX elements and create the raw HTML myself?


text:
Q: Using WPF to display XML I have a small project that I think WPF would be perfect for, I don't however have that much time so I am looking for feasibility information and pointers. I am trying to display a large number of items from an XML document and from what I have read so far I believe it would be possible to:
Use the XML document as a dataSource.
Load each item from the XML into an object, which is then added to a collection. (Is it possible to bind the XML straight to the collection?)
Using the collection bind it to a view.
Each object in the view is displayed in a similar fashion to that of an HTML table. (Use a custom control in stackPanel vertically?)
There may be thousands of objects within the collection so need to be be able to display only 50/page with the ability to sort and search. (Using collectionView?)
I have seen similar scenarios and examples on the web but most are watered down, I don't want to start this and then hit a brick wall when I could create a web based solution.
If anyone could tell me if it's possible, point me in the right direction or highlight any potential problem areas it would be appreciated.
Thanks.

A: Consider this sample xml file:
<Employees>
  <Employee ID="101">
    <Name>Ram</Name>
    <Salary>5000</Salary>
  </Employee>
  <Employee ID="102">
    <Name>Siva</Name>
    <Salary>7000</Salary>
  ...
</Employee>

You can load the data from an xml file like this:
XDocument doc = XDocument.Load(yourFilePath);

Then you can query it like this:
var filterQuery = from i in doc.Descendants("someNode")
                  where (float)i.Element("Salary") >= 6000.00
                  orderby (string)i.Element("Name")
                  select (string)i.Element("Name");

Create an ObservableCollection out of it
var filteredList = new ObservableCollection(filterQuery);

Bind this to your ListView or other Collection in xaml.
You can implement sorting and searching logics on the doc and re-populate your ObservableCollection anytime and the changes would be automatically reflected in the ListView.


text:
Q: Windows 10 or Ubuntu doesn't work I used Ubuntu and then now my Windows 10 and Ubuntu doesn't work and my hard drive and it keeps taking me back to the bios system.
If I don't press F2 or del button it takes me to the Ubuntu and then says install Ubuntu. When I select install it long log comes up and it just freezes.
Please help it's urgent and my Windows boot manager is gone too.

A: The first line in the picture initram's unpacking failed may be caused by faulty RAM. Reboot and press ESC on the boot menu and run a memory test.


text:
Q: Problem with parsing xml from a string in Android I want to parse an XML from a string. This is working fine when the string length is small. But for a long string it is not parsing anything. It is suspended on calling parse(). I use the following code for parsing. Please tell me what is the wrong with my code?
        //my xml code is string 'xmlString'
         DocumentBuilderFactory objDocFactory=DocumentBuilderFactory.newInstance();
         DocumentBuilder objDocBuilder=objDocFactory.newDocumentBuilder();
         InputSource objInput=new InputSource();
         objInput.setCharacterStream(new StringReader(xmlString));
         Document objDoc=objDocBuilder.parse(objInput);
         //appication is suspended at the above line
         objDoc.getDocumentElement().normalize();

Thank you...

A: How large is the document?
I have used TinyXML parser for Android, and am pretty satisfied with the result. Maybe you can check it out once.
Best part is it is pretty ease to use, and the learning curve is considerably less.

A: Exactly what Keith said.  Using DOM it's trying to load the entire document into memory, which is not the best thing on a mobile device.  SAX will stream the data so it will only use a little memory.